我正在为扭曲的应用程序(服务器端)构建一个简单的tkinter gui。下面的代码运行良好,除非我想编写从twisted(dataReceived方法)发送的数据,它删除Text小部件中的所有先前消息并在第一行写入。我想在该Text小部件中编写客户端消息,而不删除其中包含的先前文本。
from Tkinter import *
from twisted.internet import reactor, tksupport
from twisted.internet.protocol import Protocol, Factory
class MultiEcho(Protocol):
def __init__(self, factory):
self.factory = factory
def connectionMade(self,*args):
self.factory.echoers.append(self)
def dataReceived(self, data):
gettest = str(data)
get = App()
get.write(gettest)
def connectionLost(self, reason):
# self.factory.echoers.remove(self)
pass
class MultiEchoFactory(Factory):
def __init__(self):
self.echoers = []
def buildProtocol(self, addr):
return MultiEcho(self)
class App(Frame):
def write(self,text):
message = str(text)
self.display.configure(state='normal')
self.display.insert(END,message + '\n')
self.display.configure(state='disabled')
def handle(self,event=None):
msg = self.entry.get()
self.entry.delete(0,END)
self.write(msg + '\n')
self.display.yview(END)
def __init__(self,parent=None):
Frame.__init__(self,parent)
self.parent=parent
self.initUI()
def kill(self):
reactor.stop()
self.quit()
def initUI(self):
self.grid(row=0,sticky=N+E+S+W)
self.columnconfigure(0,weight=1)
self.rowconfigure(0,weight=1)
self.display = Text(self)
self.display.grid(row=0,sticky=N+E+S+W)
self.yscroll = Scrollbar(self,command=self.display.yview)
self.yscroll.grid(row=0,column=1,sticky=N+S)
self.display.config(yscrollcommand=self.yscroll.set)
self.entry = Entry(self)
self.entry.grid(row=1,sticky=E+W)
self.entry.bind('<Return>',self.handle)
self.master.protocol('WM_DELETE_WINDOW',self.kill)
def main():
root = Tk()
ex = App(root)
tksupport.install(root)
mef = MultiEchoFactory()
reactor.listenTCP(8000, mef)
reactor.run()
if __name__ == '__main__':
main()
请帮我解决这个问题。感谢您花时间阅读本文。
答案 0 :(得分:1)
通过反复调用App
,您将在每次通话时生成新的App
实例。
相反,您应该保留对您在ex
中创建的main
的引用,并将其传递给MultiEchoFactory.__init__
,将其保存在self
上,然后再保存到MultiEcho
} self.app.write(...)
而不是App().write(...)
。