Skip to content
Advertisement

KeyError for multiframe tkinter?

I keep getting a KeyError and I am unsure why. I added a print statement and printed the self.frames dict to ensure that the keys existed, and it appears they do. I’m new to using classes to create multi frame apps so any insight would be helpful.

The error:

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'>

The dict that prints:

{'StartPage': (<__main__.StartPage object .!frame.!startpage>, '250x100'), 'PageOne': (<__main__.PageOne object .!frame.!pageone>, '500x200')}

The code where the error occurs:

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()

Advertisement

Answer

The keys in your dictionary are the class names, then you’re trying to reference them by the class itself.

self.show_frame(StartPage) needs to be self.show_frame("StartPage")

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement