Yes, as @Barmar mentioned, importing anything from a file will first run that file. If you just want import something without running your file, you should put the infinite loop in my_program
in an if-main-block.
if __name__ == "__main__":
while True:
...
This will make it only being executed when you run only the my_program
file, like using python3 my_program.py
.
However, if you want to run that infinite loop while having the tkinter window open, you need to understand that the tkinter window itself gets executed in an infinite loop, and your Python code is busy running that window and can't do anything else at the same time. You probably have a line like window.mainloop()
in your code, this is where your code is "stuck" while executing your script.
I don't know what exactly you need that infinite loop for, but if you want it to run simultaneously with your Tkinter window, you basically have two options for doing this.
- Manually update your window in your infinite loop:
Replace your
window.mainloop()
instruction with that:
while True:
window.update()
window.update_idletasks()
(your custom code here)
The update()
and update_idletasks()
methods basically just do the same things that mainloop()
does, but only a single time. This option is good if your custom code doesn't take long to execute. However, if it does take a long time to execute, notice that your window will only be updated when window.update()
is called, so while your custom code is running, you won't be able to click on buttons or anything.
- Run your custom code in a seperate thread: You can also use multithreading to run your code in parallel to the tkinter window. Put your custom infinite loop in a function like this:
def my_custom_loop():
while True:
my code
Then, create a thread that will call that function:
from threading import Thread
my_custom_thread = Thread(target = my_custom_loop)
Before your window.mainloop()
line, you can then insert my_custom_thread.start()
to start running it in the background.
However, this could be overkill depending on what you want to achieve with your custom code. If you need more help you should be more specific about what "my code" should actually do.
my_program.py
directly, not when importing, it should be in theif __name__ == '__main__':
block. See stackoverflow.com/questions/419163/what-does-if-name-main-do/…