我在使用在屏幕上显示图像两秒钟然后被破坏的功能时遇到问题。当程序运行函数时,初始调用过程正常,但如果随后通过 tkinter 中内置的按钮调用函数,我会收到错误消息。
appcwd = os.getcwd()
user32 = ctypes.windll.user32
screensize = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)
size = str(screensize[0])+'x'+str(screensize[1])
def wlcm_scrn(event=None):
def destroy_wlcm(event=None):
wlcm_scrn.destroy()
global appcwd
global screensize
wlcm_scrn = tkinter.Tk()
file=appcwd+"\\Run_Files\\splash.gif"
splsh_img = tkinter.PhotoImage(file=file)
splosh = tkinter.Label(wlcm_scrn,image=splsh_img)
wlcmh = splsh_img.height()/2
wlcmw = splsh_img.width()/2
splosh.pack()
wlcm_scrn.config(bg='black')
wlcm_scrn.overrideredirect(True)
wlcm_scrn.bind("<Escape>",destroy_wlcm)
wlxym = '+'+str(int((screensize[0]/2)-wlcmw))+'+'+str(int((screensize[1]/2)-wlcmh))
wlcm_scrn.geometry(wlxym)
wlcm_scrn.wm_attributes("-topmost", 1)
wlcm_scrn.after(2000,destroy_wlcm)
wlcm_scrn.mainloop()
wlcm_scrn() #Call through procedure.
调用函数的按钮。
view_img = tkinter.Button(cfrm,text='Show splash image',command=wlcm_scrn)
通过按钮命令调用时出现错误消息。
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python33\lib\tkinter__init__.py", line 1475, in __call__
return self.func(*args)
File "C:\Python33\POS_Solution\Rattle_Hum_POS.py", line 1755, in run_wlcm_scrn
wlcm_scrn()
File "C:\Python33\POS_Solution\Rattle_Hum_POS.py", line 34, in wlcm_scrn
splosh = tkinter.Label(wlcm_scrn,image=splsh_img)
File "C:\Python33\lib\tkinter__init__.py", line 2596, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "C:\Python33\lib\tkinter__init__.py", line 2075, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image "pyimage3" doesn't exist
什么是“pyimage3”,为什么不存在?任何帮助将不胜感激。谢谢。
原文由 I_do_python 发布,翻译遵循 CC BY-SA 4.0 许可协议
我发现了这个问题,所以我想我会为将来遇到这个问题的任何人回答自己。
当 wlcm_scrn 按程序运行时,它是当时唯一存在的窗口,因此它可以使用 tkinter.Tk()。出现错误是因为调用该函数的按钮本身位于一个活动窗口中,该窗口也作为 Tkinter.Tk() 运行。因此,当 Python/Tkinter 尝试从按钮构建 wlcm_scrn 时,它实质上是在尝试在 root 下创建两个窗口并崩溃。
解决方案:
换线…
对这个…
…停止错误,并显示图像。
我个人将有两个函数实例。一种在 Tk() 下按程序调用,另一种在 TopLevel() 下在应用程序内调用。