I'm new in python programming. Be patient please. I'm using python 3 and I need to open a websocket communication and display a graphical interface. But if I put them in the same code they won't works because they both works on a loop function.
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")
Sorry for my bad english, thanks in advance!
Thanks to @DoNotClick I solved my problem.
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()
If you use tornado.ioloop.IOLoop.instance().start()
a loop is started which will block the current thread until tornado.ioloop.IOLoop.instance().stop()
is called but this would also stop the tornado server. If you want to execute another loop like the tkinter mainloop then you have to make it in another thread to run the two loops at the same time. If you dont know what threads are just search for a python thread tutorial