main.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. #!/usr/bin/env python3
  2. from nicegui import ui, wp
  3. from contextlib import contextmanager
  4. import inspect
  5. from nicegui.elements.markdown import Markdown
  6. from nicegui.elements.element import Element
  7. import sys
  8. from typing import Union
  9. import docutils.core
  10. import re
  11. import asyncio
  12. # add docutils css to webpage
  13. wp.head_html += docutils.core.publish_parts('', writer_name='html')['stylesheet']
  14. @contextmanager
  15. def example(content: Union[Element, str]):
  16. callFrame = inspect.currentframe().f_back.f_back
  17. begin = callFrame.f_lineno
  18. with ui.row().classes('flex w-full'):
  19. if isinstance(content, str):
  20. ui.markdown(content).classes('mr-8 w-4/12')
  21. else:
  22. doc = content.__init__.__doc__
  23. if doc:
  24. html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
  25. html = html.replace('<p>', '<h3>', 1)
  26. html = html.replace('</p>', '</h3>', 1)
  27. html = Markdown.apply_tailwind(html)
  28. ui.html(html).classes('mr-8 w-4/12')
  29. else:
  30. ui.label(content.__name__).classes('text-h5')
  31. with ui.card().classes('mt-12 w-2/12'):
  32. yield
  33. callFrame = inspect.currentframe().f_back.f_back
  34. end = callFrame.f_lineno
  35. code = inspect.getsource(sys.modules[__name__])
  36. code = code.splitlines()[begin:end]
  37. code = [l[4:] for l in code]
  38. code.insert(0, '```python')
  39. code.insert(1, 'from nicegui import ui')
  40. code.append('```')
  41. code = '\n'.join(code)
  42. ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
  43. with ui.row().classes('flex w-full'):
  44. with open('README.md', 'r') as file:
  45. content = file.read()
  46. content = re.sub(r'(?m)^\<img.*\n?', '', content)
  47. ui.markdown(content).classes('w-6/12')
  48. with ui.card().classes('mx-auto mt-24'):
  49. with ui.row():
  50. with ui.column():
  51. ui.button('Click me!', on_click=lambda: output.set_text('Click'))
  52. ui.checkbox('Check me!', on_change=lambda e: output.set_text('Checked' if e.value else 'Unchecked'))
  53. ui.switch('Switch me!', on_change=lambda e: output.set_text('Switched' if e.value else 'Unswitched'))
  54. ui.input('Text', value='abc', on_change=lambda e: output.set_text(e.value))
  55. ui.number('Number', value=3.1415927, format='%.2f', on_change=lambda e: output.set_text(e.value))
  56. with ui.column():
  57. ui.slider(min=0, max=100, value=50, step=0.1, on_change=lambda e: output.set_text(e.value))
  58. ui.radio(['A', 'B', 'C'], value='A', on_change=lambda e: output.set_text(e.value)).props('inline')
  59. ui.toggle(['1', '2', '3'], value='1', on_change=lambda e: output.set_text(e.value)).classes('mx-auto')
  60. ui.select({1: 'One', 2: 'Two', 3: 'Three'}, value=1,
  61. on_change=lambda e: output.set_text(e.value)).classes('mx-auto')
  62. with ui.column().classes('w-24'):
  63. ui.label('Output:')
  64. output = ui.label('').classes('text-bold')
  65. design = '''### Styling & Design
  66. NiceGUI uses the [Quasar Framework](https://quasar.dev/) and hence has its full design power.
  67. 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):
  68. Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
  69. You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
  70. If you really need to apply css you can use the `styles` method. Here the delimer is `;` instad of a blank space.
  71. '''
  72. with (example(design)):
  73. ui.radio(['x', 'y', 'z']).props('inline color=green')
  74. ui.button().props('icon=touch_app outline round').classes('shadow-lg ml-14')
  75. binding = '''### Bindings
  76. With help of the [binding](https://pypi.org/project/binding/) package NiceGUI is able to directly bind UI elements to models.
  77. Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
  78. Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
  79. To define a one-way binding use the `_from` and `_to` variants of these methods.
  80. Just pass a property of the model as parameter to these methods to create the binding.
  81. '''
  82. with (example(binding)):
  83. class Demo:
  84. def __init__(self):
  85. self.number = 1
  86. demo = Demo()
  87. v = ui.checkbox('visible', value=True)
  88. with ui.column().bind_visibility_from(v.value):
  89. ui.slider(min=1, max=3).bind_value(demo.number)
  90. ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo.number)
  91. ui.number().bind_value(demo.number)
  92. lifecycle = '''### Lifecycle
  93. You can run a function or coroutine on startup as a parallel task by passing it to `ui.on_startup`.
  94. If NiceGui is shut down or restarted the tasks will be automatically canceled (for example when you make a code change).
  95. You can also execude cleanup code with `ui.on_shutdown`.
  96. '''
  97. with (example(lifecycle)):
  98. count_label = ui.label('count: 0')
  99. count = 0
  100. async def update_count():
  101. global count
  102. while True:
  103. count_label.text = f'count: {count}'
  104. count += 1
  105. await asyncio.sleep(1)
  106. ui.on_startup(update_count())
  107. with example(ui.timer):
  108. from datetime import datetime
  109. clock = ui.label()
  110. t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X")))
  111. ui.checkbox('active').bind_value(t.active)
  112. with example(ui.label):
  113. ui.label('some label')
  114. with example(ui.image):
  115. ui.image('http://placeimg.com/640/360/tech')
  116. base64 = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4QCMRXhpZgAATU0AKgAAAAgABQESAAMAAAABAAEAAAEaAAUAAAABAAAASgEbAAUAAAABAAAAUgEoAAMAAAABAAIAAIdpAAQAAAABAAAAWgAAAAAAAABIAAAAAQAAAEgAAAABAAOgAQADAAAAAQABAACgAgAEAAAAAQAAACKgAwAEAAAAAQAAACMAAAAA/8IAEQgAIwAiAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAMCBAEFAAYHCAkKC//EAMMQAAEDAwIEAwQGBAcGBAgGcwECAAMRBBIh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QEAAT8hrchP08Nlp8V+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='
  117. ui.image(base64).style('width:30px')
  118. with example(ui.svg):
  119. svg_content = '''
  120. <svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
  121. <circle cx="100" cy="100" fill="yellow" r="78" stroke="black" stroke-width="3"/>
  122. <g class="eyes">
  123. <circle cx="61" cy="82" r="12"/>
  124. <circle cx="127" cy="82" r="12"/>
  125. </g>
  126. <path d="m136.81 116.53c.69 36.17-74.11 42-81.52-.73" style="fill:none; stroke: black; stroke-width: 5;"/>
  127. </svg>'''
  128. ui.svg(svg_content)
  129. with example(ui.markdown):
  130. ui.markdown('### Headline\nWith hyperlink to [GitHub](https://github.com/zauberzeug/nicegui).')
  131. with example(ui.html):
  132. ui.html('<p>demo paragraph in <strong>html</strong></p>')
  133. with example(ui.button):
  134. def button_increment():
  135. global button_count
  136. button_count += 1
  137. button_result.set_text(f'pressed: {button_count}')
  138. button_count = 0
  139. ui.button('Button', on_click=button_increment)
  140. button_result = ui.label('pressed: 0')
  141. with example(ui.checkbox):
  142. ui.checkbox('check me', on_change=lambda e: checkbox_state.set_text(e.value))
  143. with ui.row():
  144. ui.label('the checkbox is:')
  145. checkbox_state = ui.label('False')
  146. with example(ui.switch):
  147. ui.switch('switch me', on_change=lambda e: switch_state.set_text("ON" if e.value else'OFF'))
  148. with ui.row():
  149. ui.label('the switch is:')
  150. switch_state = ui.label('OFF')
  151. with example(ui.slider):
  152. slider = ui.slider(min=0, max=100, value=50).props('label')
  153. ui.label().bind_text_from(slider.value)
  154. with example(ui.input):
  155. ui.input(
  156. label='Text',
  157. placeholder='press ENTER to apply',
  158. on_change=lambda e: result.set_text('you typed: ' + e.value),
  159. ).classes('w-full')
  160. result = ui.label('')
  161. with example(ui.number):
  162. number_input = ui.number(label='Number', value=3.1415927, format='%.2f')
  163. with ui.row():
  164. ui.label('underlying value: ')
  165. ui.label().bind_text_from(number_input.value)
  166. with example(ui.radio):
  167. radio = ui.radio([1, 2, 3], value=1).props('inline')
  168. ui.radio({1: 'A', 2: 'B', 3: 'C'}, value=1).props('inline').bind_value(radio.value)
  169. with example(ui.toggle):
  170. toggle = ui.toggle([1, 2, 3], value=1)
  171. ui.toggle({1: 'A', 2: 'B', 3: 'C'}, value=1).bind_value(toggle.value)
  172. with example(ui.select):
  173. with ui.row():
  174. select = ui.select([1, 2, 3], value=1).props('inline')
  175. ui.select({1: 'One', 2: 'Two', 3: 'Three'}, value=1).props('inline').bind_value(select.value)
  176. with example(ui.plot):
  177. from matplotlib import pyplot as plt
  178. import numpy as np
  179. with ui.plot(figsize=(2.5, 1.8)):
  180. x = np.linspace(0.0, 5.0)
  181. y = np.cos(2 * np.pi * x) * np.exp(-x)
  182. plt.plot(x, y, '-')
  183. plt.xlabel('time (s)')
  184. plt.ylabel('Damped oscillation')
  185. with example(ui.line_plot):
  186. lines = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)).with_legend(['sin', 'cos'], loc='upper center', ncol=2)
  187. line_updates = ui.timer(0.1, lambda: lines.push([datetime.now()], [
  188. [np.sin(datetime.now().timestamp()) + 0.02 * np.random.randn()],
  189. [np.cos(datetime.now().timestamp()) + 0.02 * np.random.randn()],
  190. ]), active=False)
  191. ui.checkbox('active').bind_value(line_updates.active)
  192. with example(ui.joystick):
  193. ui.joystick(
  194. color='blue',
  195. size=50,
  196. on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
  197. on_end=lambda _: coordinates.set_text('0, 0'))
  198. coordinates = ui.label('0, 0')