Home > Mobile >  OOP in Python / Tkinter: how to define a module with a support class in which all widgets events are
OOP in Python / Tkinter: how to define a module with a support class in which all widgets events are

Time:11-03

I'm quite new with OOP. Let's say I have defined a Tkinter application in a file called myApp.py. This is its content:

import tkinter as tk
from tkinter import ttk
from tkinter.constants import *

import myApp_support

class App(tk.Tk):
  def __init__(self):
    super().__init__()

    self.title('myApp')
    self.resizable(False, False)
    self.state('zoomed')

    supportClass = myApp_support.AppSupport()
    
    ...

    # %% BUTTON OPEN FILE
    self.Button_OpenFile = ttk.Button(container)
    self.Button_OpenFile.configure(text='''OPEN UBX FILE''') 
    self.Button_OpenFile.configure(command = supportClass.Button_OpenFile_Clicked)

    ...

    if __name__ == "__main__":
        app = App()
        app.mainloop()

container, in the previous code, is the frame to which the button is anchored. I would like to define a class (AppSupport()) in another file (myApp_support.py), in which all events related to the app widgets are defined, such as a button clicked event. The class should define a variable that points to the window, as defined in myApp.py, in order to manage all the widgets. I tried unsuccessfully with this code saved in the myApp_support.py:

import myApp

class AppSupport():
    def __init__():
       global rootApp
       rootApp = myApp.App()
    
    def Button_OpenFile_Clicked(*args):
        print('Open Button clicked')

How can I define properly the class according to this scheme?

CodePudding user response:

You need to pass the instance of App to AppSupport

class App(tk.Tk):
  def __init__(self):
    super().__init__()
    ...
    self.supportClass = myApp_support.AppSupport(app=self)
    ...
class AppSupport():
    def __init__(self, app):
       self.app = app
  • Related