进行python的可视化编程时,在另一个模块的类下面写一个调用窗口希望在Tkinter的button上显示图片,但是总是出现错误,而在主函数里面写下以下代码确能显示希望得到的效果。出现错误:关于TclError: image "pyimage1" doesn't exist的解决
代码如下:
def GameMainWin(self,newwindowTk):
newwindowTk=Tk()
newwindowTk.geometry('800x600')
## newwindowframe=Frame(newwindowTk,relief=GROOVE,borderwidth=2,bg='red',height = 20,width = 400)
## newwindowframe.pack()
image= Image.open("syspic/startpic.jpg")
## self.image= PhotoImage(file="syspic/startpicorigin1.gif")
photo = ImageTk.PhotoImage(image)
button=Button(newwindowTk,image=photo,text="waring",command=newwindowTk.quit)
button.image=photo
button.pack()
newwindowTk.mainloop()
于是在网上对寻找该问题的解决方法,然后找到以下一段解释
a common reason for this is that you have multiple Tk instances in
your application.
if you create a PhotoImage under one Tk instance, you cannot access
it from other instances.
to fix this, make sure you only use one Tk instance (use Toplevel to create
new toplevel windows), or make sure that you create the image under the
same instance as the widget you're going to use it in. the easiest way to
do
this is to pass in a master keyword argument to the PhotoImage constructor:
photo = PhotoImage(..., master=myroot)
button = Button(myroot, ...)
your application.
if you create a PhotoImage under one Tk instance, you cannot access
it from other instances.
to fix this, make sure you only use one Tk instance (use Toplevel to create
new toplevel windows), or make sure that you create the image under the
same instance as the widget you're going to use it in. the easiest way to
do
this is to pass in a master keyword argument to the PhotoImage constructor:
photo = PhotoImage(..., master=myroot)
button = Button(myroot, ...)
button.photo = photo # keep a reference
对于PhotoImage对象只能在一个线程下使用,在主要模块中已经用TK()启动一个线程,再在次模块中启动一个线程就不能调用PhotoImage对象。所以开启希望开启次窗口可采用用frame或者toplevel去代替。
以上属于个人理解,错误望指点。