0

I'm having trouble understanding how to switch frames in tkinter.

I am using the code that has grown really popular around the internet, that switches frames by stacking them one on top of the other and then calling them. I am having trouble understanding a couple of lines of code (the ones with ***)

import tkinter as tk
class SampleApp(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)
        self.frames={}
        for F in (a, b, c):***
            page_name=F.__name__***
            frame=F(parent=container, controller=self)
            self.frames[page_name]=frame
            frame.grid(row=0, column=0, sticky="nsew")
        self.show_frame("a")
    def show_frame(self, page_name):
        frame=self.frames[page_name]
        frame.tkraise()

so I have 2 questions, the first is why in the for loop a, b, c are written like variables, and not like strings (when I am going to show the frame a, I put "a" like a string). Second, what does __name__ do in this case, what is the necessity of it.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
count zero
  • 43
  • 6
  • Have you read through the answer to [Tkinter! Understanding how to switch frames](https://stackoverflow.com/questions/34301300/tkinter-understanding-how-to-switch-frames)? – Bryan Oakley Aug 25 '19 at 18:55

1 Answers1

1

a, b, c are classes and __name__ gives you name of classes as string - so it creates dictionary

 self.frames = { "a": a(), "b": b(), "c": c() }

with "class_name_as_string": instance_of_class

And show_frame("a") uses "class_name_as_string" to get instance_of_class and show it.


You could skip __name__ and then you would have

 self.frames = {a: a(), b: b(), c: c()}

with class: instance_of_class and you would have to use class in show_frame(a)

furas
  • 134,197
  • 12
  • 106
  • 148
  • thank you, I think I get it know, but then I dont understand how python knows that a, b, c are classes, if those classes are defined after the class SampleApp class (where the for loop is) – count zero Aug 25 '19 at 22:27
  • this loop is executed when you create instance of class SampleApp. If instance is created after definition of classes a,b,c then there is no problem. – furas Aug 25 '19 at 22:52