How do I execute a script from tkinter without the window crashing?


I am creating a program, but so that you do not have to run that program by double-clicking, I am creating an app in tkinter that will take care of that.
The problem is that, when I run the program from the button, it is executed, but the tkinter window hangs and never responds again.

asked by Gabriel Mation 29.11.2018 в 04:02

1 answer


Tkinter incorporates (below, invisible to us) a loop of events that is the one that detects the actions of the user (if you have clicked the mouse for example) and invokes the appropriate functions within your code to handle the event.

When the user clicks a button, the event loop detects it and calls the appropriate function to handle the event. Until that function returns, the loop can not process more events . When the function returns, the event loop resumes and may continue processing user actions.

Therefore if the function that attends a button takes a long time to return, in the meantime the application will appear "hanging". Simply in it the event loop is waiting for the return of that function and can not attend to user actions. The operating system itself can also "think" that the application has hung up, because the operative sends it events of type "are you still alive?" from time to time to see if it responds to them (the events loop does it automatically). If the event loop is stopped, it will not respond to them and the operative can show a dialog like "It seems that this application has stopped responding" and close it.

Failing to see your code, I suspect that your function never returns, because it will do something like sys.command() to invoke that other program that you say you wanted to launch, and while that other program does not return, your function does not either will do and the event loop will be frozen.

The solution is to launch that command in another process (using the python library subprocess ) or in another thread (using threads ), or use a higher level like concurrent.futures that deals with managing processes or threads as you need.

I can not give you more details without knowing more precisely what you are trying to do and without seeing part of your code.

answered by 29.11.2018 / 09:54