SHARE
TWEET

Python UDP Asyncio and Tkinter

rharder Feb 3rd, 2017 (edited) 131 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env python3
  2. """
  3. An example of how to use asyncio event loops and tkinter event loops in the same program.
  4.  
  5. Discussed here: http://blog.iharder.net/2017/02/03/python-asyncio-and-tkinter-together/
  6. UDP Version: http://pastebin.com/PeHHRR4E
  7. TCP Version: http://pastebin.com/ZGeDULR9
  8. """
  9. import threading
  10. import tkinter as tk
  11. import asyncio
  12. from functools import partial
  13.  
  14. __author__ = "Robert Harder"
  15.  
  16.  
  17. def main():
  18.     tk_root = tk.Tk()
  19.     Main(tk_root)
  20.     tk_root.mainloop()
  21.  
  22.  
  23. class Main:
  24.     def __init__(self, tk_root):
  25.         # Tk setup
  26.         self.lbl_var = tk.StringVar()
  27.         tk_root.title("Tk Asyncio Demo")
  28.         tk.Label(tk_root, text="Incoming Message, UDP Port 9999:").pack()
  29.         tk.Label(tk_root, textvariable=self.lbl_var).pack()
  30.  
  31.         # Prepare coroutine to connect server
  32.         self.transport = None  # type: asyncio.DatagramTransport
  33.  
  34.         @asyncio.coroutine
  35.         def _connect():
  36.             loop = asyncio.get_event_loop()  # Pulls the new event loop because that is who launched this coroutine
  37.             yield from loop.create_datagram_endpoint(lambda: self, local_addr=("0.0.0.0", 9999))
  38.  
  39.         # Thread that will handle io loop
  40.         def _run(loop):
  41.             asyncio.set_event_loop(loop)
  42.             loop.run_forever()
  43.  
  44.         ioloop = asyncio.new_event_loop()
  45.         asyncio.run_coroutine_threadsafe(_connect(), loop=ioloop)  # Schedules connection
  46.         t = threading.Thread(target=partial(_run, ioloop))
  47.         t.daemon = True  # won't hang app when it closes
  48.         t.start()  # Server will connect now
  49.  
  50.     def connection_made(self, transport):
  51.         print("connection_made")
  52.         self.transport = transport
  53.  
  54.     def connection_lost(self, exc):
  55.         print("connection_lost")
  56.  
  57.     def datagram_received(self, data, addr):
  58.         data_string = data.decode()
  59.         print("datagram_received", data_string.strip(), addr)
  60.         self.transport.sendto("RECVD: {}".format(data_string).encode(), addr=addr)
  61.         self.lbl_var.set(data_string.strip())
  62.  
  63.     def error_received(self, exc):
  64.         print("error_received")
  65.  
  66.  
  67. if __name__ == "__main__":
  68.     main()
RAW Paste Data
Want to get better at Python?
Learn to code Python in 2017
Pastebin PRO Summer Special!
Get 40% OFF on Pastebin PRO accounts!
Top