0

I have a file named "intro_to_tkinter.py" and in this file I have imported a function "print something()" from another file named "demos_tkinter.py". Whenever I execute the "intro_to_tkinter.py" file "demos_tkinter.py"is executed.

this is the "demos_tkinter.py" file

from tkinter import * 
def print_something():
    print("hello")
roots=Tk()
roots.mainloop()

this is "intro_to_tkinter.py" file

from tkinter import * 
from demos_tkinter import print_something 
root=Tk() 
root.configure(bg="#000000") 
print_something() 
root.mainloop()

what should i do to execute only the desired function and not the file

JRiggles
  • 4,847
  • 1
  • 12
  • 27
  • Are you expecting the new window to open upon calling the function from 'demos_tkinter.py'? – nrhoopes Aug 16 '23 at 14:09
  • I think this is because when you import a function from another file, Python first loads the file and executes all the module-level code in the file as initialization. In your case the two statements roots=Tk() and roots.mainloop() will be executed when the module first loads. After that, any subsequest import of the same demos_tkinter.py module in another module will not re-execute the code becasue it is already loaded. It is done only when the module is first loaded. To avoid this you would have to put those statements in another function and execute that function when you want it to run. – JohnRC Aug 16 '23 at 14:12
  • 2
    Importing executes the script. All top-level code is run. You'd expect to see a `print("hello world")` on import, but it may be less obvious that `roots=Tk()` runs also. – tdelaney Aug 16 '23 at 14:12

2 Answers2

2

All top-level code in a given module is executed at import, so in the case of "demos_tkinter.py" it's starting up a tkinter app.

You can fix this by adding an if __name__ == '__main__' guard clause to "demos_tkinter.py" like so:

from tkinter import *


def print_something():
    print("hello")


if __name__ == '__main__':
    roots = Tk()
    roots.mainloop()

This way, roots.mainloop() will only be called if this script is run directly, and not when it's imported as a module.


As a bonus, this import behavior is why a python file containing only import this will print out The Zen of Python when run.

JRiggles
  • 4,847
  • 1
  • 12
  • 27
-1

The correct way:

demos_tkinter.py. You don't need to add import tkinter. But only intro_to_tkinter.py will create for you.

So one Tk() and mainloop() will do entirely script.

code:

#from tkinter import *

def print_something():
    print("hello")
    
#roots=Tk()
#roots.mainloop()
toyota Supra
  • 3,181
  • 4
  • 15
  • 19