I'm trying to create an app in which i could move between windows. While trying to put together a tkinter app, I came up with an idea to create new windows as the class App:
methods.
Questions: is this a good idea? Maybe such approach has some drawbacks that I do not see?
Sample code of the idea:
import tkinter as tk
import tkinter.ttk as ttk
class App:
def __init__(self, master=None):
self.master = master
# Window 1 widgets
self.frame1 = ttk.Frame(master, width=300, height=150, relief='groove')
self.frame1.pack_propagate(False)
self.label1 = ttk.Label(self.frame1, text='This is window 1')
self.button1 = ttk.Button(self.frame1, text='Go to window 2', command=self.window2)
self.button2 = ttk.Button(self.frame1, text='Go to window 3', command=self.window3)
# Window 2 widgets
self.frame2 = ttk.Frame(master, width=300, height=150, relief='groove')
self.frame2.pack_propagate(False)
self.label2 = ttk.Label(self.frame2, text='This is window 2')
self.button3 = ttk.Button(self.frame2, text='Go to window 1', command=self.window1)
self.button4 = ttk.Button(self.frame2, text='Go to window 3', command=self.window3)
# Window 3 widgets
self.frame3 = ttk.Frame(master, width=300, height=150, relief='groove')
self.frame3.pack_propagate(False)
self.label3 = ttk.Label(self.frame3, text='This is window 3')
self.button5 = ttk.Button(self.frame3, text='Go to window 1', command=self.window1)
self.button6 = ttk.Button(self.frame3, text='Go to window 2', command=self.window2)
self.window1()
def window1(self):
self.forget_widgets()
self.frame1.pack(side='top', pady=(25, 0))
self.label1.pack(side='top', pady=(25, 25))
self.button1.pack(side='top', pady=(0, 5))
self.button2.pack(side='top')
def window2(self):
self.forget_widgets()
self.frame2.pack(side='top', pady=(25, 0))
self.label2.pack(side='top', pady=(25, 25))
self.button3.pack(side='top', pady=(0, 5))
self.button4.pack(side='top')
def window3(self):
self.forget_widgets()
self.frame3.pack(side='top', pady=(25, 0))
self.label3.pack(side='top', pady=(25, 25))
self.button5.pack(side='top', pady=(0, 5))
self.button6.pack(side='top')
def forget_widgets(self):
for widget in self.master.winfo_children():
widget.pack_forget()
if __name__ == '__main__':
root = tk.Tk()
root.geometry('350x200')
App(master=root)
root.mainloop()
While looking for other possible methods I have found that it is either best to use the toplevel widget, or create each window as a new class. The first method is not what i am looking for though, because I am trying to replicate a game-like GUI right now. As for the second method, I am not really sure. While surfing in the net I found out that creating a class with only __init__
method is overuse of classes and in general a bad practice. This is done in an answer by Bryan Oakley here on stackoverflow though: Switch between two frames in tkinter
Could anyone elaborate on this and try to explain me which method is the best and the one I should stick to while learning tkinter? Thanks!