这是我编写的代码,在其他用户的帮助下,我修复了以前的错误。但是这一点让我感到难过。这是我的代码
我在我认为是问题的区域周围放置了注释标记。为了解决这个问题,我已经阅读了一些资料,但没有得到任何结果。
import tkinter as tk
import sys
from timeit import default_timer as timer
import time
from PIL import ImageTk, Image
tot_time=0
del_time=0
imgpath=r'logo.jpg'
def NewTab():
start=timer()
time.sleep(del_time) #user defined delay time
window.withdraw()
win2.deiconify()
end=timer()
tot_time=end-start
labW2.configure(text=('That took %s miliseconds or %s seconds'%(str(round(tot_time*1000,5)),str(round(tot_time,5)))))
def close():
sys.exit()
def NTButt():
win2.withdraw()
window.deiconify()
win2=tk.Tk()
win2.geometry('1100x900')
win2.title('Button Click')
labW2=tk.Label(win2, text='ERROR: Time could not be calculated')
butW2=tk.Button(win2, text='Go back', bg='White', command=NTButt)
btn2W2=tk.Button(win2, text='Leave', bg='Red', command=close)
labW2.pack()
butW2.pack()
btn2W2.pack()
win2.withdraw()
window=tk.Tk()
window.geometry('1100x900')
window.title('Hello World')
lab1= tk.Label(window, text='Input the desired delay time')
ent=tk.Entry(window)
btn=tk.Button(window, text='Go to new window', bg='Blue', command=NewTab)
btn2=tk.Button(window, text='Leave', bg='Red', command=close)
###############################################
imgset=ImageTk.PhotoImage(Image.open(imgpath))
photo = ImageTk.PhotoImage(imgset)
labimg = tk.Label(window, image=photo)
labimg.image = photo
labimg.pack()
###############################################
lab1.pack()
ent.pack()
btn.pack()
btn2.pack()
window.mainloop()
包括我收到的错误消息
Traceback (most recent call last):
File "C:\PythonScripts\trunk\Personal\PythonWindow_ForTiming.py", line 53, in <module>
photo = ImageTk.PhotoImage(imgset)
File "C:\Python34\lib\site-packages\PIL\ImageTk.py", line 106, in __init__
mode = Image.getmodebase(mode)
File "C:\Python34\lib\site-packages\PIL\Image.py", line 290, in getmodebase
return ImageMode.getmode(mode).basemode
File "C:\Python34\lib\site-packages\PIL\ImageMode.py", line 50, in getmode
return _modes[mode]
KeyError: <PIL.ImageTk.PhotoImage object at 0x0000000002A06208>
Exception ignored in: <bound method PhotoImage.__del__ of <PIL.ImageTk.PhotoImage object at 0x0000000002DC45C0>>
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\PIL\ImageTk.py", line 116, in __del__
name = self.__photo.name
AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'
我是tkinter的新手,这可能只是我的错误,请评论解决方案以帮助我理解。提前致谢
最佳答案
我不是TKinter专家,但似乎引起异常的那一行是:photo = ImageTk.PhotoImage(imgset)
不需要;您已经在上一行中加载了图像。
引发异常是因为您要将ImageTk.PhotoImage()
的实例传递给ImageTk.PhotoImage()
因此,有问题的代码变为:
###############################################
photo = ImageTk.PhotoImage(Image.open(imgpath))
labimg = tk.Label(window, image=photo)
labimg.image = photo
labimg.pack()
###############################################
关于python - 如何在python3.4中使用ImageTk和Tkinter修复AttributeError?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38075488/