我们实现了使用 Tkinter GUI 的分布式聊天。当我将系统更新到 Fedora18 时,我在调用 Tkinter 事件时遇到异常,几乎与此处描述相同:
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib64/python2.7/threading.py", line 551, in bootstrap_inner self.run()
File "/usr/lib64/python2.7/threading.py", line 504, in run self.target(*self.__args, **self.__kwargs)
File "/hachat/peer.py", line 156, in startRecvLoop
self.processMessage(msg, addr)
File "/hachat/peer.py", line 222, in processMessage
self.gui.receive(msg)
File "/hachat/gui.py", line 74, in receive
self.textfenster.insert(END,msg.name+": "+msg.text+'n')
File "/usr/lib64/python2.7/lib-tk/Tkinter.py", line 2986, in insert
self.tk.call((self._w, 'insert', index, chars) + args)
TclError: out of stack space (infinite loop?)
这是从 gui 类中截取出来的:
import Tkinter
import ScrolledText
import tkMessageBox
import tkSimpleDialog
import threading
class gui(object):
def __init__(self, parent):
self.root = Tkinter.Tk()
self.textfenster = ScrolledText.ScrolledText(self.fpopup,width=90,height=24,background='white')
self.textfenster.pack(fill=Tkinter.BOTH, expand=Tkinter.YES)
def run(self):
self.guiRunThread = threading.Thread(target=self.root.mainloop())
self.guiRunThread.daemon = True
self.guiRunThread.start()
def receive(self,msg):
self.textfenster.insert(Tkinter.END,msg.name+": "+msg.text+'n')
self.textfenster.see(Tkinter.END)
异常仅出现在我的系统上,原因似乎是tk没有在支持线程的情况下编译。我必须摆脱这种 Exeption - 由于程序是分布式的,它需要在不同的系统上运行。所以我要求如何摆脱这个异常以及获取支持线程的 tk 的提示。我使用的Python版本是2.7.3,Tcl/Tk版本8.5。 import Tkinter; Tkinter.Tk().tk.eval("puts $tcl_platform(threaded)")
也回馈了一个例外。
我解决了队列与Tk通信的问题。有关示例,请参阅 Mutli-threading python with Tkinter!
这个工作:
from Tkinter import *
from ScrolledText import ScrolledText
from threading import Thread
scrolled = None
def start():
global scrolled
root = Tk()
scrolled = ScrolledText(root)
scrolled.pack(fill=BOTH, expand=YES)
return root
Thread(target=start().mainloop).start()
print scrolled.get(0.0, END)