不确定如何在Tkinter中设置背景图像

时间:2018-10-19 13:16:49

标签: python tkinter

在我开始之前,我确实知道有一个关于我的问题的帖子here, 但是,这并不能完全帮助我,即使按照帖子中的答案进行操作,我似乎仍然遇到问题。

我似乎遇到了两种不同的“错误”

一个错误,表明图像文件不可读。使用此代码时给出的结果(这是另一篇文章给出的答案):

self.background_image=tk.PhotoImage…
self.background_label = tk.Label(parent, image=background_image)
self.background_label.place(x=0, y=0, relwidth=1, relheight=1)

和另一个“错误”,当使用以下代码时,没有图像显示,但没有给出真正的错误消息:

self.background_image = tk.PhotoImage(r'C:/hazuki-gui/resources/background1.png')
self.background_label = tk.Label(image=self.background_image)
self.background_label.place(x=0,y=0)

我环顾四周,一切都显示了我上面显示的第一种方式。 我尝试同时使用pngjpg图像,但是在两种情况下都返回相同的结果。

任何对此的帮助,将不胜感激。

侧面说明:如果在python 2.7和python 3.x上执行此操作有任何区别,请告诉我(当前我正在使用python 2.7,但将其移至3.x)

1 个答案:

答案 0 :(得分:0)

也许由于没有引用您的图片,所以您的图片被垃圾回收了?

self.background_image = tk.PhotoImage(file=r'C:/hazuki-gui/resources/background1.png')
self.background_label = tk.Label(image=self.background_image)
self.background_label.place(x=0,y=0)
self.background_label.img = self.background_image #try to add this