本文共 1368 字,大约阅读时间需要 4 分钟。
tkinter 使用 Label 显示 png、jpg 不能成功显示,但是不报错。
所以问题应该出在图片的读取上。
源代码如下:
class Window: …… def window(): …… self.imglabel = tk.Label(window, image=image) self.imglabel.grid(row=4, column=1) …… def show_lossImg(): img = Image.open("test.png") image = ImageTk.PhotoImage(img) self.imglabel.config(image=image) #或者 self.imglabel["image"]=image
因为定义img 和 image
的位置与主窗口定义位置不在一处(主窗口定义在主函数中,两个变量定义在子函数中),所以子函数执行结束,返回主函数时,两个变量作用域已经超出范围。
1、在函数名下面加上global img, image
即可
class Window: …… def window(): …… self.imglabel = tk.Label(window, image=image) self.imglabel.grid(row=4, column=1) …… def show_lossImg(): global img, image img = Image.open("test.png") image = ImageTk.PhotoImage(img) self.imglabel.config(image=image) #或者 self.imglabel["image"]=image
2、如果上述方法没有起作用,尝试为self.imglabel
加背景颜色:self.imglabel.config(bg="red")
。如果能正常显示背景颜色,说明图片已经正常显示,但是因为图片太大,所以和没有正常显示一样。
resize
图片就可以了。如下: class Window: …… def window(): …… self.imglabel = tk.Label(window, image=image) self.imglabel.grid(row=4, column=1) …… def show_lossImg(): global img, image img = Image.open("test.png") # resize 图片 image = ImageTk.PhotoImage(img.resize((50, 50))) self.imglabel.config(image=image) #为图片设置背景 self.imglabel.config(bg="red")
转载地址:http://opqqf.baihongyu.com/