Tkinter & socket question

Michael P. Reilly arcege at shore.net
Sat Jun 19 19:34:32 EDT 1999


Gregory A. Landrum <landrum at foreman.ac.rwth-aachen.de> wrote:

:>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:
: http://www.pythonware.com/library/tkinter/introduction/x8550-alarm-handlers-and-other.htm

: 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!"
:                 return
:             theConn = self.clientConn
:         elif self.clientActive == 1:
:             theConn = self.socket

:         if theConn is None: return

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

:  # 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.

You can also deal directly with Tcl/Tk's filehandler:

  from Tkinter import tkinter
  self.root.tk.createfilehandler(socket, tkinter.READABLE,
    self.handle_msg
  )
  ...
  self.root.tk.deletefilehandler(socket)

The mainloop() method handles the rest for you.

  -Arcege





More information about the Python-list mailing list