我是python编程的新手。请耐心等待。我正在使用python 3,我需要打开一个websocket通信并显示一个图形界面。但是,如果我将它们放在相同的代码中,它们将无法工作,因为它们都适用于循环函数。
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.websocket
from tkinter import *
class ConfigurationHandler(tornado.websocket.WebSocketHandler):
def open(self):
print ("Connection Opened")
self.write_message("connected")
def on_close(self):
print ("Connection Closed")
def on_message(self, message):
print (("Message received: {}").format(message))
self.write_message(message)
def check_origin(self, origin):
return True
try:
application= tornado.web.Application([(r"/",ConfigurationHandler)])
if __name__ == "__main__":
app=tornado.httpserver.HTTPServer(application)
print("waiting")
app.listen(8000)
tornado.ioloop.IOLoop.instance().start()
root=Tk() #I need to see this window
root.mainloop()
except (KeyboardInterrupt,SystemExit):
raise
except:
print("Error")
抱歉我的英文不好, 提前谢谢!
感谢@DoNotClick我解决了我的问题。
SOLUTION:
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.websocket
from tkinter import *
import threading
class ConfigurationHandler(tornado.websocket.WebSocketHandler):
def open(self):
print ("Connection Opened")
self.write_message("connected")
def on_close(self):
print ("Connection Closed")
def on_message(self, message):
print (("Message received: {}").format(message))
self.write_message(message)
def check_origin(self, origin):
return True
class myThread (threading.Thread):
def __init__(self,name):
threading.Thread.__init__(self)
self.name=name
def run(self):
try:
application= tornado.web.Application([(r"/",ConfigurationHandler)])
if __name__ == "__main__":
app=tornado.httpserver.HTTPServer(application)
print("waiting")
app.listen(8000)
tornado.ioloop.IOLoop.instance().start()
except (KeyboardInterrupt,SystemExit):
raise
except:
print("Error")
on_finish()
root=Tk()
thread1=myThread("Connection")
thread1.start()
root.mainloop()
答案 0 :(得分:1)
如果使用tornado.ioloop.IOLoop.instance().start()
,则会启动循环,这将阻止当前线程,直到调用tornado.ioloop.IOLoop.instance().stop()
,但这也会停止龙卷风服务器。如果你想执行像tkinter mainloop这样的另一个循环,那么你必须在另一个线程中同时运行这两个循环。如果你不知道什么线程只是搜索python线程教程