Tkinter RuntimeError: Too early to create image:没有默认根窗口



所以我试图在python中绘制图像到更大的画布,并不断在标题中获得错误。我有一个tkinter.Tk()的参考,我已经将其设置为画布的主,我已经打包了画布,并运行主循环。这一切都发生在程序启动时。然后,我调用main.py中的gui.drawentity(),它尝试创建一个图像并将其绘制到画布上。

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()

main.py

e = player.Player(100, 200, "Ball_Grayed.png", 3)
gui.drawentity(e)

data.py

cd = os.path.join(os.getcwd(), "resources")
def getimagepath(imgName, imgType):
return os.path.join(cd, imgType, imgName)

当运行py main.py时,我得到以下输出:

File "S:UsersSeanGoogle DrivecspersonalBallAdventuremain.py", line 12, in <module>
gui.drawentity(e)
File "S:UsersSeanGoogle DrivecspersonalBallAdventuregui.py", line 22, in drawentity
img = tk.PhotoImage(imgPath)
File "C:UsersSeanAppDataLocalProgramsPythonPython310libtkinter__init__.py", line 4093, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:UsersSeanAppDataLocalProgramsPythonPython310libtkinter__init__.py", line 4026, in __init__
master = _get_default_root('create image')
File "C:UsersSeanAppDataLocalProgramsPythonPython310libtkinter__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
在我看来一切都很好,有人能看出问题是什么吗?

(参见Nesi的评论)

似乎tk.mainloop()调用阻塞了(程序的执行停止在那里)。我只是在退出窗口后才得到错误,这是有意义的,因为当调用mainloop()时,程序基本上进入while True循环。由于我已经手动销毁了默认的根窗口,因此在继续代码时没有什么可借鉴的。

所以,要小心放置mainloop()的位置,并且要知道它会阻塞

(源/更多信息)

最新更新