为什么python photoimages不存在?

Alb*_*lla 2 python image tkinter

我将展示代码的减少部分,这给我一个问题.

"_tkinter.TclError:image"pyimageN"不存在" - 其中N保持1或2或3等...

有一个第一类显示在后台使用图像的菜单.

class MenuWindow():    #in this class we show the main part of the program
    def __init__(self):
        self.Menu=Tk()
        self.MCanvas=Canvas(self.Menu)
        self.MCanvas.bind("<ButtonPress-1>",self.MenuClick)

        #unuseful lines that configure the window and the canvas#

        self.Background=PhotoImage(height=600,width=700)#a simple tkinter.PhotoImage object

        #other unuseful lines that draw the photoimage ( without reading any file, with the method put())#

        self.MCanvas.create_image((x,y),image=self.Background,state="normal")

        #unuseful lines that continue the drawing of the canvas#
Run Code Online (Sandbox Code Playgroud)

第二个类显示另一个窗口,在后台使用另一个图像.这个类是由第一个类通过函数self.MenuClick的点击绑定启动的.

class EditorWindow():    #in this class we show the main part of the program
    def __init__(self):
        self.Eenu=Tk()
        self.ECanvas=Canvas(self.Eenu)

        #unuseful lines that configure the window and the canvas#

        self.Background=PhotoImage(height=600,width=700)

        #other unuseful lines that draw the photoimage ( without reading any file , with the method put() )#

        self.ECanvas.create_image((x,y),image=self.Background,state="normal")#in this line i get the error

        #unuseful lines that continue the drawing of the canvas#
Run Code Online (Sandbox Code Playgroud)

完成回溯如下:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/tkinter/__init__.py", line 1399, in __call__
    return self.func(*args)
  File "/Users/albertoperrella/Desktop/slay.py", line 70, in MenuClick
    EditorWindow(self)
  File "/Users/albertoperrella/Desktop/slay.py", line 85, in __init__
    self.ECanvas.create_image((3,3),image=self.Background,state="normal",anchor="nw")
  File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/tkinter/__init__.py", line 2140, in create_image
    return self._create('image', args, kw)
  File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/tkinter/__init__.py", line 2131, in _create
    *(args + self._options(cnf, kw))))
_tkinter.TclError: image "pyimage2" doesn't exist
Run Code Online (Sandbox Code Playgroud)

这两个类是以类似的方式制作的,所以我不知道为什么我得到第二个错误.我确信这不是写错误,例如(构造而不是构造)并且我正在使用的图像实际上存在.

所以我认为:

  • 我犯了一些概念错误,

  • 或者它是python中的一个bug(或TkInter的微妙行为)

Alb*_*lla 5

我解决了自己的问题:

我定义的第二个类是问题,因为它使用另一个根窗口,别名Tk().等效于普通Tk()窗口的是Toplevel(),它与根相同但没有自己的解释器上下文.

很快,为了解决这个问题,我不得不改变EditorWindow类的init()方法的fisrt行

        self.Eenu=Tk()
Run Code Online (Sandbox Code Playgroud)

        self.Eenu=Toplevel() 
Run Code Online (Sandbox Code Playgroud)

  • 正确 - 你不能有两个 `Tk` 实例。一个实例,并只调用一次“mainloop”。 (2认同)