简体   繁体   English

Tkinter 背景图片不显示

[英]Tkinter Background Image not showing up

I am trying to create a weather App in Tkinter GUI.我正在尝试在 Tkinter GUI 中创建一个天气应用程序。 It is working fine.它工作正常。 I want to add a background image to it but it wont show up.我想给它添加一个背景图像,但它不会显示。 initially i did it without the reference line but it didnt work.最初我在没有参考线的情况下做到了,但它没有用。 On some website they said to keep reference of the image but that too didnt work.在一些网站上,他们说要保留图像的参考,但这也没有用。 Also my Tkinter window size is 1920x1080 and the image was of same dimension but it still doesnt show up.此外,我的 Tkinter window 尺寸为 1920x1080,图像尺寸相同,但仍未显示。 I tried to reduce image size than window but still not working.我试图将图像尺寸缩小到 window 但仍然无法正常工作。 Any suggestions accepted.接受任何建议。 Also there is no error.也没有错误。

bg = PhotoImage('clearsky2.jpg')
bgl = Label(gui,image=bg)
bgl.image = bg #given a reference
bgl.place(x=0, y=0, relwidth=1,relheight=1)
bgl.pack()

Its sad that tkinter.PhotoImage does not support JPEG files, but it does support PNG in the newer version and has proper support for GIF too.遗憾的是tkinter.PhotoImage不支持JPEG文件,但它在较新版本中支持PNG ,并且对GIF也有适当的支持。 To use JPEG you need PIL installed.要使用JPEG ,您需要安装PIL In the terminal say:在终端说:

pip install Pillow

After that import it like:之后像这样导入它:

from PIL import Image,ImageTk

Then now, to open the image with PIL, say:那么现在,要使用 PIL 打开图像,请说:

img_file = Image.open('clearsky2.jpg')
bg = ImageTk.PhotoImage(img_file)
bgl = Label(gui,image=bg)
bgl.place(x=0, y=0, relwidth=1,relheight=1)

This will work with JPEG and PNG files as well and, keep in mind you dont need to keep a reference unless your looping over images or creating image inside of a function.这也适用于JPEGPNG文件,请记住您不需要保留参考,除非您循环处理图像或在 function 中创建图像。

Hope it cleared your problem, do let me know if any more errors希望它解决了你的问题,如果还有错误请告诉我

Cheers干杯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM