Repository navigation
Description
tkinter can register a callback to run from the Tk mainloop when a file descriptor becomes readable or writable, via tk.createfilehandler() / tk.deletefilehandler(). But these wrap Tcl_CreateFileHandler, which is not implemented on Windows, so there is no portable way to do asynchronous I/O on a file, pipe or socket inside the Tk event loop.
Tcl's channel API (Tcl_MakeFileChannel, Tcl_CreateChannelHandler) works on all platforms. I propose exposing it in tkinter.
A new method creates a channel from a file, a pipe or a socket:
channel = widget.tk.createchannel(file, mode='r')- file is an object with a
fileno()method (a file or socket) or an integer file descriptor. - mode is
'r','w'or'rw'. - The channel duplicates the descriptor/handle/socket, so closing the channel does not close the original, and vice versa.
- The channel is binary and non-blocking.
It returns a tkchannel object:
read(size=-1)— read up to size bytes;b''at end of file,Noneif nothing is available.write(data)— write a bytes-like object.flush(),eof(),close().createhandler(mask, func)/deletehandler()— callfunc(channel, mask)when the channel becomes readable or writable, where mask ORstkinter.READABLEandtkinter.WRITABLE.name— the Tcl channel name, usable from Tcl commands and options that take a channel, such as the channel option ofCanvas.postscript().closed.
It is also a context manager that closes the channel on exit.
This complements the existing file handlers (which stay as the thin Unix-only wrapper) and overlaps in spirit with gh-154801 (exposing more of Tcl's event-loop API).
Activity