Question
How to run the Tkinter mainloop
and an infinite server loop simultaneously, in the same script?
Background
I am in the process of creating a GUI server in Tkinter (Python 2.7.3). So far, the GUI works correctly, the Server works correctly, but I am having issues integrating the two. As far as I know (correct me if I am wrong) the server needs to be running on an infinite loop to accept new users. Sadly, the GUI also needs an infinite loop. I am wondering how to have both loops running at the same time.
My current mainloop function looks like this (s
is the socket object):
def mainloop(s):
while True:
channel, addr = s.accept()
print "Connected with", addr
That is obviously needed to keep the server running (I think.) The issue though, is that this loop comes before my mainloop
and thus I have problems with that. If I do it the other way around, the Server is never opened.
Full Code
My server code is here, and my client is here.
Thanks!
You might want to use Twisted http://twistedmatrix.com/trac/
It integrates Tk loop into its reactor loop(which does the networking)http://twistedmatrix.com/documents/8.2.0/api/twisted.internet.tksupport.html ,and you can easily build protocols....
Run them in separate threads. See the threading module documentation for more information.
Use the thread module to open your server mainloop in a new thread.
Replace
with
Then you can call root.mainloop() to run Tkinter, just like you did.
UPDATE
Per A. Rodas' comment below, it's preferred to use the newer
threading
module which is compatible with Python 3.so you can replace
with