多帧 tkinter 的 KeyError?
KeyError for multiframe tkinter?
我一直收到 KeyError,我不确定为什么。我添加了一个 print 语句并打印了 self.frames dict 以确保密钥存在,而且看起来确实如此。我是使用 类 创建多框架应用程序的新手,所以任何见解都会有所帮助。
错误:
Traceback (most recent call last):
File "/root/Desktop/I.T.E.D./ITED.py", line 165, in <module>
app = ITED()
File "/root/Desktop/I.T.E.D./ITED.py", line 29, in __init__
self.show_frame(StartPage)
File "/root/Desktop/I.T.E.D./ITED.py", line 33, in show_frame
frame, geometry = self.frames[page_name]
KeyError: <class '__main__.StartPage'>
打印的字典:
{'StartPage': (<__main__.StartPage object .!frame.!startpage>, '250x100'), 'PageOne': (<__main__.PageOne object .!frame.!pageone>, '500x200')}
发生错误的代码:
class ITED(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.pack(side="top", fill="both", expand = True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F,geometry in zip((StartPage, PageOne), ('250x100', '500x200')):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = (frame, geometry)
frame.grid(row=0, column=0, sticky="nsew")
print(self.frames)
self.show_frame(StartPage)
def show_frame(self, page_name):
frame, geometry = self.frames[page_name]
self.update_idletasks()
self.geometry(geometry)
frame.tkraise()
def quit(self):
self.app.destroy()
您字典中的关键字是 class 名称,然后您试图通过 class 本身引用它们。
self.show_frame(StartPage)
需要 self.show_frame("StartPage")
我一直收到 KeyError,我不确定为什么。我添加了一个 print 语句并打印了 self.frames dict 以确保密钥存在,而且看起来确实如此。我是使用 类 创建多框架应用程序的新手,所以任何见解都会有所帮助。
错误:
Traceback (most recent call last):
File "/root/Desktop/I.T.E.D./ITED.py", line 165, in <module>
app = ITED()
File "/root/Desktop/I.T.E.D./ITED.py", line 29, in __init__
self.show_frame(StartPage)
File "/root/Desktop/I.T.E.D./ITED.py", line 33, in show_frame
frame, geometry = self.frames[page_name]
KeyError: <class '__main__.StartPage'>
打印的字典:
{'StartPage': (<__main__.StartPage object .!frame.!startpage>, '250x100'), 'PageOne': (<__main__.PageOne object .!frame.!pageone>, '500x200')}
发生错误的代码:
class ITED(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.pack(side="top", fill="both", expand = True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F,geometry in zip((StartPage, PageOne), ('250x100', '500x200')):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = (frame, geometry)
frame.grid(row=0, column=0, sticky="nsew")
print(self.frames)
self.show_frame(StartPage)
def show_frame(self, page_name):
frame, geometry = self.frames[page_name]
self.update_idletasks()
self.geometry(geometry)
frame.tkraise()
def quit(self):
self.app.destroy()
您字典中的关键字是 class 名称,然后您试图通过 class 本身引用它们。
self.show_frame(StartPage)
需要 self.show_frame("StartPage")