我正在尝试使Tkinter应用程序能够响应来自其他应用程序的请求,例如gRPC服务器。 GUI启动,但是使用它的简单程序挂起等待响应。
GUI如下所示:
import ScrolledText
from Tkinter import BOTH, END, LEFT
from concurrent import futures
import grpc
import output_pb2
import output_pb2_grpc
import threading
from contextlib import contextmanager
import time
class TextWindow():
def __init__(self, port=51151):
self.port = port
print('Starting output window')
self.stext = ScrolledText.ScrolledText(bg='white', height=10)
self.stext.pack(fill=BOTH, side=LEFT, expand=True)
self.stext.focus_set()
self.output = Output(self)
self.stext.bind('<Destroy>', self.close, add='+')
with self.serve():
print('Listening on test')
while True:
self.stext.update()
self.stext.update_idletasks()
time.sleep(0.5)
def append(self, text):
self.stext.insert(END, text)
def close(self, event=None):
self.server.stop(None)
@contextmanager
def serve(self):
self.server = grpc.server(futures.ProcessPoolExecutor(max_workers=10))
output_pb2_grpc.add_OutputServicer_to_server(self.output, self.server)
self.server.add_insecure_port('[::]:%d' % self.port)
self.server.start()
yield
self.server.stop(0)
class Output(output_pb2_grpc.OutputServicer):
"""
Chatbot relay service
"""
def __init__(self, window):
self.window = window
def Output(self, request, context):
"""Methods to get information from the active engine.
"""
self.window.append(request.text)
return output_pb2.Text(message='Got string %s!' % request.text)
if __name__ == "__main__":
TextWindow()
(serve
方法是从this blog post中轻松获取的,我尝试了其他事情,例如在新线程中运行,tkinter mainloop
等)
示例调用者脚本如下所示:
import grpc
import output_pb2_grpc
import output_pb2
def run(text='Hi!'):
channel = grpc.insecure_channel('localhost:51151')
stub = output_pb2_grpc.OutputStub(channel)
string = output_pb2.Text(text=text)
#Line that hangs:
response = stub.Out(string)
print("Output client received: " + response.text)
if __name__ == '__main__':
run()
GUI似乎运行良好,但是脚本(在脚本之后单独启动)却无法运行。可以预期的是,文本Hi
出现在GUI中,Got string Hi!!
出现在控制台中。但是,GUI中什么也没有出现,并且脚本没有完成。我认为存在一些线程问题,但不知道它是什么。我使用python 2.7。有人可以帮忙吗?