线程执行时 Python GUI 没有响应 [英] Python GUI is not responding while thread is executing
问题描述
我有 Python GUI,在一个 for 循环中,我从某个 dll 调用函数,该函数返回用于逐行填充 tableWidget 的值.所有这些都工作正常,除了我无法在表格仍在填充时滚动表格(同时 dll 函数计算事物 - 每行 7-8 秒)所以我尝试使用这样的线程:
I have Python GUI, and in one for-loop I call function from some dll which returns values for populating tableWidget row by row. All this works fine, except I can't scroll table while it's still populating (while dll function calculating things - 7-8secs for each row) so I tried work with threads like this:
q = Queue.Queue()
for i in (0, numberOfRows):
threading.Thread(target=self.callFunctionFromDLL, args=(arg1,arg2, q)).start()
result = q.get()
... do something with "result" and populate table row....
def callFunctionFromDLL(self, arg1, arg2, q):
result = self.dll.functionFromDLL(arg1, arg2)
q.put(result)
但是直到从 q.get 传递结果之前 GUI 仍然没有响应(functionFromDLL 工作 7-8 秒,并且在 GUI 填充行时我可以滚动表格).我之前并没有真正使用过线程,因此对于如何执行此操作的任何建议或示例将不胜感激.
but still GUI is not responding until result is passed from q.get (functionFromDLL works 7-8 secs, and than for a moment while GUI populating row I can scroll table). I didn't really worked with threads before, so any suggestion or example how to do this would be appreciated.
我也试过这种方式,同样的事情,在functionFromDLL工作时gui仍然没有响应:
I've also tried this way, same thing, gui still not responding while functionFromDLL works:
for i in (0, numberOfRows):
t = threading.Thread(target=self.callFunctionFromDLL, args=(arg1,arg2))
t.start()
t.join()
result = self.result
... do something with "result" and populate table row....
def callFunctionFromDLL(self, arg1, arg2):
self.result = self.dll.functionFromDLL(arg1, arg2)
推荐答案
如果您正在使用 tkinter
模块,您可能能够从 Directory Pruner 4 已实现.为了解决大多数 GUI 库不能很好地与线程配合使用的事实,该秘籍使用了代码下方列出的一些自定义模块.affinity
、threadbox
和 safetkinter
模块提供了程序使用的 GUI 库的线程安全包装.
If you are using the tkinter
module, you might be able to get some help from how Directory Pruner 4 is implemented. To get around the fact that most GUI libraries do not play well with threads, the recipe utilizes some custom modules listed below the code. The modules affinity
, threadbox
, and safetkinter
provide a thread-safe wrapping of the GUI library the program uses.
这篇关于线程执行时 Python GUI 没有响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!