W1ll1amvl
W1ll1amvl

Reputation: 1269

Call up a function from another module

I am making a project where I need several modules which are imported into one main module. I have decided to move the interaction to a single Tkinter window. Instead of using input() I use tkinter.Entry(), for example. I have functions for each step of the interaction.

When I get past the last function of the first module, the configured button has a command to go to a function in the second module. I get an error saying that the command is not defined.

I seem unable to import the configured button variable into the next module, and anything else I tried gave no result. It simply doesn't go to the next module after the first module is done.

I have made the main Tkinter window in the main module and have it that it will mainloop after importing the other modules. Shouldn't the function I want to call upon be defined? How can I get from one function to the next if the latter is in a separate module?


Here is a minimal example:

main_script.py

import tkinter
mainwindow = tkinter.Tk()
# here i set the window to a certain size etc.
import mod1
import mod2
mainwindow.mainloop()

mod1.py

import tkinter
def button1():
    label.destroy()
    button1.destroy()
    button2.config(text = "continue", command = func2)
def button2():
    label.destroy()
    button1.destroy()
     button2.config(text = "continue", command = func2)
label = tkinter.Label(text = "example label")
button1 = tkinter.Button(text = "button1", command = button1)
button2 = tkinter.Button(text = "button2", command = button2)
label.pack()
button1.pack()
button2.pack()

mod2.py

def func2():
    button2.destroy()
    print ("haha it works...")

Upvotes: 3

Views: 3173

Answers (1)

user2357112
user2357112

Reputation: 280500

Importing a module has no effect on what the module you import can see. If you want to use mod1 contents in mod2 and mod2 contents in mod1, you need to have them import each other and refer to each other's contents with the appropriate module:

# mod1
import mod2
...
    button2.config(text = "continue", command = mod2.func2)

# mod2
import mod1
def func2():
    mod1.button2.destroy()

Circular imports cause nasty initialization order issues, though, so imports like this are a bad idea. When dividing your code into modules, try to do so in such a way that import loops like this aren't necessary.

Upvotes: 2

Related Questions