I'm trying to make the app read data from a socket, but it takes some time and locks the interface, how do I make it respond to tk events while waiting?
1 Answers
Thats is easy! And you don’t even need threads! But you’ll have to restructure your I/O code a bit. Tk has the equivalent of Xt’s XtAddInput() call, which allows you to register a callback function which will be called from the Tk mainloop when I/O is possible on a file descriptor. Here’s what you need:
from Tkinter import tkinter
tkinter.createfilehandler(file, mask, callback)
The file may be a Python file or socket object (actually, anything with a fileno() method), or an integer file descriptor. The mask is one of the constants tkinter.READABLE or tkinter.WRITABLE. The callback is called as follows:
callback(file, mask)
You must unregister the callback when you’re done, using
tkinter.deletefilehandler(file)
Note: since you don’t know how many bytes are available for reading, you can’t use the Python file object’s read or readline methods, since these will insist on reading a predefined number of bytes. For sockets, the recv() or recvfrom() methods will work fine; for other files, use os.read(file.fileno(), maxbytecount).

- 2,574
- 3
- 21
- 27
-
This is one of the really, really great features of Tk -- getting an event when a file can be read makes socket handling very easy. – Bryan Oakley Jul 28 '10 at 15:57
-
This seems not to work on Windows, even though Windows has `WSAAsyncSelect()` which exactly delivers notifications of socket readiness to GUI – Ben Voigt May 10 '21 at 22:02