[SOLVED] How to call function of main code in an Imported module?

Issue

Can an imported module make the Main module call a function?
I created a sequence diagram and I have a barebones code example of what I mean:

main:

import test2

def function():
    do sth

test2:

import tkinter as tk

window  = tk.Tk()
test = tk.Button(master = window, text = "hdsd", command = # call function of main program)
test.grid(row = 0, column = 0)
window.mainloop()

Solution

The way to do this is to design your imported code so that you are only importing objects (functions, classes, constants) and not running code. Then, once you have functions or classes, you can pass other functions or objects to them.

For example, consider this main.py:

import test2
def function():
    do sth
test2.create_gui(function)

test2.py might then look like this:

def create_gui(func):
    window  = tk.Tk()
    test = tk.Button(master = window, text = "hdsd", command = func)
    test.grid(row = 0, column = 0)
    window.mainloop()

Arguably, a better solution is to use classes, both for the code in main.py and in test2.py. By adding all of the functions into a class, you can pass one instance and your GUI will have access to all of the functions.

main.py

from test2 import GUI
class Main():
    def __init__(self):
        self.gui = GUI(self)

    def function(self):
        do sth

    def another_function(self):
        do sth

if __name__ == "__main__":
    main = Main()
    main.gui.start()

test2.py

import tkinter as tk
class GUI(tk.Tk):
    def __init__(self, main):
        super().__init__()
        test1 = tk.Button(self, text="hdsd", command=main.function)
        test2 = tk.Button(self, text="sdhd", command=main.another_function)

        test1.grid(row=0, column=0)
        test2.grid(row=0, column=1)

    def start(self):
        self.mainloop()

Answered By – Bryan Oakley

Answer Checked By – Pedro (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.