Tkinter & socket question

Gregory A. Landrum landrum at
Sat Jun 19 12:18:46 CEST 1999

>2) I need to poll the connection periodically, say, every second. This would
>not have been a problem in console mode... I don't know how to do this in a
>Tkinter environment though. So, how can I do something every second (or every
>n milliseconds, or whatever the time span may be)? Are threads the way to go?
>I haven't used them before.

Wow, a question I can answer.... amazing.
Obligatory-Mandatory-Necessary-Essential Disclaimer:  I bear no
resemblance whatsoever to a python wizard, I just happen to have done
something like what you want to do.  There's almost definitely a
better way of doing this, but my method seems to work.

I assume that you have already opened a nonblocking socket connection,
and that that is what you are polling.  Your main Tkinter window has a
method called "after" which can be used to do the polling.
Documentation can be found at:

An example, in my stupid little networked python game, I have the
following polling function:
    def ListenForMessages(self):
        msg = None
        theConn = None
	# Check to see if we are the client or the server
        if self.serverActive == 1:
            if self.clientConn is None:
                print "No Client!"
            theConn = self.clientConn
        elif self.clientActive == 1:
            theConn = self.socket

        if theConn is None: return

	# see if there is anything there to read
            msg = theConn.recv(1024)
	    # Got it!  Dispatch the message.
        except error:
	    # nope... no one loves us.

	# re-register the after callback, with a 200msec delay
        self.listenID = self.Game.rootWin.after(200,self.ListenForMessages)

The last line is important, because the after callback is removed
after being called.  So it needs to be re-registered with Tk.

The callback is first registered immediately upon establishing the
socket connection.

I hope this helps,

Dr. Greg Landrum  (landrumSPAM at
Institute of Inorganic Chemistry
Aachen University of Technology

More information about the Python-list mailing list