[英]Tkinter RuntimeError: Too early to create image: no default root window
所以我试图在 python 中将图像绘制到 tkinter canvas 中,并不断收到标题中的错误。 我有一个参考tkinter.Tk()
,我把它设置为画布的主人,我已经打包了 canvas,并运行了主循环。 这一切都发生在程序启动时。 然后,我在 main.py 中调用gui.drawentity()
,它尝试创建一个图像并将其绘制到 canvas。
gui.py
root = tk.Tk()
canvas = tk.Canvas(root, bg="green")
canvas.pack(fill=tk.BOTH, expand=True)
root.mainloop()
def drawentity(entity):
imgPath = data.getimagepath(entity.img, entity.imgType)
img = None
try:
img = tk.PhotoImage(imgPath)
canvas.create_image(entity.x, entity.y, img)
except IOError as e: print(e)
finally:
if not isinstance(img, type(None)): img.close()
主文件
e = player.Player(100, 200, "Ball_Grayed.png", 3)
gui.drawentity(e)
数据.py
cd = os.path.join(os.getcwd(), "resources")
def getimagepath(imgName, imgType):
return os.path.join(cd, imgType, imgName)
运行py main.py
时,我得到以下 output:
File "S:\Users\Sean\Google Drive\cs\personal\BallAdventure\main.py", line 12, in <module>
gui.drawentity(e)
File "S:\Users\Sean\Google Drive\cs\personal\BallAdventure\gui.py", line 22, in drawentity
img = tk.PhotoImage(imgPath)
File "C:\Users\Sean\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 4093, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Users\Sean\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 4026, in __init__
master = _get_default_root('create image')
File "C:\Users\Sean\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 297, in _get_default_root
raise RuntimeError(f"Too early to {what}: no default root window")
RuntimeError: Too early to create image: no default root window
在我看来一切都很好,有人能看出问题所在吗?
(见内西的评论)
似乎tk.mainloop()
调用块(程序的执行在那里停止)。 我只是在退出 window 后才收到错误消息,这是有道理的,因为在调用mainloop()
时程序本质上进入了一个while True
循环。 由于我一直在手动销毁默认根 window,因此在继续代码时没有什么可借鉴的。
因此,请注意放置mainloop()
的位置,并知道它会阻塞。
(来源/更多信息)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.