在python中使用(GUI)Tkinter显示图像时出错

时间:2018-05-16 10:36:07

标签: python image user-interface tkinter label

当我尝试运行以下代码时,它显示错误:
追溯(最近的呼叫最后):
_tkinter.TclError:无法识别图像文件“logo.png”中的数据
代码:

from Tkinter import *


root = Tk()
root.geometry('300x200')
f0 = Frame(root,width=300, height=50)
f0.pack()
logo = PhotoImage(file='logo.png')
lb1 = Label(f0,image=logo).pack()

f1 = Frame(root)
f1.pack()
label = Label(f1, text="Email")
label.grid(row=1,column=1)

wb1 = Entry(f1, bd = 5)
wb1.grid(row=1,column=2)
label2 = Label(f1,text="Password")
label2.grid(row=2,column=1) 
wb2 = Entry(f1,show='*',bd = 5)
wb2.grid(row=2,column=2)
label3 = Label(f1,text="Bug ID")
label3.grid(row=3,column=1)
wb3 = Entry(f1, bd = 5)
wb3.grid(row=3,column=2)

f2 = Frame(root) 
f2.pack()

def printdata():
     st = "Hello, Work in progress.."
     lab2 = Label(f2, text=st)
     lab2.grid(row=2, column=2)


but1 = Button(f2,text="Automate it", bg="blue", fg="white", 
command=printdata)
but1.grid(row=1,column=2)
root.mainloop()

有人可以建议,我在这里可能犯的错误是什么? 提前谢谢。

2 个答案:

答案 0 :(得分:1)

我认为这应该解决它(有关此reference的详细信息):

from PIL import Image, ImageTk

image = Image.open("logo.png")
logo = ImageTk.PhotoImage(image)

lb1 = Label(f0,image=logo)
lb1.image = logo #keep a reference to it
lb1.pack()

编辑:

我认为您的tkinter版本可以直接运行:

logo = ImageTk.PhotoImage("logo.png")

lb1 = Label(f0,image=logo)
lb1.image = logo #keep a reference to it
lb1.pack()

答案 1 :(得分:0)

pack移至换行符

logo = PhotoImage(file='logo.png')
lb1 = Label(f0,image=logo)
lbl.pack()