I am trying to build a very simple user interface in Python 3 using Tkinter to be used in windows. and have written a code which is not efficient - it is excessively long for no good reason. I am looking for advice, perhaps even conceptual, about how to make this short and elegant.
Here is a simple excerpt from the code, for only 2 periods. I have many periods, and have created each of them as a class, which is the problem that I am trying to replace. I presume that we should just have one Period
class, objects of which will be called sequentially. I do not understand how to do this with Tkinter.
import tkinter as tk
from tkinter import ttk
class Game(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 in (Period1, Period2):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky='nsew')
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class Period1(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
buttonNext = ttk.Button(self, text='next', command=lambda: controller.show_frame(Period2))
buttonNext.pack()
class Period2(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
buttonNext = ttk.Button(self, text='next', command=lambda: controller.show_frame(Period1))
buttonNext.pack()
app = Game()
app.mainloop()