如何在等待套接字数据时使 tkinter 响应事件?

2022-01-15 00:00:00 python tkinter event-handling

问题描述

我正在尝试让应用程序从套接字读取数据,但它需要一些时间并锁定接口,我如何让它在等待时响应 tk 事件?

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?


解决方案

这很简单!你甚至不需要线程!但是你必须稍微重构你的 I/O 代码.Tk 与 Xt 的 XtAddInput() 调用等效,它允许您注册一个回调函数,当文件描述符上可以进行 I/O 时,该回调函数将从 Tk 主循环中调用.这是您需要的:

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)

该文件可能是 Python 文件或套接字对象(实际上,任何具有 fileno() 方法的对象)或整数文件描述符.掩码是常量 tkinter.READABLE 或 tkinter.WRITABLE 之一.回调调用如下:

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)

注意:由于您不知道有多少字节可供读取,因此您不能使用 Python 文件对象的 read 或 readline 方法,因为它们会坚持读取预定义的字节数.对于套接字,recv() 或 recvfrom() 方法可以正常工作;对于其他文件,请使用 os.read(file.fileno(), maxbytecount).

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).

相关文章