0

I'm currently writing a tiny windowed app using python and tkinter.

I have very little experience with tkinter and I asked myself whether it would be best to:

  • make my window a class inheriting from tkinter.Tk
  • initialise all objects and variables
  • do all the processes in its __init__ method as if it was a main likewise:

    class Main_Frame(tkinter.Tk):
        def __init__(self):
            super().__init__()
            self.grid = Grid(60, 40)
            can_width, can_height = self.canvas_dim()
            self.can = tk.Canvas(self, width = can_width, height = can_height)
            self.can.bind('<Button-1>', self.color_1)
            self.can.pack()
    

Also, all the functions would be translated to become methods of that class.

Or should I just instantiate the Tk class and put all treatments, variables and instances in the main?

If you need a more detailed look on the code here are the two versions of the code: gist

baduker
  • 19,152
  • 9
  • 33
  • 56
Louisono
  • 11
  • 6
  • This is either _primarily opinion based_ or a duplicate to [this](https://stackoverflow.com/q/17466561/7032856) IMO. – Nae Mar 13 '18 at 09:50
  • i agree this is primarily opinion based, personally i prefer putting all methods relating to the GUI into a single class that inherits from a tk widget. as this keeps related code together. – James Kent Mar 13 '18 at 10:46
  • I tend to put all the GUI into one class and inherit from frame. – Mike - SMT Mar 13 '18 at 13:50
  • I don't think it's a good idea to inherit from `tkinter.Tk` as that object needs to be _singularly present_, hence it breaks object reuse. I think `Frame` is the better option here. You can manipulate the Tk object anyway using `widget.winfo_toplevel()` anyway. – Nae Mar 14 '18 at 19:12
  • @Nae thanks for your suggestions! I have read some related questions (a lot of which were answered by Bryan Oakley) that helped me very much. – Louisono Mar 15 '18 at 09:54
  • While this isn't what you asked, I recommend creating the GUI in another method and other variables not related to the GUI In `__init__`. This allows you to separate GUI from class code and makes things easy to differentiate. – Pycoder Oct 26 '22 at 08:04

0 Answers0