Python GUI is not responding while thread is executing

拟墨画扇 提交于 2019-12-11 00:43:35

问题


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)

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.

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)

回答1:


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.




回答2:


CPython (what you probably have) has a Global Interpreter Lock in it that defeats a lot of multithreading. This is a known problem that has proven difficult to solve. (Look up "Python GIL" for more info.) Some other implementations, such as Jython, don't have this problem.



来源:https://stackoverflow.com/questions/13566751/python-gui-is-not-responding-while-thread-is-executing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!