我正在使用TKinter创建GUI,主窗口可以从其主菜单打开其自身的新实例。
但是,当我创建窗口的新实例时,此方法没有出现,应该在画布上显示的图像没有出现。有没有人可以帮助您?
这是我的GUI代码:
class MainPage:
def __init__(self, master):
master.title("EIL Viewer")
master.geometry('1000x650')
#creating the main menu
master.option_add('*tearOff', False)
mainmenu = Menu(master)
master.configure(menu = mainmenu)
File = Menu(mainmenu)
mainmenu.add_cascade(menu= File, label = 'File')
#setting up commands for main menu
File.add_command( label = 'New Window', command = lambda: New() , accelerator = 'Ctrl + N')
#creating the canvas on the window
self.canvas = Canvas(master)
self.canvas.pack()
self.canvas.pack_configure(fill= BOTH, expand = True)
self.canvas.config(width=300, height= 500,background = 'white')
#setting the image on the canvas
photo = PhotoImage( file = 'C:/Users/Admin/Documents/Untitled Folder/sampleimage.png')
self.canvas.img = photo #here I am storing the image to the canvas so that it stays in the memory
self.image = self.canvas.create_image(150,150, image = self.canvas.img)
这是我编写从主菜单打开新实例的函数的代码:
#setting n = 0 counter to distinguish the different windows
n = 0
def New():
n = Tk()
mainpage = MainPage(n)
n.mainloop()
n = n + 1
设置计数器n = n + 1的原因是,每次调用窗口的新实例时,它都不会运行通过同一主窗口的窗口。这是多余的吗?
当我尝试从菜单中运行“新建窗口”命令时,我收到以下有关加载到画布上的图像的错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "<ipython-input-3-803bc8733dc3>", line 60, in <lambda>
File.add_command( label = 'New Window', command = lambda: New() , accelerator = 'Ctrl + N')
File "<ipython-input-3-803bc8733dc3>", line 1425, in New
mainpage = MainPage(n)
File "<ipython-input-3-803bc8733dc3>", line 480, in __init__
self.eil = self.canvas.create_image(150,150, image = self.canvas.img)
File "C:\Users\Camilla Tac\Anaconda3\lib\tkinter\__init__.py", line 2483, in create_image
return self._create('image', args, kw)
File "C:\Users\Camilla Tac\Anaconda3\lib\tkinter\__init__.py", line 2474, in _create
*(args + self._options(cnf, kw))))
_tkinter.TclError: image "pyimage16" doesn't exist
有人可以帮我解决这个问题吗?
答案 0 :(得分:0)
您无法在Tk
的两个实例之间共享图像。适当的Tkinter GUI应该始终只有Tk
一次实例。如果需要多个窗口,则除第一个窗口外,每个窗口都必须是Toplevel
的实例。