1
0

main.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. #!/usr/bin/env python3
  2. from nicegui import ui
  3. from contextlib import contextmanager
  4. import inspect
  5. import sys
  6. from typing import Callable, Union
  7. import docutils.core
  8. import re
  9. import asyncio
  10. from nicegui.elements.html import Html
  11. from nicegui.elements.markdown import Markdown
  12. from nicegui.events import KeyEventArguments
  13. from nicegui.globals import page_stack
  14. # add docutils css to webpage
  15. page_stack[0].head_html += docutils.core.publish_parts('', writer_name='html')['stylesheet']
  16. @contextmanager
  17. def example(content: Union[Callable, type, str]):
  18. callFrame = inspect.currentframe().f_back.f_back
  19. begin = callFrame.f_lineno
  20. def add_html_anchor(element: Html):
  21. html = element.content
  22. match = re.search(r'<h3.*?>(.*?)</h3>', html)
  23. if not match:
  24. return
  25. headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
  26. if not headline_id:
  27. return
  28. icon = '<span class="material-icons">link</span>'
  29. anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
  30. html = html.replace('<h3', f'<h3 id="{headline_id}"', 1)
  31. html = html.replace('</h3>', f' {anchor}</h3>', 1)
  32. element.view.inner_html = html
  33. with ui.row().classes('flex w-full'):
  34. if isinstance(content, str):
  35. add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
  36. else:
  37. doc = content.__doc__ or content.__init__.__doc__
  38. html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
  39. html = html.replace('<p>', '<h3>', 1)
  40. html = html.replace('</p>', '</h3>', 1)
  41. html = Markdown.apply_tailwind(html)
  42. add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
  43. with ui.card().classes('mt-12 w-2/12'):
  44. with ui.column().classes('flex w-full'):
  45. yield
  46. callFrame = inspect.currentframe().f_back.f_back
  47. end = callFrame.f_lineno
  48. code = inspect.getsource(sys.modules[__name__])
  49. lines = code.splitlines()
  50. while lines[end]:
  51. end += 1
  52. code = lines[begin:end]
  53. code = [l[4:] for l in code]
  54. code.insert(0, '```python')
  55. code.insert(1, 'from nicegui import ui')
  56. if code[2].split()[0] not in ['from', 'import']:
  57. code.insert(2, '')
  58. code.append('')
  59. code.append('ui.run()')
  60. code.append('```')
  61. code = '\n'.join(code)
  62. ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
  63. with ui.row().classes('flex w-full'):
  64. with open('README.md', 'r') as file:
  65. content = file.read()
  66. content = re.sub(r'(?m)^\<img.*\n?', '', content)
  67. ui.markdown(content).classes('w-6/12')
  68. with ui.card().classes('mx-auto mt-24'):
  69. with ui.row():
  70. with ui.column():
  71. ui.button('Click me!', on_click=lambda: output.set_text('Click'))
  72. ui.checkbox('Check me!', on_change=lambda e: output.set_text('Checked' if e.value else 'Unchecked'))
  73. ui.switch('Switch me!', on_change=lambda e: output.set_text('Switched' if e.value else 'Unswitched'))
  74. ui.input('Text', value='abc', on_change=lambda e: output.set_text(e.value))
  75. ui.number('Number', value=3.1415927, format='%.2f', on_change=lambda e: output.set_text(e.value))
  76. with ui.column():
  77. ui.slider(min=0, max=100, value=50, step=0.1, on_change=lambda e: output.set_text(e.value))
  78. ui.radio(['A', 'B', 'C'], value='A', on_change=lambda e: output.set_text(e.value)).props('inline')
  79. ui.toggle(['1', '2', '3'], value='1', on_change=lambda e: output.set_text(e.value)).classes('mx-auto')
  80. ui.select({1: 'One', 2: 'Two', 3: 'Three'}, value=1,
  81. on_change=lambda e: output.set_text(e.value)).classes('mx-auto')
  82. with ui.column().classes('w-24'):
  83. ui.label('Output:')
  84. output = ui.label('').classes('text-bold')
  85. with example(ui.label):
  86. ui.label('some label')
  87. with example(ui.image):
  88. ui.image('http://placeimg.com/640/360/tech')
  89. base64 = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4QCMRXhpZgAATU0AKgAAAAgABQESAAMAAAABAAEAAAEaAAUAAAABAAAASgEbAAUAAAABAAAAUgEoAAMAAAABAAIAAIdpAAQAAAABAAAAWgAAAAAAAABIAAAAAQAAAEgAAAABAAOgAQADAAAAAQABAACgAgAEAAAAAQAAACKgAwAEAAAAAQAAACMAAAAA/8IAEQgAIwAiAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAMCBAEFAAYHCAkKC//EAMMQAAEDAwIEAwQGBAcGBAgGcwECAAMRBBIhBTETIhAGQVEyFGFxIweBIJFCFaFSM7EkYjAWwXLRQ5I0ggjhU0AlYxc18JNzolBEsoPxJlQ2ZJR0wmDShKMYcOInRTdls1V1pJXDhfLTRnaA40dWZrQJChkaKCkqODk6SElKV1hZWmdoaWp3eHl6hoeIiYqQlpeYmZqgpaanqKmqsLW2t7i5usDExcbHyMnK0NTV1tfY2drg5OXm5+jp6vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAQIAAwQFBgcICQoL/8QAwxEAAgIBAwMDAgMFAgUCBASHAQACEQMQEiEEIDFBEwUwIjJRFEAGMyNhQhVxUjSBUCSRoUOxFgdiNVPw0SVgwUThcvEXgmM2cCZFVJInotIICQoYGRooKSo3ODk6RkdISUpVVldYWVpkZWZnaGlqc3R1dnd4eXqAg4SFhoeIiYqQk5SVlpeYmZqgo6SlpqeoqaqwsrO0tba3uLm6wMLDxMXGx8jJytDT1NXW19jZ2uDi4+Tl5ufo6ery8/T19vf4+fr/2wBDAAwMDAwMDBUMDBUeFRUVHikeHh4eKTQpKSkpKTQ+NDQ0NDQ0Pj4+Pj4+Pj5LS0tLS0tXV1dXV2JiYmJiYmJiYmL/2wBDAQ8QEBkXGSsXFytnRjlGZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2f/2gAMAwEAAhEDEQAAAeqBgCIareozvbaK3avBqa52teT6He3z0TqCUZa22r//2gAIAQEAAQUCaVVKTjGnLFqSqqlGuciX+87YgM8ScWhAx5KWUJUdJClKadMye6O//9oACAEDEQE/AUxI86A0ynfb/9oACAECEQE/ASaYZBLxpKNinFh2dv8A/9oACAEBAAY/AmUniHVXxfVx7ZIP9x0GlOJdfa+BeVentkSWR66jsI1HUfF+f4l1UykiqR/CypAorg6n/hvuH5nv/8QAMxABAAMAAgICAgIDAQEAAAILAREAITFBUWFxgZGhscHw0RDh8SAwQFBgcICQoLDA0OD/2gAIAQEAAT8hrchP08Nlp8V+7MHK/wCcEXw8q94vkT4K5DD0fpsJBFkwYvy/8cJBuuX7l82UhL9HmlzVKCOfi+3/ADe6Z2jgePxcMYN/xxYQtAu8UCj/ALXDvn/sBxRB/g3/AL//2gAMAwEAAhEDEQAAEE5gPHEUEAP/xAAzEQEBAQADAAECBQUBAQABAQkBABEhMRBBUWEgcfCRgaGx0cHh8TBAUGBwgJCgsMDQ4P/aAAgBAxEBPxAN4PZaNJuOW/g//9oACAECEQE/EAGt2fwmfzBp3X8P/9oACAEBAAE/ELGubg74j5M+RuAgxMrE4g5c4qAjQh1Oh9GL3/xggJDuHs5H2fY1rQIGDISTZ3KuGYzkk8dSkh4Ah8TJ8c0SsIco+yPRD76/486QSwOdnIpjvmvjAQ8pEx4ixlVcDldAdtawTzP5CSqs1wAPeJDMz0nwvHVlRSYTI1ic6b58RUC4kuSTXmFOJuxknJgsgDQMkjQgj/gCBHee6QjzflUA4/5//9k='
  90. ui.image(base64).style('width:30px')
  91. with example(ui.svg):
  92. svg_content = '''
  93. <svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
  94. <circle cx="100" cy="100" r="78" fill="yellow" stroke="black" stroke-width="3" />
  95. <circle cx="61" cy="82" r="12" />
  96. <circle cx="127" cy="82" r="12" />
  97. <path d="m136.81 116.53c.69 36.17-74.11 42-81.52-.73" style="fill:none; stroke: black; stroke-width: 5;" />
  98. </svg>'''
  99. ui.svg(svg_content)
  100. overlay = '''### Captions and Overlays
  101. By nesting elements inside a `ui.image` you can create augmentations.
  102. Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
  103. To overlay an svg, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
  104. '''
  105. with example(overlay):
  106. with ui.image('http://placeimg.com/640/360/nature'):
  107. ui.label('nice').classes('absolute-bottom text-subtitle2 text-center')
  108. with ui.image('https://cdn.pixabay.com/photo/2020/07/13/12/56/mute-swan-5400675__340.jpg'):
  109. svg_content = '''
  110. <svg viewBox="0 0 510 340" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
  111. <circle cx="200" cy="200" r="100" fill="none" stroke="red" stroke-width="10" />
  112. </svg>'''
  113. ui.svg(svg_content).style('background:transparent')
  114. with example(ui.markdown):
  115. ui.markdown('### Headline\nWith hyperlink to [GitHub](https://github.com/zauberzeug/nicegui).')
  116. with example(ui.html):
  117. ui.html('<p>demo paragraph in <strong>html</strong></p>')
  118. with example(ui.button):
  119. def button_increment():
  120. global button_count
  121. button_count += 1
  122. button_result.set_text(f'pressed: {button_count}')
  123. button_count = 0
  124. ui.button('Button', on_click=button_increment)
  125. button_result = ui.label('pressed: 0')
  126. async_button = '''### Button with asynchronous action
  127. The button element does also support asynchronous action.
  128. '''
  129. with example(async_button):
  130. async def async_task():
  131. ui.notify('Asynchronous task started')
  132. await asyncio.sleep(5)
  133. ui.notify('Asynchronous task finished')
  134. ui.button('Start asynchronous task', on_click=async_task)
  135. with example(ui.checkbox):
  136. ui.checkbox('check me', on_change=lambda e: checkbox_state.set_text(e.value))
  137. with ui.row():
  138. ui.label('the checkbox is:')
  139. checkbox_state = ui.label('False')
  140. with example(ui.switch):
  141. ui.switch('switch me', on_change=lambda e: switch_state.set_text("ON" if e.value else'OFF'))
  142. with ui.row():
  143. ui.label('the switch is:')
  144. switch_state = ui.label('OFF')
  145. with example(ui.slider):
  146. slider = ui.slider(min=0, max=100, value=50).props('label')
  147. ui.label().bind_text_from(slider, 'value')
  148. with example(ui.input):
  149. ui.input(
  150. label='Text',
  151. placeholder='press ENTER to apply',
  152. on_change=lambda e: result.set_text('you typed: ' + e.value),
  153. ).classes('w-full')
  154. result = ui.label('')
  155. with example(ui.number):
  156. number_input = ui.number(label='Number', value=3.1415927, format='%.2f')
  157. with ui.row():
  158. ui.label('underlying value: ')
  159. ui.label().bind_text_from(number_input, 'value')
  160. with example(ui.radio):
  161. radio = ui.radio([1, 2, 3], value=1).props('inline')
  162. ui.radio({1: 'A', 2: 'B', 3: 'C'}, value=1).props('inline').bind_value(radio, 'value')
  163. with example(ui.toggle):
  164. toggle = ui.toggle([1, 2, 3], value=1)
  165. ui.toggle({1: 'A', 2: 'B', 3: 'C'}, value=1).bind_value(toggle, 'value')
  166. with example(ui.select):
  167. with ui.row():
  168. select = ui.select([1, 2, 3], value=1).props('inline')
  169. ui.select({1: 'One', 2: 'Two', 3: 'Three'}, value=1).props('inline').bind_value(select, 'value')
  170. with example(ui.upload):
  171. ui.upload(on_upload=lambda files: content.set_text(files))
  172. content = ui.label()
  173. with example(ui.plot):
  174. from matplotlib import pyplot as plt
  175. import numpy as np
  176. with ui.plot(figsize=(2.5, 1.8)):
  177. x = np.linspace(0.0, 5.0)
  178. y = np.cos(2 * np.pi * x) * np.exp(-x)
  179. plt.plot(x, y, '-')
  180. plt.xlabel('time (s)')
  181. plt.ylabel('Damped oscillation')
  182. with example(ui.line_plot):
  183. lines = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)).with_legend(['sin', 'cos'], loc='upper center', ncol=2)
  184. line_updates = ui.timer(0.1, lambda: lines.push([datetime.now()], [
  185. [np.sin(datetime.now().timestamp()) + 0.02 * np.random.randn()],
  186. [np.cos(datetime.now().timestamp()) + 0.02 * np.random.randn()],
  187. ]), active=False)
  188. ui.checkbox('active').bind_value(line_updates, 'active')
  189. with example(ui.log):
  190. from datetime import datetime
  191. log = ui.log(max_lines=10).classes('h-16')
  192. ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
  193. with example(ui.scene):
  194. with ui.scene(width=200, height=200) as scene:
  195. scene.sphere().material('#4488ff')
  196. scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
  197. scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
  198. with scene.group().move(z=2):
  199. box1 = scene.box().move(x=2)
  200. scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
  201. scene.box(wireframe=True).material('#888888').move(x=2, y=2)
  202. scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
  203. scene.curve([-4, -2, 0], [-4, -1, 0], [-3, -1, 0], [-3, 0, 0]).material('#008800')
  204. logo = "https://avatars.githubusercontent.com/u/2843826"
  205. scene.texture(logo, [[[0, 3, 0], [3, 3, 0]], [[0, 0, 0], [3, 0, 0]]]).move(1, -2)
  206. teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
  207. scene.stl(teapot).scale(0.2).move(-3, 4)
  208. with example(ui.joystick):
  209. ui.joystick(
  210. color='blue',
  211. size=50,
  212. on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
  213. on_end=lambda _: coordinates.set_text('0, 0'))
  214. coordinates = ui.label('0, 0')
  215. with example(ui.dialog):
  216. with ui.dialog() as dialog:
  217. with ui.card():
  218. ui.label('Hello world!')
  219. ui.button('Close', on_click=dialog.close)
  220. ui.button('Open dialog', on_click=dialog.open)
  221. with example(ui.menu):
  222. choice = ui.label('Try the menu.')
  223. with ui.menu() as menu:
  224. ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
  225. ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
  226. ui.menu_separator()
  227. ui.menu_item('Close', on_click=menu.close)
  228. ui.button('Open menu', on_click=menu.open).props('color=secondary')
  229. with example(ui.notify):
  230. ui.button('Show notification', on_click=lambda: ui.notify('Some message', close_button='OK'))
  231. design = '''### Styling
  232. NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
  233. Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
  234. Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
  235. You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
  236. If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
  237. All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
  238. '''
  239. with example(design):
  240. ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
  241. ui.button().props('icon=touch_app outline round').classes('shadow-lg ml-14')
  242. with example(ui.colors):
  243. ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
  244. ui.button('Default', on_click=lambda: ui.colors())
  245. ui.colors()
  246. with example(ui.card):
  247. with ui.card().tight():
  248. ui.image('http://placeimg.com/640/360/nature')
  249. with ui.card_section():
  250. ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
  251. with example(ui.column):
  252. with ui.column():
  253. ui.label('label 1')
  254. ui.label('label 2')
  255. ui.label('label 3')
  256. with example(ui.row):
  257. with ui.row():
  258. ui.label('label 1')
  259. ui.label('label 2')
  260. ui.label('label 3')
  261. clear = '''### Clear Containers
  262. To remove all elements from a row, column or card container, use the `clear()` method.
  263. '''
  264. with example(clear):
  265. container = ui.row()
  266. def add_face():
  267. with container:
  268. ui.icon('face')
  269. add_face()
  270. ui.button('Add', on_click=add_face)
  271. ui.button('Clear', on_click=container.clear)
  272. binding = '''### Bindings
  273. With help of the [binding](https://pypi.org/project/binding/) package NiceGUI is able to directly bind UI elements to models.
  274. Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
  275. Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
  276. To define a one-way binding use the `_from` and `_to` variants of these methods.
  277. Just pass a property of the model as parameter to these methods to create the binding.
  278. '''
  279. with example(binding):
  280. class Demo:
  281. def __init__(self):
  282. self.number = 1
  283. demo = Demo()
  284. v = ui.checkbox('visible', value=True)
  285. with ui.column().bind_visibility_from(v, 'value'):
  286. ui.slider(min=1, max=3).bind_value(demo, 'number')
  287. ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
  288. ui.number().bind_value(demo, 'number')
  289. with example(ui.timer):
  290. from datetime import datetime
  291. with ui.row().classes('items-center'):
  292. clock = ui.label()
  293. t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
  294. ui.checkbox('active').bind_value(t, 'active')
  295. with ui.row():
  296. def lazy_update():
  297. new_text = datetime.now().strftime('%X.%f')[:-5]
  298. if lazy_clock.text[:8] == new_text[:8]:
  299. return False
  300. lazy_clock.text = new_text
  301. lazy_clock = ui.label()
  302. ui.timer(interval=0.1, callback=lazy_update)
  303. lifecycle = '''### Lifecycle
  304. You can run a function or coroutine on startup as a parallel task by passing it to `ui.on_startup`.
  305. If NiceGUI is shut down or restarted, the tasks will be automatically canceled (for example when you make a code change).
  306. You can also execute cleanup code with `ui.on_shutdown`.
  307. '''
  308. with example(lifecycle):
  309. with ui.row() as row:
  310. ui.label('count:')
  311. count_label = ui.label('0')
  312. count = 0
  313. async def counter():
  314. global count
  315. while True:
  316. count_label.text = str(count)
  317. count += 1
  318. await row.view.update()
  319. await asyncio.sleep(1)
  320. ui.on_startup(counter())
  321. with example(ui.page):
  322. with ui.page('/other_page') as other:
  323. ui.label('Welcome to the other side')
  324. ui.link('Back to main page', '/')
  325. ui.link('Visit other page', '/other_page')
  326. with example(ui.open):
  327. with ui.page('/yet_another_page') as other:
  328. ui.label('Welcome to yet another page')
  329. ui.button('RETURN', on_click=lambda e: ui.open('/', e.socket))
  330. ui.button('REDIRECT', on_click=lambda e: ui.open('/yet_another_page', e.socket))
  331. add_route = """### Route
  332. Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
  333. Routed paths must start with a `'/'`.
  334. """
  335. with example(add_route):
  336. import starlette
  337. ui.add_route(starlette.routing.Route(
  338. '/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
  339. ))
  340. ui.link('Try the new route!', '/new/route')
  341. get_decorator = """### Get decorator
  342. Syntactic sugar to add routes.
  343. Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/1'`.
  344. """
  345. with example(get_decorator):
  346. import starlette
  347. @ui.get('/another/route/{id}')
  348. def produce_plain_response(request):
  349. path_param_id = request.path_params['id']
  350. return starlette.responses.PlainTextResponse(f'Response {path_param_id}')
  351. ui.link('Try yet another route!', '/another/route/1')
  352. with example(ui.keyboard):
  353. from nicegui.events import KeyEventArguments
  354. def handle_key(e: KeyEventArguments):
  355. if e.key == 'f' and not e.action.repeat:
  356. if e.action.keyup:
  357. ui.notify('f was just released')
  358. elif e.action.keydown:
  359. ui.notify('f was just pressed')
  360. if e.modifiers.shift and e.action.keydown:
  361. if e.key.arrow_left:
  362. ui.notify('going left')
  363. elif e.key.arrow_right:
  364. ui.notify('going right')
  365. elif e.key.arrow_up:
  366. ui.notify('going up')
  367. elif e.key.arrow_down:
  368. ui.notify('going down')
  369. keyboard = ui.keyboard(on_key=handle_key)
  370. ui.label('Key events can be caught globally by using the keyboard element.')
  371. ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
  372. ui.run()