[英]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.