In simply trying to work on organizing my code, I've found online that it seems to be best to put much of your code into classes when needed. So in doing that, I'd figure that I'll try to create a frame class
with create_labels
and create_buttons
methods.
My goal is to be able to create 2 or more seperate frames that are similar in style (hence why I find it best to make a frame class). Then, using methods, create labels, buttons, and other widgets and allow them to move around with ease within their respective frames.
So here's my code:
import tkinter as tk
window = tk.Tk()
class MyFrame(tk.Frame):
def __init__(self, parent, **kwargs):
tk.Frame.__init__(self, parent)
self.parent = parent
self.layout(**kwargs)
def labels(self, text, **kwargs):
tk.Label.__init__(self, text=text)
self.layout(**kwargs)
def buttons(self, text, command, **kwargs):
tk.Button.__init__(self, text=text, command=command)
self.layout(**kwargs)
def layout(self, row=0, column=0, columnspan=None, row_weight=None, column_weight=None, color=None, sticky=None, ipadx=None, padx=None, ipady=None, pady=None):
self.grid(row=row, column=column, columnspan=columnspan, sticky=sticky, ipadx=ipadx, padx=padx, ipady=ipady, pady=pady)
self.grid_rowconfigure(row, weight=row_weight)
self.grid_columnconfigure(column, weight=column_weight)
self.config(bg=color)
frame_1 = MyFrame(window, row=0, column=0, sticky="news", color="pink")
frame_1.buttons("Btn_1/Frme_1", quit, row=0, column=0)
frame_1.buttons("Btn_2/Frme_1", quit, row=0, column=1)
frame_2 = MyFrame(window, row=1, column=0, sticky="news", color="green")
frame_2.buttons("Btn_1/Frme_2", quit, row=0, column=0)
frame_2.buttons("Btn_2/Frme_2", quit, row=0, column=1)
window.grid_columnconfigure(0, weight=1)
window.grid_columnconfigure(1, weight=1)
window.grid_rowconfigure(1, weight=1)
window.grid_rowconfigure(0, weight=1)
window.mainloop()
Now I think a problem of mine is during the __init__ method
because there should be 2 frames and 2 buttons per frame. However, there's no errors which makes it harder to find out for sure of that's why only the latest buttons and frames exist. I don't even think it's a case of one frame or widget 'covering' another. I think the second frame/widgets seem to be overwriting the first frame/widgets.
Any help is appreciated.