我一直在试图用多处理模块,用于更新Tkinter的GUI,但是当我运行这段代码,它给酸洗错误。
# Test Code for Tkinter with threads
import Tkinter
from multiprocessing import Queue
import multiprocessing
import time
# Data Generator which will generate Data
def GenerateData():
global q
for i in range(10):
print "Generating Some Data, Iteration %s" %(i)
time.sleep(2)
q.put("Some Data from iteration %s \n" %(i))
def QueueHandler():
global q, text_wid
while True:
if not q.empty():
str = q.get()
text_wid.insert("end", str)
# Main Tkinter Application
def GUI():
global text_wid
tk = Tkinter.Tk()
text_wid = Tkinter.Text(tk)
text_wid.pack()
tk.mainloop()
if __name__ == '__main__':
# Queue which will be used for storing Data
tk = Tkinter.Tk()
text_wid = Tkinter.Text(tk)
q = multiprocessing .Queue()
t1 = multiprocessing.Process(target=GenerateData,args=(q,))
t2 = multiprocessing.Process(target=QueueHandler,args=(q,text_wid))
t1.start()
t2.start()
text_wid.pack()
tk.mainloop()
错误:
PicklingError: Can't pickle <type 'thread.lock'>: it's not found as thread.lock
如果我删除了参数text_wid
,则没有错误报告,但文本组件未更新从queque数据。
更新:
我修改代码以便调用来更新每当有在队列值的GUI的功能,从而防止Tkinter的窗口小部件被传递到单独的过程。 现在,我没有得到任何错误,但小部件不更新的数据。 但是如果我使用的混合Threading
和Multiprocessing
模块即创建一个单独的线程从队列中处理数据,然后它工作正常。 我的问题为什么没有它的工作时,我在运行单独的进程中处理程序代码。 我不是正确地传递数据。 下面是修改后的代码:
# Test Code for Tkinter with threads
import Tkinter
import multiprocessing
from multiprocessing import Queue
import time
import threading
# Data Generator which will generate Data
def GenerateData(q):
for i in range(10):
print "Generating Some Data, Iteration %s" %(i)
time.sleep(2)
q.put("Some Data from iteration %s \n" %(i))
def QueueHandler(q):
while True:
if not q.empty():
str = q.get()
update_gui(str)
#text_wid.insert("end", str)
# Main Tkinter Application
def GUI():
global text_wid
tk = Tkinter.Tk()
text_wid = Tkinter.Text(tk)
text_wid.pack()
tk.mainloop()
def update_gui(str):
global text_wid
text_wid.insert("end", str)
if __name__ == '__main__':
# Queue which will be used for storing Data
tk = Tkinter.Tk()
text_wid = Tkinter.Text(tk)
q = multiprocessing.Queue()
t1 = multiprocessing.Process(target=GenerateData,args=(q,))
t2 = multiprocessing.Process(target=QueueHandler,args=(q,))
t1.start()
t2.start()
text_wid.pack()
tk.mainloop()