問題描述
我正在嘗試讓應用程序從套接字讀取數(shù)據(jù),但它需要一些時間并鎖定接口,我如何讓它在等待時響應 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?
推薦答案
這很簡單!你甚至不需要線程!但是你必須稍微重構(gòu)你的 I/O 代碼.Tk 與 Xt 的 XtAddInput() 調(diào)用等效,它允許您注冊一個回調(diào)函數(shù),當文件描述符上可以進行 I/O 時,該回調(diào)函數(shù)將從 Tk 主循環(huán)中調(diào)用.這是您需要的:
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() 方法的對象)或整數(shù)文件描述符.掩碼是常量 tkinter.READABLE 或 tkinter.WRITABLE 之一.回調(diào)調(diào)用如下:
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)
您必須在完成后取消注冊回調(diào),使用
You must unregister the callback when you’re done, using
tkinter.deletefilehandler(file)
注意:由于您不知道有多少字節(jié)可供讀取,因此您不能使用 Python 文件對象的 read 或 readline 方法,因為它們會堅持讀取預定義的字節(jié)數(shù).對于套接字,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).
這篇關(guān)于如何在等待套接字數(shù)據(jù)時使 tkinter 響應事件?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!