Python - Interacting with GUI elements across multiple modules

Viewed 231

I have a GUI built in python that I would like to move to it's own module. However I am running into issues when interacting with the GUI elements as well as importing them correctly. (Example code below)

I believe the issue is partially that the gui module does not finish importing before being used inside main. If I were to use a third module with the active code to start it, the GUI would be functional but then I am unsure how to reference the GUI widgets from inside the 'main' methods absent the app object.

My question is mainly that of what is the recommended way to implement an interactive GUI with many widgets. Am I completely off track trying to split it up among different modules? In my actual project if I put it all inside a single module it's running over several thousand lines of code already and I am not yet finished adding features.

EDIT: The specific problem in the below example is the failure of the button command with error of "'main' is not defined". Switching that to only the function name similarly gives the error "'testButton' is not defined"

gui.py

import tkinter as tk

class AppGUI(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()

        self.master.minsize(self.master.winfo_reqwidth(), self.master.winfo_reqheight()) 
        self.master.resizable(False,False) 
        self.master.protocol("WM_DELETE_WINDOW", self.quit_callback)

        self.create_frames()
        self.create_widgets()

    def create_frames(self):
        self.r0c0 = tk.Frame(self, width=200, height=100, bg="grey")
        self.r0c0.grid(row=0, column=0, sticky="nw", padx=5, pady=5)
        
    def create_widgets(self):
        self.testButton = tk.Button(
          master=self.r0c0, text="testButton",
          command=lambda: main.testButton("testing"),
          ).pack()
        self.outputTextBox = tk.Text(master=self.r0c0)
        self.outputTextBox.pack()
import main

main.py

import tkinter as tk

def testButton(phrase):
  tmp = app.outputTestBox.get("1.0", tk.END)
  print(tmp)
  app.outputTestBox.insert("0.0","testing: "+phrase+"\n")

import gui
##Begin Gui##
window = tk.Tk()
app = gui.AppGUI(master=window)

app.mainloop()   
0 Answers
Related