tkinter picture error: "images may not be named same as on main window"

tkinter picture error: "images may not be named same as on main window"

我正在尝试编写 flappy bird 的 tkinter 版本,但在使用 tkinter 时遇到了一个我以前从未见过的错误。我到处搜索,并尝试了我能想到的一切。到目前为止,这是我的代码:

from tkinter import *
root = Tk()
canvas = Canvas(root, height=400, width=400)
canvas.pack()
bird = PhotoImage(root, file="L:\Programming\Python\flappyBird\bird.png")

这是错误:

Traceback (most recent call last):
  File "L:\Programming\Python\flappyBird\flappyBird.py", line 5, in <module>
    bird = PhotoImage(root, file="L:\Programming\Python\flappyBird\bird.png")
  File "C:\Python34\lib\tkinter\__init__.py", line 3384, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "C:\Python34\lib\tkinter\__init__.py", line 3340, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: images may not be named the same as the main window
>>> 

查看 PhotoImage 的文档,似乎不建议提供任何位置参数。尝试在没有 root.

的情况下创建它
bird = PhotoImage(file="L:\Programming\Python\flappyBird\bird.png")

PhotoImage 构造函数中的第一个关键字参数是 name。通过将 root 作为第一个位置参数传递,它与 name 关键字参数相关联。因此,您正在尝试创建一个与根 window 同名的小部件,因此出现错误 "images may not be named the same as the main window"

在创建图像时省略 root 作为第一个参数,问题就会消失。