I dive into tkinter at the moment and many code examples on the internet cover only very simple examples and don't teach best-practices.
For better maintainability and clearness, I'd like to use OOP for a GUI, which makes sense from my point of view. However, I'd live your advice about how to structure it because I'm a beginner in general. I've already browsed other questions, but they could not answer my specific general question I have.
My idea here:
Would like to create a menubar for the GUI and create a new file menu.py that only deals with that menu. Here you can find two examples:
1. Example: Logically, the menubar consists of other menus. So the menu contains menus. But I am not sure if it's good to use nested classes?
import tkinter as tk
class Menu(tk.Frame):
def __init__(self, parent, *args, **kwargs):
super().__init__(parent, *args, **kwargs)
self.parent = parent
self.menubar = Menubar(self)
class Menubar(tk.Menu):
def __init__(self, parent, *args, **kwargs):
super().__init__(parent, *args, **kwargs)
self.parent = parent
self.add_cascade(label="File", menu=self.file_menu)
self.add_cascade(label="Edit", menu=self.edit_menu)
self.file_menu = FileMenu(self)
self.edit_menu = EditMenu(self)
class FileMenu(tk.Menu):
def __init__(self, parent, *args, **kwargs):
super().__init__(parent, *args, **kwargs)
self.parent = parent
class EditMenu(tk.Menu):
def __init__(self, parent, *args, **kwargs):
super().__init__(parent, *args, **kwargs)
self.parent = parent
2. Example: Here you can find a more procedural example. But the weakness here from my point of view is that hierarchical the Menubar as well as the file_menu and the edit_menu are on the same level. But logically the Menubar consists of the file_menu and edit_menu. So, it's not really modular. On the other side, it's perhaps(?) more easy to read than the first example.
import tkinter as tk
class Menu(tk.Frame):
def __init__(self, parent, *args, **kwargs):
super().__init__(parent, *args, **kwargs)
self.parent = parent
self.menubar = tk.Menu(self)
self.create_file_menu(self.menubar)
self.create_edit_menu(self.menubar)
def create_file_menu(self, parent):
self.file_menu = tk.Menu(parent)
self.menubar.add_cascade(label="File", menu=self.file_menu)
def create_edit_menu(self, parent):
self.edit_menu = tk.Menu(parent)
self.menubar.add_cascade(label="Edit", menu=self.edit_menu)