【问题标题】:tkinter picture error: "images may not be named same as on main window"tkinter 图片错误:“图像的名称可能与主窗口上的名称不同”
【发布时间】:2015-03-02 13:37:56
【问题描述】:

我正在尝试编写一个 tkinter 版本的 Flappy Bird,但在使用 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
>>> 

【问题讨论】:

  • 大胆猜测:试试bird = PhotoImage(file="L:\\Programming\\Python\\flappyBird\\bird.png")
  • 哇。我不敢相信我以前没有尝试过。出于某种奇怪的原因,这奏效了。谢谢

标签: python-3.x tkinter tkinter-canvas


【解决方案1】:

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

bird = PhotoImage(file="L:\\Programming\\Python\\flappyBird\\bird.png")

【讨论】:

    【解决方案2】:

    PhotoImage 构造函数中的第一个关键字参数是name。通过将root 作为第一个位置参数传递,它与name 关键字参数相关联。因此,您正在尝试创建一个与根窗口同名的小部件,因此错误“图像可能与主窗口命名不同”

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 2014-08-17
      • 1970-01-01
      • 1970-01-01
      • 2019-11-13
      • 1970-01-01
      相关资源
      最近更新 更多