To prevent hanging, you need to separate the calculations in the mainmethod
from Tkinter's main loop by executing them in different threads. However, threading system in Python is not that well-developed as in other languages (AFAIK) because of GIL (Global Interpreter Lock), but there is an alternative - using processes just like threads. This is possible with multiprocessing
library.
In order to just prevent hanging, you could create another function
from multiprocessing import Process
def mainmethodLaunch():
global mainmethodProcess
mainmethodProcess = Process(target=mainmethod)
mainmethodProcess.start()
And bind this function to MyButton2
instead of mainmethod
itself.
Docs: https://docs.python.org/2/library/multiprocessing.html#the-process-class
You can see p.join
in the example. join
method will cause your main process to wait for the other one to complete, which you don't want.
So when you press the button, mainmethodLaunch
function will be invoked, and it will create another process executing mainmethod
. mainmethodLaunch
function's own run duration should be insignificant. Due to usage of another process, Tkinter window will not hang. However, if you do just this, you will not be able to interact with mainmethod
process in any kind while it will be working.
In order to let these processes communicate with each other, you could use pipes (https://docs.python.org/2/library/multiprocessing.html#exchanging-objects-between-processes)
I guess the example is quite clear.
In order to receive some data from the mainmethod
process over time, you will have to poll the parent_conn
once a little time, let's say, second. This can be achieved with Tkinter's after
method
(tkinter: how to use after method)
IMPORTANT NOTE: when using multiprocessing
, you MUST initialize the program in if __name__ == '__main__':
block. I mean, there should be no doing-something code outside functions and this block, no doing-something code with zero indent.
This is because multiprocessing
is going to fork the same Python executable file, and it will have to distinguish the main process from the forked one, and not do initializing stuff in the forked one.
Check twice if you have done that because if you make such a mistake, it can cost you hanging of not just Tkinter window, but the whole system :)
Because the process will be going to fork itself endlessly, consuming all RAM you have, regardless of how much you have.