SHARE
TWEET

Untitled

a guest Jun 16th, 2019 58 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3.  
  4. from tkinter import *
  5. from tkinter import messagebox
  6. import asyncio
  7. import random
  8.  
  9. def do_freezed():
  10.     """ Button-Event-Handler to see if a button on GUI works. """
  11.     messagebox.showinfo(message='Tkinter is reacting.')
  12.  
  13. def do_tasks():
  14.     """ Button-Event-Handler starting the asyncio part. """
  15.     loop = asyncio.get_event_loop()
  16.     try:
  17.         loop.run_until_complete(do_urls())
  18.     finally:
  19.         loop.close()
  20.  
  21. async def one_url(url):
  22.     """ One task. """
  23.     sec = random.randint(1, 15)
  24.     await asyncio.sleep(sec)
  25.     return 'url: {}tsec: {}'.format(url, sec)
  26.  
  27. async def do_urls():
  28.     """ Creating and starting 10 tasks. """
  29.     tasks = [
  30.         one_url(url)
  31.         for url in range(10)
  32.     ]
  33.     completed, pending = await asyncio.wait(tasks)
  34.     results = [task.result() for task in completed]
  35.     print('n'.join(results))
  36.  
  37.  
  38. if __name__ == '__main__':
  39.     root = Tk()
  40.  
  41.     buttonT = Button(master=root, text='Asyncio Tasks', command=do_tasks)
  42.     buttonT.pack()
  43.     buttonX = Button(master=root, text='Freezed???', command=do_freezed)
  44.     buttonX.pack()
  45.  
  46.     root.mainloop()
  47.      
  48. from tkinter import *
  49. from tkinter import messagebox
  50. import asyncio
  51. import threading
  52. import random
  53.  
  54. def _asyncio_thread(async_loop):
  55.     async_loop.run_until_complete(do_urls())
  56.  
  57.  
  58. def do_tasks(async_loop):
  59.     """ Button-Event-Handler starting the asyncio part. """
  60.     threading.Thread(target=_asyncio_thread, args=(async_loop,)).start()
  61.  
  62.  
  63. async def one_url(url):
  64.     """ One task. """
  65.     sec = random.randint(1, 8)
  66.     await asyncio.sleep(sec)
  67.     return 'url: {}tsec: {}'.format(url, sec)
  68.  
  69. async def do_urls():
  70.     """ Creating and starting 10 tasks. """
  71.     tasks = [one_url(url) for url in range(10)]
  72.     completed, pending = await asyncio.wait(tasks)
  73.     results = [task.result() for task in completed]
  74.     print('n'.join(results))
  75.  
  76.  
  77. def do_freezed():
  78.     messagebox.showinfo(message='Tkinter is reacting.')
  79.  
  80. def main(async_loop):
  81.     root = Tk()
  82.     Button(master=root, text='Asyncio Tasks', command= lambda:do_tasks(async_loop)).pack()
  83.     buttonX = Button(master=root, text='Freezed???', command=do_freezed).pack()
  84.     root.mainloop()
  85.  
  86. if __name__ == '__main__':
  87.     async_loop = asyncio.get_event_loop()
  88.     main(async_loop)
  89.      
  90. """Proof of concept: integrate tkinter, asyncio and async iterator.
  91.  
  92. Terry Jan Reedy, 2016 July 25
  93. """
  94.  
  95. import asyncio
  96. from random import randrange as rr
  97. import tkinter as tk
  98.  
  99.  
  100. class App(tk.Tk):
  101.  
  102.     def __init__(self, loop, interval=1/120):
  103.         super().__init__()
  104.         self.loop = loop
  105.         self.protocol("WM_DELETE_WINDOW", self.close)
  106.         self.tasks = []
  107.         self.tasks.append(loop.create_task(self.rotator(1/60, 2)))
  108.         self.tasks.append(loop.create_task(self.updater(interval)))
  109.  
  110.     async def rotator(self, interval, d_per_tick):
  111.         canvas = tk.Canvas(self, height=600, width=600)
  112.         canvas.pack()
  113.         deg = 0
  114.         color = 'black'
  115.         arc = canvas.create_arc(100, 100, 500, 500, style=tk.CHORD,
  116.                                 start=0, extent=deg, fill=color)
  117.         while await asyncio.sleep(interval, True):
  118.             deg, color = deg_color(deg, d_per_tick, color)
  119.             canvas.itemconfigure(arc, extent=deg, fill=color)
  120.  
  121.     async def updater(self, interval):
  122.         while True:
  123.             self.update()
  124.             await asyncio.sleep(interval)
  125.  
  126.     def close(self):
  127.         for task in self.tasks:
  128.             task.cancel()
  129.         self.loop.stop()
  130.         self.destroy()
  131.  
  132.  
  133. def deg_color(deg, d_per_tick, color):
  134.     deg += d_per_tick
  135.     if 360 <= deg:
  136.         deg %= 360
  137.         color = '#%02x%02x%02x' % (rr(0, 256), rr(0, 256), rr(0, 256))
  138.     return deg, color
  139.  
  140. loop = asyncio.get_event_loop()
  141. app = App(loop)
  142. loop.run_forever()
  143. loop.close()
  144.      
  145. from tkinter import *
  146. from tkinter import messagebox
  147. import asyncio
  148. import random
  149.  
  150. def do_freezed():
  151.     """ Button-Event-Handler to see if a button on GUI works. """
  152.     messagebox.showinfo(message='Tkinter is reacting.')
  153.  
  154. def do_tasks():
  155.     """ Button-Event-Handler starting the asyncio part. """
  156.     loop = asyncio.get_event_loop()
  157.     try:
  158.         loop.run_until_complete(do_urls())
  159.     finally:
  160.         loop.close()
  161.  
  162. async def one_url(url):
  163.     """ One task. """
  164.     sec = random.randint(1, 15)
  165.     root.update_idletasks()  # ADDED: Allow tkinter to update gui.
  166.     await asyncio.sleep(sec)
  167.     return 'url: {}tsec: {}'.format(url, sec)
  168.  
  169. async def do_urls():
  170.     """ Creating and starting 10 tasks. """
  171.     tasks = [one_url(url) for url in range(10)]
  172.     completed, pending = await asyncio.wait(tasks)
  173.     results = [task.result() for task in completed]
  174.     print('n'.join(results))
  175.  
  176.  
  177. if __name__ == '__main__':
  178.     root = Tk()
  179.  
  180.     buttonT = Button(master=root, text='Asyncio Tasks', command=do_tasks)
  181.     buttonT.pack()
  182.     buttonX = Button(master=root, text='Freezed???', command=do_freezed)
  183.     buttonX.pack()
  184.  
  185.     root.mainloop()
  186.      
  187. import threading
  188. from functools import partial
  189. from tkinter import *
  190. from tkinter import messagebox
  191. import asyncio
  192. import random
  193.  
  194.  
  195. # Please wrap all this code in a nice App class, of course
  196.  
  197. def _run_aio_loop(loop):
  198.     asyncio.set_event_loop(loop)
  199.     loop.run_forever()
  200. aioloop = asyncio.new_event_loop()
  201. t = threading.Thread(target=partial(_run_aio_loop, aioloop))
  202. t.daemon = True  # Optional depending on how you plan to shutdown the app
  203. t.start()
  204.  
  205. buttonT = None
  206.  
  207. def do_freezed():
  208.     """ Button-Event-Handler to see if a button on GUI works. """
  209.     messagebox.showinfo(message='Tkinter is reacting.')
  210.  
  211. def do_tasks():
  212.     """ Button-Event-Handler starting the asyncio part. """
  213.     buttonT.configure(state=DISABLED)
  214.     asyncio.run_coroutine_threadsafe(do_urls(), aioloop)
  215.  
  216. async def one_url(url):
  217.     """ One task. """
  218.     sec = random.randint(1, 3)
  219.     # root.update_idletasks()  # We can delete this now
  220.     await asyncio.sleep(sec)
  221.     return 'url: {}tsec: {}'.format(url, sec)
  222.  
  223. async def do_urls():
  224.     """ Creating and starting 10 tasks. """
  225.     tasks = [one_url(url) for url in range(3)]
  226.     completed, pending = await asyncio.wait(tasks)
  227.     results = [task.result() for task in completed]
  228.     print('n'.join(results))
  229.     buttonT.configure(state=NORMAL)  # Tk doesn't seem to care that this is called on another thread
  230.  
  231.  
  232. if __name__ == '__main__':
  233.     root = Tk()
  234.  
  235.     buttonT = Button(master=root, text='Asyncio Tasks', command=do_tasks)
  236.     buttonT.pack()
  237.     buttonX = Button(master=root, text='Freezed???', command=do_freezed)
  238.     buttonX.pack()
  239.  
  240.     root.mainloop()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top