Search code examples
pythontkinter

calling and passing arguments between two python files


I am using customtkinter textbox for a GUI in file1, and I want to print multiple texts whenever I call the print function in file1 from file2. Sorry, it's a 300+ LOC. I just put some of the codes here for visualization. So if we press the stop button that stop_exec will be called. Here is the latest edit. Sorry for confusing you.

File1:

import customtkinter as ctk
import tkinter as tk

class App(ctk.CTk):
    def __init__(self):
        super().__init__()
        self.title("dummy")
        self.geometry(f"{800}x{500}")
        self.SM_data = ctk.CTkTextbox(self, corner_radius=0, fg_color="#dee2e6", text_color="#000000",font=("Tahoma",12), border_width=1, border_color="#000000")
        self.SM_data.grid(row=0, column=0, sticky="nsew")
        self.stop_button =ctk.CTkButton(self, width=24, height=24, text="X", anchor="right", hover_color="#D20103", fg_color="#E60808", command= self.stop_execution)
        self.stop_button.grid(row=0, column=1, padx=(0,4), sticky="e")

    def print_SM(self, text):
        print(f"Received text: {text}")  #print measure
        self.SM_data.insert(tk.END, text + "\n")

    def stop_execution(self):
        from File2 import stop_exec
        stop_exec() 

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

File2:

from File1 import App

# Create an instance of the App class
app_instance = App()

def stop_exec():
    y = "test print"
    app_instance.print_SM(y)

The output should be printing "test print" in the textbox.

Also why did i get the additional problem after closing the GUI:

invalid command name "3043397009600update"
    while executing
"3043397009600update"
    ("after" script)
invalid command name "3043396906432check_dpi_scaling"
    while executing
"3043396906432check_dpi_scaling"
    ("after" script)
invalid command name "3043397009856<lambda>"
    while executing
"3043397009856<lambda>"
    ("after" script)

Solution

  • You create a new instance of App() inside stop_exec() and call its print_SM() which does not insert text into the already created instance inside File1.

    Suggest to pass the already created instance to stop_exec() instead:

    File2:

    def stop_exec(app_instance):
        y = "test print"
        app_instance.print_SM(y)
    

    File1:

    ...
    class App(ctk.CTk):
       ...
       def stop_execution(self):
           from File2 import stop_exec
           stop_exec(self)  # pass App instance to the function