def multi_fields(t): print('Dynamic labels.') refresh(st7735, True) # Clear any prior image nfields = [] dy = wri.height + 6 y = 2 col = 15 width = wri.stringlen('99.99') for txt in ('X:', 'Y:', 'Z:'): Label(wri, y, 0, txt) # Use wri default colors nfields.append(Label(wri, y, col, width, bdcolor=None)) # Specify a border, color TBD y += dy end = utime.ticks_add(utime.ticks_ms(), t * 1000) while utime.ticks_diff(end, utime.ticks_ms()) > 0: for field in nfields: value = int.from_bytes(uos.urandom(3), 'little') / 167772 overrange = None if value < 70 else YELLOW if value < 90 else RED field.value('{:5.2f}'.format(value), fgcolor=overrange, bdcolor=overrange) refresh(st7735) utime.sleep(1) Label(wri, 0, 64, ' OK ', True, fgcolor=RED) refresh(st7735) utime.sleep(1)
def __init__(self, writer, row, col, *, height=50, fgcolor=None, bgcolor=None, bdcolor=False, ticks=8, label=None, style=0, pip=None): super().__init__(writer, row, col, height, 2 * height, fgcolor, bgcolor, bdcolor) self.style = style self.pip = self.fgcolor if pip is None else pip if label is not None: self.label = Label(writer, row + height + 20, col, label) self.minLabel = Label(writer, row + height + 5, col, '0.0V') self.minLabel = Label(writer, row + height + 5, col + 2 * height - 25, '5.0V') radius = height self.radius = radius self.ticks = ticks self.xorigin = col + radius self.yorigin = row + radius self.vectors = set()
def vari_fields(): print('vari_fields') refresh(st7735, True) # Clear any prior image Label(wri, 0, 0, 'Text:') Label(wri, 20, 0, 'Border:') width = wri.stringlen('Yellow') lbl_text = Label(wri, 0, 40, width) lbl_bord = Label(wri, 20, 40, width) lbl_text.value('Red') lbl_bord.value('Red') lbl_var = Label(wri, 40, 2, '25.46', fgcolor=RED, bdcolor=RED) refresh(st7735) utime.sleep(2) lbl_text.value('Red') lbl_bord.value('Yellow') lbl_var.value(bdcolor=YELLOW) refresh(st7735) utime.sleep(2) lbl_text.value('Red') lbl_bord.value('None') lbl_var.value(bdcolor=False) refresh(st7735) utime.sleep(2) lbl_text.value('Yellow') lbl_bord.value('None') lbl_var.value(fgcolor=YELLOW) refresh(st7735) utime.sleep(2) lbl_text.value('Blue') lbl_bord.value('Green') lbl_var.value('18.99', fgcolor=BLUE, bdcolor=GREEN) refresh(st7735)
def cubesRendererWindow(self): """ Popup window for Cubes Renderer control and options""" popupBtnCubesRenderer = PopupButton(self.window, "Cubes") popupBtnCubesRenderer.setFontSize(16) popupCubesRenderer = popupBtnCubesRenderer.popup() popupCubesRenderer.setLayout(GroupLayout()) Label(popupCubesRenderer, "Cubes Renderer Options", "sans-bold") def cb(state): # self.pw.gl_canvas.switchCubesRenderer() self.pw.gl_canvas.cubes.switch() # self.pw.gl_canvas.setCubesSize(sliderCubeSize.value()) self.pw.gl_canvas.cubes.setSize(sliderCubeSize.value()) self.pw.gl_canvas.updateRenderers() chb = CheckBox(popupCubesRenderer, "Cubes", cb) def cb(state): # self.pw.gl_canvas.setCubesSize(sliderCubeSize.value()) self.pw.gl_canvas.cubes.setSize(sliderCubeSize.value()) self.pw.gl_canvas.updateRenderers() sliderCubeSize = Slider(popupCubesRenderer) sliderCubeSize.setValue(0.25) sliderCubeSize.setRange((0, 0.5)) sliderCubeSize.setFixedWidth(120) sliderCubeSize.setCallback(cb)
def neighborsRendererWindow(self): """ Popup window for Neighbors Renderer control and options""" popupBtnNeighborsRenderer = PopupButton(self.window, "Neighbors") popupBtnNeighborsRenderer.setFontSize(16) popupNeighborsRenderer = popupBtnNeighborsRenderer.popup() popupNeighborsRenderer.setLayout(GroupLayout()) Label(popupNeighborsRenderer, "Neighbors Renderer Options", "sans-bold") def switch_cb(state): self.pw.gl_canvas.neighbors.switch(intBox.value() - 1) self.pw.gl_canvas.updateRenderers() chb = CheckBox(popupNeighborsRenderer, "Neighbors", switch_cb) intBox = IntBox(popupNeighborsRenderer) intBox.setEditable(True) intBox.setFixedSize((150, 20)) intBox.setUnits("spin index") intBox.setValue(1) intBox.setDefaultValue("1") intBox.setFontSize(16) intBox.setFormat("[1-9][0-9]*") intBox.setSpinnable(True) intBox.setMinValue(1) intBox.setValueIncrement(1) def update_cb(state): self.pw.gl_canvas.neighbors.setIndex(intBox.value() - 1) self.pw.gl_canvas.updateRenderers() intBox.setCallback(update_cb)
def seq(): print('Time sequence test - sine and cosine.') refresh(st7735, True) # Clear any prior image # y axis at t==now, no border g = CartesianGraph(wri, 32, 2, height=80, xorigin=10, fgcolor=False, gridcolor=LIGHTGREEN, bdcolor=WHITE) # tsy = TSequence(g, YELLOW, 50) # tsr = TSequence(g, RED, 50) lbl = Label(wri, 10, 5, 'label') lbl.value("DAMPED OSCILLATOR") plt = TSequence(g, WHITE, 200) r = 0.9 p = 0 for t in range(300): g.clear() # tsy.add(0.9*math.sin(t/10)) # tsr.add(0.4*math.cos(t/10)) plt.add(r * math.cos(t / 10)) r = r - 0.003 refresh(st7735) # print(r) utime.sleep_ms(1) p = p + 1
def miscaleneousRenderersWindow(self): """ Popup window for other Renderers and general options""" popupBtnMiscRenderers = PopupButton(self.window, "Misc") popupBtnMiscRenderers.setFontSize(16) popupMiscRenderers = popupBtnMiscRenderers.popup() popupMiscRenderers.setLayout(GroupLayout()) Label(popupMiscRenderers, "Miscaleneous Renderers", "sans-bold") def cb(state): self.pw.gl_canvas.coordinate.switch() self.pw.gl_canvas.updateRenderers() chb = CheckBox(popupMiscRenderers, "Coordinates", cb) chb.setChecked(self.pw.gl_canvas.coordinate.show) def cb(state): print("Not implemented!") chb = CheckBox(popupMiscRenderers, "ArrowsSphere", cb) def cb(state): self.pw.gl_canvas.bounding_box.switch() self.pw.gl_canvas.updateRenderers() chb = CheckBox(popupMiscRenderers, "Bounding Box", cb) chb.setChecked(self.pw.gl_canvas.bounding_box.show)
def fields(use_spi=False, soft=True): ssd = setup(use_spi, soft) # Create a display instance Writer.set_textpos(ssd, 0, 0) # In case previous tests have altered it wri = Writer(ssd, fixed, verbose=False) wri.set_clip(False, False, False) textfield = Label(wri, 0, 2, wri.stringlen('longer')) numfield = Label(wri, 25, 2, wri.stringlen('99.99'), bdcolor=None) countfield = Label(wri, 0, 90, wri.stringlen('1')) n = 1 for s in ('short', 'longer', '1', ''): textfield.value(s) numfield.value('{:5.2f}'.format(int.from_bytes(uos.urandom(2),'little')/1000)) countfield.value('{:1d}'.format(n)) n += 1 refresh(ssd) utime.sleep(2) textfield.value('Done', True) refresh(ssd)
def __init__(self, parent): global nomix_set_status super(StatusWindow, self).__init__(parent, 'Status') # self.setLayout(GridLayout(orientation=Orientation.Vertical)) self.setSize((1410, 90)) self.setPosition((15, 750)) self.label = Label(self, '', 'sans-bold') self.label.setFixedSize((1400, 50)) self.label.setPosition((15, 50)) nomix_set_status = self.set_status
def aclock(): rtc = pyb.RTC() uv = lambda phi: cmath.rect(1, phi) # Return a unit vector of phase phi pi = cmath.pi days = ('Mon', 'Tue', 'Wed', 'Thur', 'Fri', 'Sat', 'Sun') months = ('Jan', 'Feb', 'March', 'April', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec') # Instantiate Writer Writer.set_textpos(ssd, 0, 0) # In case previous tests have altered it wri = Writer(ssd, font_small, verbose=False) wri.set_clip(True, True, False) wri_tim = Writer(ssd, font_large, verbose=False) wri_tim.set_clip(True, True, False) # Instantiate displayable objects dial = Dial(wri, 2, 2, height=215, ticks=12, bdcolor=None, pip=True) lbltim = Label(wri_tim, 50, 230, '00.00.00') lbldat = Label(wri, 100, 230, 100) hrs = Pointer(dial) mins = Pointer(dial) hstart = 0 + 0.7j # Pointer lengths and position at top mstart = 0 + 0.92j while True: t = rtc.datetime( ) # (year, month, day, weekday, hours, minutes, seconds, subseconds) hang = -t[4] * pi / 6 - t[5] * pi / 360 # Angles of hands in radians mang = -t[5] * pi / 30 if abs(hang - mang) < pi / 360: # Avoid visually confusing overlap of hands hang += pi / 30 # by making hr hand lag slightly hrs.value(hstart * uv(hang)) mins.value(mstart * uv(mang)) lbltim.value('{:02d}.{:02d}'.format(t[4], t[5])) lbldat.value('{} {} {} {}'.format(days[t[3] - 1], t[2], months[t[1] - 1], t[0])) refresh(ssd) # Power saving: only refresh every 30s for _ in range(30): upower.lpdelay(1000) ssd.update() # Toggle VCOM
def aclock(): uv = lambda phi: cmath.rect(1, phi) # Return a unit vector of phase phi pi = cmath.pi days = ('Mon', 'Tue', 'Wed', 'Thur', 'Fri', 'Sat', 'Sun') months = ('Jan', 'Feb', 'March', 'April', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec') # Instantiate Writer Writer.set_textpos(ssd, 0, 0) # In case previous tests have altered it wri = Writer(ssd, font_small, verbose=False) wri.set_clip(True, True, False) wri_tim = Writer(ssd, font_large, verbose=False) wri_tim.set_clip(True, True, False) # Instantiate displayable objects dial = Dial(wri, 2, 2, height=215, ticks=12, bdcolor=None, pip=True) lbltim = Label(wri_tim, 50, 230, '00.00.00') lbldat = Label(wri, 100, 230, 100) hrs = Pointer(dial) mins = Pointer(dial) secs = Pointer(dial) hstart = 0 + 0.7j # Pointer lengths and position at top mstart = 0 + 0.92j sstart = 0 + 0.92j while True: t = utime.localtime() hang = -t[4] * pi / 6 - t[ 5] * pi / 360 # Angles of hour and minute hands mang = -t[5] * pi / 30 sang = -t[6] * pi / 30 if abs(hang - mang) < pi / 360: # Avoid overlap of hr and min hands hang += pi / 30 # which is visually confusing. Add slight lag to hts hrs.value(hstart * uv(hang)) mins.value(mstart * uv(mang)) secs.value(sstart * uv(sang)) lbltim.value('{:02d}.{:02d}.{:02d}'.format(t[3], t[4], t[5])) lbldat.value('{} {} {} {}'.format(days[t[6]], t[2], months[t[1] - 1], t[0])) refresh(ssd) utime.sleep(1)
def vari_fields(): print('Variable label styles.') refresh(st7735, True) # Clear any prior image wri_large = CWriter(st7735, freesans20, GREEN, BLACK, verbose=False) wri_large.set_clip(True, True, False) Label(wri_large, 0, 0, 'Text') Label(wri_large, 20, 0, 'Border') width = wri_large.stringlen('Yellow') lbl_text = Label(wri_large, 0, 65, width) lbl_bord = Label(wri_large, 20, 65, width) lbl_text.value('Red') lbl_bord.value('Red') lbl_var = Label(wri_large, 50, 2, '25.46', fgcolor=RED, bdcolor=RED) refresh(st7735) utime.sleep(2) lbl_text.value('Red') lbl_bord.value('Yellow') lbl_var.value(bdcolor=YELLOW) refresh(st7735) utime.sleep(2) lbl_text.value('Red') lbl_bord.value('None') lbl_var.value(bdcolor=False) refresh(st7735) utime.sleep(2) lbl_text.value('Yellow') lbl_bord.value('None') lbl_var.value(fgcolor=YELLOW) refresh(st7735) utime.sleep(2) lbl_text.value('Blue') lbl_bord.value('Green') lbl_var.value('18.99', fgcolor=BLUE, bdcolor=GREEN) Label(wri, st7735.height - wri.height - 2, 0, 'Done', fgcolor=RED) refresh(st7735)
def __init__(self, parent_window): position = (5, 35) super(FooWindow, self).__init__(parent_window, position) # Buttons Label(self.window, "Push buttons", "sans-bold") b = Button(self.window, "Plain button") def cb(): print("pushed!") b.setCallback(cb) b = Button(self.window, "Styled", entypo.ICON_ROCKET) b.setBackgroundColor(Color(0, 0, 1.0, 0.1)) b.setCallback(cb)
def dotsRenderWindow(self): """ Popup window for Dots Renderer control and options""" popupBtnDotRenderer = PopupButton(self.window, "Dots") popupBtnDotRenderer.setFontSize(16) popupDotRenderer = popupBtnDotRenderer.popup() popupDotRenderer.setLayout(GroupLayout()) Label(popupDotRenderer, "Dot Renderer Options", "sans-bold") def cb(state): self.pw.gl_canvas.dots.switch(comboDotStyle.selectedIndex()) self.pw.gl_canvas.dots.setSize(sliderDotRadius.value()) self.pw.gl_canvas.updateRenderers() chb = CheckBox(popupDotRenderer, "Dot", cb) def cb(state): self.pw.gl_canvas.dots.setSize(sliderDotRadius.value()) self.pw.gl_canvas.updateRenderers() sliderDotRadius = Slider(popupDotRenderer) sliderDotRadius.setRange([0, 1000]) sliderDotRadius.setValue(500) sliderDotRadius.setFixedWidth(120) sliderDotRadius.setCallback(cb) Label(popupDotRenderer, "Dot style") comboDotStyle = ComboBox(popupDotRenderer, self.pw.gl_canvas.dots.getStyles()) def cb(state): self.pw.gl_canvas.dots.setStyle(comboDotStyle.selectedIndex()) comboDotStyle.setCallback(cb) comboDotStyle.setFontSize(16) comboDotStyle.setFixedSize((100, 20))
def multi_fields(use_spi=False, soft=True): ssd = setup(use_spi, soft) # Create a display instance Writer.set_textpos(ssd, 0, 0) # In case previous tests have altered it wri = Writer(ssd, small, verbose=False) wri.set_clip(False, False, False) nfields = [] dy = small.height() + 6 y = 2 col = 15 width = wri.stringlen('99.99') for txt in ('X:', 'Y:', 'Z:'): Label(wri, y, 0, txt) nfields.append(Label(wri, y, col, width, bdcolor=None)) # Draw border y += dy for _ in range(10): for field in nfields: value = int.from_bytes(uos.urandom(3),'little')/167772 field.value('{:5.2f}'.format(value)) refresh(ssd) utime.sleep(1) Label(wri, 0, 64, ' DONE ', True) refresh(ssd)
def arrowsRendererWindow(self): """ Popup window for Arrows Renderer control and options""" popupBtnArrowsRenderer = PopupButton(self.window, "Arrows") popupBtnArrowsRenderer.setFontSize(16) popupArrowsRenderer = popupBtnArrowsRenderer.popup() popupArrowsRenderer.setLayout(GroupLayout()) Label(popupArrowsRenderer, "Arrows Renderer Options", "sans-bold") def cb(state): self.pw.gl_canvas.arrows.switch() self.pw.gl_canvas.updateRenderers() chb = CheckBox(popupArrowsRenderer, "Arrows", cb) chb.setChecked(self.pw.gl_canvas.arrows.show)
def clock(x): print('Clock test.') refresh(st7735, True) # Clear any prior image lbl = Label(wri, 5, 85, 'Clock') dial = Dial(wri, 5, 5, height=75, ticks=12, bdcolor=None, label=50) # Border in fg color hrs = Pointer(dial) mins = Pointer(dial) hrs.value(0 + 0.7j, RED) mins.value(0 + 0.9j, YELLOW) dm = cmath.rect(1, -cmath.pi / 30) # Rotate by 1 minute (CW) dh = cmath.rect(1, -cmath.pi / 1800) # Rotate hours by 1 minute for n in range(x): refresh(st7735) utime.sleep_ms(200) mins.value(mins.value() * dm, YELLOW) hrs.value(hrs.value() * dh, RED) dial.text('ticks: {}'.format(n)) lbl.value('Done')
def lem(): print('Lemniscate of Bernoulli.') def populate(): t = -math.pi while t <= math.pi + 0.1: x = 0.5 * math.sqrt(2) * math.cos(t) / (math.sin(t)**2 + 1) y = math.sqrt(2) * math.cos(t) * math.sin(t) / (math.sin(t)**2 + 1) yield x, y t += 0.1 refresh(ssd, True) # Clear any prior image Label(wri, 82, 2, 'To infinity and beyond...') g = CartesianGraph(wri, 2, 2, height=75, fgcolor=WHITE, gridcolor=LIGHTGREEN) curve = Curve(g, YELLOW, populate()) refresh(ssd)
def aclock(): uv = lambda phi: cmath.rect(1, phi) # Return a unit vector of phase phi pi = cmath.pi days = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday') months = ('Jan', 'Feb', 'March', 'April', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec') CWriter.set_textpos(st7735, 0, 0) # In case previous tests have altered it wri = CWriter(st7735, arial10, GREEN, BLACK, verbose=False) wri.set_clip(True, True, False) # Instantiate displayable objects refresh(st7735, True) # Clear any prior image dial = Dial(wri, 2, 2, height=75, ticks=12, bdcolor=None, label=120, pip=False) # Border in fg color lbltim = Label(wri, 5, 85, 35) hrs = Pointer(dial) mins = Pointer(dial) secs = Pointer(dial) hstart = 0 + 0.7j # Pointer lengths and position at top mstart = 0 + 0.92j sstart = 0 + 0.92j while True: t = cetTime() hrs.value(hstart * uv(-t[3] * pi / 6 - t[4] * pi / 360), YELLOW) mins.value(mstart * uv(-t[4] * pi / 30), YELLOW) secs.value(sstart * uv(-t[5] * pi / 30), RED) lbltim.value('{:02d}.{:02d}.{:02d}'.format(t[3], t[4], t[5])) dial.text('{} {} {} {}'.format(days[t[6]], t[2], months[t[1] - 1], t[0])) refresh(st7735) utime.sleep(1)
def tab_cb(index): if index == (tabWidget.tabCount()-1): global counter # When the "+" tab has been clicked, simply add a new tab. tabName = "Dynamic {0}".format(counter) layerDyn = tabWidget.createTab(index, tabName) layerDyn.setLayout(GroupLayout()) Label(layerDyn, "Function graph widget", "sans-bold") graphDyn = Graph(layerDyn, "Dynamic function") graphDyn.setHeader("E = 2.35e-3") graphDyn.setFooter("Iteration {0}".format(index*counter)) valuesDyn = [0.5 * abs((0.5 * math.sin(i / 10.0 + counter)) + (0.5 * math.cos(i / 23.0 + 1 + counter))) for i in range(100)] graphDyn.setValues(valuesDyn) counter += 1 # We must invoke perform layout from the screen instance to keep everything in order. # This is essential when creating tabs dynamically. self.performLayout() # Ensure that the newly added header is visible on screen tabWidget.ensureTabVisible(index)
def tab_cb(index): if index == plus_id: global counter # When the "+" tab has been clicked, simply add a new tab. tab_name = "Dynamic {0}".format(counter) layer_dyn = Widget(tab_widget) layer_dyn.set_layout(GroupLayout()) new_id = tab_widget.insert_tab(tab_widget.tab_count() - 1, tab_name, layer_dyn) Label(layer_dyn, "Function graph widget", "sans-bold") graph_dyn = Graph(layer_dyn, "Dynamic function") graph_dyn.set_header("E = 2.35e-3") graph_dyn.set_footer("Iteration {0}".format(index*counter)) values_dyn = [0.5 * abs((0.5 * math.sin(i / 10.0 + counter)) + (0.5 * math.cos(i / 23.0 + 1 + counter))) for i in range(100)] graph_dyn.set_values(values_dyn) counter += 1 # We must invoke the layout manager after adding tabs dynamically self.perform_layout() tab_widget.set_selected_id(new_id)
def cart(): print('Cartesian data test.') def populate_1(): x = 0 while x < 2.01: yield x, exp(-x) * cos(10 * x) # x, y x += 0.1 refresh(st7735, True) # Clear any prior image g = CartesianGraph(wri, 20, 2, fgcolor=Display.WHITE, gridcolor=Display.LIGHT_GREEN) # Asymmetric y axis curve1 = Curve(g, Display.RED, populate_1(), origin=(1, 0)) title = Label(wri, 2, 10, 'Damped Oscillator', fgcolor=Display.WHITE, bdcolor=Display.WHITE) refresh(st7735)
def __init__(self, voxel_grids, normals=None, mesh_file=None): super(VoxelGridViewer, self).__init__() self.disp_idx = 0 self.voxel_grids = voxel_grids self.normals = normals if mesh_file is not None: self.mesh = TriangleMesh(mesh_file) else: self.mesh = None window = Window(self, "VoxelGridViewer") window.setPosition((15, 15)) window.setLayout(GroupLayout()) tools = Widget(window) tools.setLayout( BoxLayout(Orientation.Horizontal, Alignment.Middle, 0, 5)) self.label = Label(window, self.voxel_grids[self.disp_idx][0]) self.selected_voxel = None self.performLayout()
def voltmeter(): print('Voltmeter with ADC connected to pin 34') refresh(st7735, True) # Clear any prior imag title = Label(wri, 2, 40, 'Voltmeter', fgcolor=Display.WHITE, bdcolor=Display.WHITE) uv = lambda phi: cmath.rect(1, phi) # Return a unit vector of phase phi scale = Scale(wri, 30, 5, height=60, ticks=5, bdcolor=None, label=50) # Border in fg color voltage = Pointer(scale) while True: v = adc.read() * 3.3 / 4096 # we have Vdd = 3.3 V and a 12 bit ADC voltage.value( (0 + 0.9j) * cmath.rect(1, cmath.pi / 2 - (v / 5) * cmath.pi), Display.RED) scale.text('voltage: {0:.1f} V'.format(v)) refresh(st7735) utime.sleep_ms(100) # a measurement everv 100 ms
def __init__(self, parent, name, sound, color): super(SoundLayer, self).__init__(parent) print('[+] SoundLayer::__init__') self.setLayout(GridLayout(resolution=4)) self.sound = sound self.cp = Button(self, '') self.color = color self.cp.setBackgroundColor(color) label = Label(self, name + ':', 'sans-bold') label.setFixedSize((70, 20)) self.cp.setFixedSize((20, 40)) self.solomute = Widget(self) self.solomute.setLayout(GridLayout(resolution=3)) self._parent = parent self._focused = False self.issolo = False self.ismute = False self.selected_color = Color(0x3e, 0x3e, 0x3f, 0xff) slider = Slider(self.solomute) slider.setFixedSize((180, 20)) def mute_cb(): print('mute') mute = Button(self.solomute, 'M') mute.setCallback(mute_cb) def solo_cb(): print('solo') solo = Button(self.solomute, 'S') solo.setCallback(solo_cb) spacer = Widget(self) spacer.setWidth(20) self.setFixedSize((400, 40))
def __init__(self): super(TestApp, self).__init__((1024, 768), "NanoGUI Test") self.shader = None window = Window(self, "Button demo") window.set_position((15, 15)) window.set_layout(GroupLayout()) Label(window, "Push buttons", "sans-bold") b = Button(window, "Plain button") def cb(): print("pushed!") b.set_callback(cb) b = Button(window, "Styled", icons.FA_ROCKET) b.set_background_color(Color(0, 0, 1.0, 0.1)) b.set_callback(cb) Label(window, "Toggle buttons", "sans-bold") b = Button(window, "Toggle me") b.set_flags(Button.Flags.ToggleButton) def change_cb(state): print("Toggle button state: %s" % str(state)) b.set_change_callback(change_cb) Label(window, "Radio buttons", "sans-bold") b = Button(window, "Radio button 1") b.set_flags(Button.Flags.RadioButton) b = Button(window, "Radio button 2") b.set_flags(Button.Flags.RadioButton) Label(window, "A tool palette", "sans-bold") tools = Widget(window) tools.set_layout( BoxLayout(Orientation.Horizontal, Alignment.Middle, 0, 6)) ToolButton(tools, icons.FA_CLOUD) ToolButton(tools, icons.FA_FAST_FORWARD) ToolButton(tools, icons.FA_COMPASS) ToolButton(tools, icons.FA_UTENSILS) Label(window, "Popup buttons", "sans-bold") popup_btn = PopupButton(window, "Popup", icons.FA_FLASK) popup = popup_btn.popup() popup.set_layout(GroupLayout()) Label(popup, "Arbitrary widgets can be placed here") CheckBox(popup, "A check box") # popup right popup_btn = PopupButton(popup, "Recursive popup", icons.FA_CHART_PIE) popup_right = popup_btn.popup() popup_right.set_layout(GroupLayout()) CheckBox(popup_right, "Another check box") # popup left popup_btn = PopupButton(popup, "Recursive popup", icons.FA_DNA) popup_btn.set_side(Popup.Side.Left) popup_left = popup_btn.popup() popup_left.set_layout(GroupLayout()) CheckBox(popup_left, "Another check box") window = Window(self, "Basic widgets") window.set_position((200, 15)) window.set_layout(GroupLayout()) Label(window, "Message dialog", "sans-bold") tools = Widget(window) tools.set_layout( BoxLayout(Orientation.Horizontal, Alignment.Middle, 0, 6)) def cb2(result): print("Dialog result: %i" % result) b = Button(tools, "Info") def cb(): dlg = MessageDialog(self, MessageDialog.Type.Information, "Title", "This is an information message") dlg.set_callback(cb2) b.set_callback(cb) b = Button(tools, "Warn") def cb(): dlg = MessageDialog(self, MessageDialog.Type.Warning, "Title", "This is a warning message") dlg.set_callback(cb2) b.set_callback(cb) b = Button(tools, "Ask") def cb(): dlg = MessageDialog(self, MessageDialog.Type.Warning, "Title", "This is a question message", "Yes", "No", True) dlg.set_callback(cb2) b.set_callback(cb) import os import sys os.chdir(sys.path[0]) try: icons_data = nanogui.load_image_directory(self.nvg_context(), "icons") except: try: icons_data = nanogui.load_image_directory( self.nvg_context(), "../icons") except: icons_data = nanogui.load_image_directory( self.nvg_context(), "../resources/icons") Label(window, "Image panel & scroll panel", "sans-bold") image_panel_btn = PopupButton(window, "Image Panel") image_panel_btn.set_icon(icons.FA_IMAGES) popup = image_panel_btn.popup() vscroll = VScrollPanel(popup) img_panel = ImagePanel(vscroll) img_panel.set_images(icons_data) popup.set_fixed_size((245, 150)) img_window = Window(self, "Selected image") img_window.set_position((710, 15)) img_window.set_layout(GroupLayout()) img_view = ImageView(img_window) img_view.set_image( Texture(icons_data[0][1] + ".png", Texture.InterpolationMode.Trilinear, Texture.InterpolationMode.Nearest)) img_view.center() def cb(i): print("Selected item %i" % i) img_view.set_image( Texture(icons_data[i][1] + ".png", Texture.InterpolationMode.Trilinear, Texture.InterpolationMode.Nearest)) img_panel.set_callback(cb) Label(window, "File dialog", "sans-bold") tools = Widget(window) tools.set_layout( BoxLayout(Orientation.Horizontal, Alignment.Middle, 0, 6)) b = Button(tools, "Open") valid = [("png", "Portable Network Graphics"), ("txt", "Text file")] def cb(): result = nanogui.file_dialog(valid, False) print("File dialog result = %s" % result) b.set_callback(cb) b = Button(tools, "Save") def cb(): result = nanogui.file_dialog(valid, True) print("File dialog result = %s" % result) b.set_callback(cb) Label(window, "Combo box", "sans-bold") ComboBox(window, ["Combo box item 1", "Combo box item 2", "Combo box item 3"]) Label(window, "Check box", "sans-bold") def cb(state): print("Check box 1 state: %s" % state) chb = CheckBox(window, "Flag 1", cb) chb.set_checked(True) def cb(state): print("Check box 2 state: %s" % state) CheckBox(window, "Flag 2", cb) Label(window, "Progress bar", "sans-bold") self.progress = ProgressBar(window) Label(window, "Slider and text box", "sans-bold") panel = Widget(window) panel.set_layout( BoxLayout(Orientation.Horizontal, Alignment.Middle, 0, 20)) slider = Slider(panel) slider.set_value(0.5) slider.set_fixed_width(80) text_box = TextBox(panel) text_box.set_fixed_size((60, 25)) text_box.set_value("50") text_box.set_units("%") text_box.set_font_size(20) text_box.set_alignment(TextBox.Alignment.Right) def cb(value): text_box.set_value("%i" % int(value * 100)) slider.set_callback(cb) def cb(value): print("Final slider value: %i" % int(value * 100)) slider.set_final_callback(cb) window = Window(self, "Misc. widgets") window.set_position((425, 15)) window.set_layout(GroupLayout()) tab_widget = TabWidget(window) layer = Widget(tab_widget) layer.set_layout(GroupLayout()) tab_widget.append_tab("Color Wheel", layer) Label(layer, "Color wheel widget", "sans-bold") ColorWheel(layer) layer = Widget(tab_widget) layer.set_layout(GroupLayout()) tab_widget.append_tab("Function Graph", layer) Label(layer, "Function graph widget", "sans-bold") graph = Graph(layer, "Some function") graph.set_header("E = 2.35e-3") graph.set_footer("Iteration 89") values = [ 0.5 * (0.5 * math.sin(i / 10.0) + 0.5 * math.cos(i / 23.0) + 1) for i in range(100) ] graph.set_values(values) # Dummy tab used to represent the last tab button. plus_id = tab_widget.append_tab("+", Widget(tab_widget)) def tab_cb(index): if index == plus_id: global counter # When the "+" tab has been clicked, simply add a new tab. tab_name = "Dynamic {0}".format(counter) layer_dyn = Widget(tab_widget) layer_dyn.set_layout(GroupLayout()) new_id = tab_widget.insert_tab(tab_widget.tab_count() - 1, tab_name, layer_dyn) Label(layer_dyn, "Function graph widget", "sans-bold") graph_dyn = Graph(layer_dyn, "Dynamic function") graph_dyn.set_header("E = 2.35e-3") graph_dyn.set_footer("Iteration {0}".format(index * counter)) values_dyn = [ 0.5 * abs((0.5 * math.sin(i / 10.0 + counter)) + (0.5 * math.cos(i / 23.0 + 1 + counter))) for i in range(100) ] graph_dyn.set_values(values_dyn) counter += 1 # We must invoke the layout manager after adding tabs dynamically self.perform_layout() tab_widget.set_selected_id(new_id) tab_widget.set_callback(tab_cb) window = Window(self, "Grid of small widgets") window.set_position((425, 300)) layout = GridLayout(Orientation.Horizontal, 2, Alignment.Middle, 15, 5) layout.set_col_alignment([Alignment.Maximum, Alignment.Fill]) layout.set_spacing(0, 10) window.set_layout(layout) Label(window, "Floating point :", "sans-bold") float_box = TextBox(window) float_box.set_editable(True) float_box.set_fixed_size((100, 20)) float_box.set_value("50") float_box.set_units("GiB") float_box.set_default_value("0.0") float_box.set_font_size(16) float_box.set_format("[-]?[0-9]*\\.?[0-9]+") Label(window, "Positive integer :", "sans-bold") int_box = IntBox(window) int_box.set_editable(True) int_box.set_fixed_size((100, 20)) int_box.set_value(50) int_box.set_units("Mhz") int_box.set_default_value("0") int_box.set_font_size(16) int_box.set_format("[1-9][0-9]*") int_box.set_spinnable(True) int_box.set_min_value(1) int_box.set_value_increment(2) Label(window, "Checkbox :", "sans-bold") cb = CheckBox(window, "Check me") cb.set_font_size(16) cb.set_checked(True) Label(window, "Combo box :", "sans-bold") cobo = ComboBox(window, ["Item 1", "Item 2", "Item 3"]) cobo.set_font_size(16) cobo.set_fixed_size((100, 20)) Label(window, "Color picker :", "sans-bold") cp = ColorPicker(window, Color(255, 120, 0, 255)) cp.set_fixed_size((100, 20)) def cp_final_cb(color): print("ColorPicker Final Callback: [{0}, {1}, {2}, {3}]".format( color.r, color.g, color.b, color.w)) cp.set_final_callback(cp_final_cb) # setup a fast callback for the color picker widget on a new window # for demonstrative purposes window = Window(self, "Color Picker Fast Callback") window.set_position((425, 300)) layout = GridLayout(Orientation.Horizontal, 2, Alignment.Middle, 15, 5) layout.set_col_alignment([Alignment.Maximum, Alignment.Fill]) layout.set_spacing(0, 10) window.set_layout(layout) window.set_position((425, 500)) Label(window, "Combined: ") b = Button(window, "ColorWheel", icons.FA_INFINITY) Label(window, "Red: ") red_int_box = IntBox(window) red_int_box.set_editable(False) Label(window, "Green: ") green_int_box = IntBox(window) green_int_box.set_editable(False) Label(window, "Blue: ") blue_int_box = IntBox(window) blue_int_box.set_editable(False) Label(window, "Alpha: ") alpha_int_box = IntBox(window) def cp_fast_cb(color): b.set_background_color(color) b.set_text_color(color.contrasting_color()) red = int(color.r * 255.0) red_int_box.set_value(red) green = int(color.g * 255.0) green_int_box.set_value(green) blue = int(color.b * 255.0) blue_int_box.set_value(blue) alpha = int(color.w * 255.0) alpha_int_box.set_value(alpha) cp.set_callback(cp_fast_cb) self.perform_layout() self.render_pass = RenderPass([self]) self.render_pass.set_clear_color(0, Color(0.3, 0.3, 0.32, 1.0)) if nanogui.api == 'opengl': vertex_shader = """ #version 330 uniform mat4 mvp; in vec3 position; void main() { gl_Position = mvp * vec4(position, 1.0); }""" fragment_shader = """ #version 330 out vec4 color; uniform float intensity; void main() { color = vec4(vec3(intensity), 1.0); }""" elif nanogui.api == 'gles2' or nanogui.api == 'gles3': vertex_shader = """ precision highp float; uniform mat4 mvp; attribute vec3 position; void main() { gl_Position = mvp * vec4(position, 1.0); }""" fragment_shader = """ precision highp float; uniform float intensity; void main() { gl_FragColor = vec4(vec3(intensity), 1.0); }""" elif nanogui.api == 'metal': vertex_shader = """ using namespace metal; struct VertexOut { float4 position [[position]]; }; vertex VertexOut vertex_main(const device packed_float3 *position, constant float4x4 &mvp, uint id [[vertex_id]]) { VertexOut vert; vert.position = mvp * float4(position[id], 1.f); return vert; }""" fragment_shader = """ using namespace metal; fragment float4 fragment_main(const constant float &intensity) { return float4(intensity); }""" self.shader = Shader( self.render_pass, # An identifying name "A simple shader", vertex_shader, fragment_shader) self.shader.set_buffer("indices", np.array([0, 1, 2, 2, 3, 0], dtype=np.uint32)) self.shader.set_buffer( "position", np.array([[-1, -1, 0], [1, -1, 0], [1, 1, 0], [-1, 1, 0]], dtype=np.float32)) self.shader.set_buffer("intensity", np.array(0.5, dtype=np.float32))
def add_slider(variable_scope, widget, variable_name, min_val, max_val, dtype, callback=None, logspace=False): Label(widget, variable_name) widget = Widget(widget) widget.setLayout(BoxLayout(Orientation.Horizontal, Alignment.Middle, 0, 20)) slider = Slider(widget) diff = max_val - min_val logdiff = np.log(max_val) - np.log(min_val) if logspace: slider.setValue( (np.log(variable_scope.__dict__[variable_name]) - np.log(min_val)) / logdiff) else: slider.setValue( (variable_scope.__dict__[variable_name] - min_val) / diff) slider.setFixedWidth(120) textBox = TextBox(widget) textBox.setFixedSize((60, 25)) textBox.setEditable(True) if dtype == int: textBox.setValue('{:d}'.format(variable_scope.__dict__[variable_name])) else: textBox.setValue('{:.3f}'.format( variable_scope.__dict__[variable_name])) textBox.setFontSize(20) textBox.setAlignment(TextBox.Alignment.Right) # TODO: Somehow the textbox callback is broken? # def cb_text(value): # print('type(value): {}'.format(type(value))) # print('value: {}'.format(value)) # textBox.setCallback(cb_text) def cb(value): if logspace: if dtype == int: textBox.setValue('{:d}'.format( int(np.exp(logdiff * value + np.log(min_val))))) else: textBox.setValue('{:.3f}'.format( np.exp(logdiff * value + np.log(min_val)))) else: if dtype == int: textBox.setValue('{:d}'.format(int(diff * value + min_val))) else: textBox.setValue('{:.3f}'.format(diff * value + min_val)) slider.setCallback(cb) def cb(value): if logspace: variable_scope.__dict__[variable_name] = dtype( np.exp(logdiff * value + np.log(min_val))) else: variable_scope.__dict__[variable_name] = dtype(diff * value + min_val) if callback: callback() slider.setFinalCallback(cb)
def __init__(self, variable_scope, widget, variable_name, min_val, max_val, dtype, callback=None, logspace=False, slider_width=120, warp_fun=None, inv_warp_fun=None): super().__init__(widget) if logspace: warp_fun = np.log inv_warp_fun = np.exp if warp_fun is None: def warp_fun(x): return x def inv_warp_fun(x): return x self.warp_fun = warp_fun self.inv_warp_fun = inv_warp_fun self.variable_scope = variable_scope self.variable_name = variable_name self.logspace = logspace self.min_val = min_val self.max_val = max_val self.dtype = dtype Label(widget, variable_name) widget = Widget(widget) widget.setLayout( BoxLayout(Orientation.Horizontal, Alignment.Middle, 0, 20)) self.slider = Slider(widget) diff = warp_fun(max_val) - warp_fun(min_val) self.slider.setValue( (warp_fun(variable_scope.__dict__[variable_name]) - warp_fun(min_val)) / diff) self.slider.setFixedWidth(slider_width) self.textBox = TextBox(widget) self.textBox.setFixedSize((60, 25)) self.textBox.setEditable(True) if dtype == int: self.textBox.setValue('{:d}'.format( variable_scope.__dict__[variable_name])) else: self.textBox.setValue('{:.3f}'.format( variable_scope.__dict__[variable_name])) self.textBox.setFontSize(20) self.textBox.setAlignment(TextBox.Alignment.Right) def cb(value): try: value = dtype(value) except ValueError: return False if value < min_val or value > max_val: return False self.slider.setValue( float((warp_fun(value) - warp_fun(min_val)) / diff)) variable_scope.__dict__[variable_name] = value if callback: callback() return True self.textBox.setCallback(cb) def cb(value): format_str = {int: r'{:d}', float: r'{:.3f}'} self.textBox.setValue(format_str[dtype].format( dtype(inv_warp_fun(diff * value + warp_fun(min_val))))) self.slider.setCallback(cb) def cb(value): variable_scope.__dict__[variable_name] = dtype( inv_warp_fun(diff * value + warp_fun(min_val))) if callback: callback() self.slider.setFinalCallback(cb)
def __init__(self): super(TestApp, self).__init__((1024, 768), "NanoGUI Test") window = Window(self, "Button demo") window.setPosition((15, 15)) window.setLayout(GroupLayout()) Label(window, "Push buttons", "sans-bold") b = Button(window, "Plain button") def cb(): print("pushed!") b.setCallback(cb) b = Button(window, "Styled", entypo.ICON_ROCKET) b.setBackgroundColor(Color(0, 0, 1.0, 0.1)) b.setCallback(cb) Label(window, "Toggle buttons", "sans-bold") b = Button(window, "Toggle me") b.setFlags(Button.Flags.ToggleButton) def change_cb(state): print("Toggle button state: %s" % str(state)) b.setChangeCallback(change_cb) Label(window, "Radio buttons", "sans-bold") b = Button(window, "Radio button 1") b.setFlags(Button.Flags.RadioButton) b = Button(window, "Radio button 2") b.setFlags(Button.Flags.RadioButton) Label(window, "A tool palette", "sans-bold") tools = Widget(window) tools.setLayout( BoxLayout(Orientation.Horizontal, Alignment.Middle, 0, 6)) ToolButton(tools, entypo.ICON_CLOUD) ToolButton(tools, entypo.ICON_CONTROLLER_FAST_FORWARD) ToolButton(tools, entypo.ICON_COMPASS) ToolButton(tools, entypo.ICON_INSTALL) Label(window, "Popup buttons", "sans-bold") popupBtn = PopupButton(window, "Popup", entypo.ICON_EXPORT) popup = popupBtn.popup() popup.setLayout(GroupLayout()) Label(popup, "Arbitrary widgets can be placed here") CheckBox(popup, "A check box") # popup right popupBtn = PopupButton(popup, "Recursive popup", entypo.ICON_FLASH) popupRight = popupBtn.popup() popupRight.setLayout(GroupLayout()) CheckBox(popupRight, "Another check box") # popup left popupBtn = PopupButton(popup, "Recursive popup", entypo.ICON_FLASH) popupBtn.setSide(Popup.Side.Left) popupLeft = popupBtn.popup() popupLeft.setLayout(GroupLayout()) CheckBox(popupLeft, "Another check box") window = Window(self, "Basic widgets") window.setPosition((200, 15)) window.setLayout(GroupLayout()) Label(window, "Message dialog", "sans-bold") tools = Widget(window) tools.setLayout( BoxLayout(Orientation.Horizontal, Alignment.Middle, 0, 6)) def cb2(result): print("Dialog result: %i" % result) b = Button(tools, "Info") def cb(): dlg = MessageDialog(self, MessageDialog.Type.Information, "Title", "This is an information message") dlg.setCallback(cb2) b.setCallback(cb) b = Button(tools, "Warn") def cb(): dlg = MessageDialog(self, MessageDialog.Type.Warning, "Title", "This is a warning message") dlg.setCallback(cb2) b.setCallback(cb) b = Button(tools, "Ask") def cb(): dlg = MessageDialog(self, MessageDialog.Type.Warning, "Title", "This is a question message", "Yes", "No", True) dlg.setCallback(cb2) b.setCallback(cb) import os import sys os.chdir(sys.path[0]) try: icons = nanogui.loadImageDirectory(self.nvgContext(), "icons") except: try: icons = nanogui.loadImageDirectory(self.nvgContext(), "../icons") except: icons = nanogui.loadImageDirectory(self.nvgContext(), "../resources/icons") Label(window, "Image panel & scroll panel", "sans-bold") imagePanelBtn = PopupButton(window, "Image Panel") imagePanelBtn.setIcon(entypo.ICON_FOLDER) popup = imagePanelBtn.popup() vscroll = VScrollPanel(popup) imgPanel = ImagePanel(vscroll) imgPanel.setImages(icons) popup.setFixedSize((245, 150)) img_window = Window(self, "Selected image") img_window.setPosition((710, 15)) img_window.setLayout(GroupLayout()) imgView = ImageView(img_window, icons[0][0]) def cb(i): print("Selected item %i" % i) imgView.bindImage(icons[i][0]) imgPanel.setCallback(cb) imgView.setGridThreshold(3) Label(window, "File dialog", "sans-bold") tools = Widget(window) tools.setLayout( BoxLayout(Orientation.Horizontal, Alignment.Middle, 0, 6)) b = Button(tools, "Open") valid = [("png", "Portable Network Graphics"), ("txt", "Text file")] def cb(): result = nanogui.file_dialog(valid, False) print("File dialog result = %s" % result) b.setCallback(cb) b = Button(tools, "Save") def cb(): result = nanogui.file_dialog(valid, True) print("File dialog result = %s" % result) b.setCallback(cb) Label(window, "Combo box", "sans-bold") ComboBox(window, ["Combo box item 1", "Combo box item 2", "Combo box item 3"]) Label(window, "Check box", "sans-bold") def cb(state): print("Check box 1 state: %s" % state) chb = CheckBox(window, "Flag 1", cb) chb.setChecked(True) def cb(state): print("Check box 2 state: %s" % state) CheckBox(window, "Flag 2", cb) Label(window, "Progress bar", "sans-bold") self.progress = ProgressBar(window) Label(window, "Slider and text box", "sans-bold") panel = Widget(window) panel.setLayout( BoxLayout(Orientation.Horizontal, Alignment.Middle, 0, 20)) slider = Slider(panel) slider.setValue(0.5) slider.setFixedWidth(80) textBox = TextBox(panel) textBox.setFixedSize((60, 25)) textBox.setValue("50") textBox.setUnits("%") textBox.setFontSize(20) textBox.setAlignment(TextBox.Alignment.Right) def cb(value): textBox.setValue("%i" % int(value * 100)) slider.setCallback(cb) def cb(value): print("Final slider value: %i" % int(value * 100)) slider.setFinalCallback(cb) window = Window(self, "Misc. widgets") window.setPosition((425, 15)) window.setLayout(GroupLayout()) tabWidget = TabWidget(window) layer = tabWidget.createTab("Color Wheel") layer.setLayout(GroupLayout()) Label(layer, "Color wheel widget", "sans-bold") ColorWheel(layer) layer = tabWidget.createTab("Function Graph") layer.setLayout(GroupLayout()) Label(layer, "Function graph widget", "sans-bold") graph = Graph(layer, "Some function") graph.setHeader("E = 2.35e-3") graph.setFooter("Iteration 89") values = [ 0.5 * (0.5 * math.sin(i / 10.0) + 0.5 * math.cos(i / 23.0) + 1) for i in range(100) ] graph.setValues(values) tabWidget.setActiveTab(0) # Dummy tab used to represent the last tab button. tabWidget.createTab("+") def tab_cb(index): if index == (tabWidget.tabCount() - 1): global counter # When the "+" tab has been clicked, simply add a new tab. tabName = "Dynamic {0}".format(counter) layerDyn = tabWidget.createTab(index, tabName) layerDyn.setLayout(GroupLayout()) Label(layerDyn, "Function graph widget", "sans-bold") graphDyn = Graph(layerDyn, "Dynamic function") graphDyn.setHeader("E = 2.35e-3") graphDyn.setFooter("Iteration {0}".format(index * counter)) valuesDyn = [ 0.5 * abs((0.5 * math.sin(i / 10.0 + counter)) + (0.5 * math.cos(i / 23.0 + 1 + counter))) for i in range(100) ] graphDyn.setValues(valuesDyn) counter += 1 # We must invoke perform layout from the screen instance to keep everything in order. # This is essential when creating tabs dynamically. self.performLayout() # Ensure that the newly added header is visible on screen tabWidget.ensureTabVisible(index) tabWidget.setCallback(tab_cb) tabWidget.setActiveTab(0) window = Window(self, "Grid of small widgets") window.setPosition((425, 300)) layout = GridLayout(Orientation.Horizontal, 2, Alignment.Middle, 15, 5) layout.setColAlignment([Alignment.Maximum, Alignment.Fill]) layout.setSpacing(0, 10) window.setLayout(layout) Label(window, "Floating point :", "sans-bold") floatBox = TextBox(window) floatBox.setEditable(True) floatBox.setFixedSize((100, 20)) floatBox.setValue("50") floatBox.setUnits("GiB") floatBox.setDefaultValue("0.0") floatBox.setFontSize(16) floatBox.setFormat("[-]?[0-9]*\\.?[0-9]+") Label(window, "Positive integer :", "sans-bold") intBox = IntBox(window) intBox.setEditable(True) intBox.setFixedSize((100, 20)) intBox.setValue(50) intBox.setUnits("Mhz") intBox.setDefaultValue("0") intBox.setFontSize(16) intBox.setFormat("[1-9][0-9]*") intBox.setSpinnable(True) intBox.setMinValue(1) intBox.setValueIncrement(2) Label(window, "Checkbox :", "sans-bold") cb = CheckBox(window, "Check me") cb.setFontSize(16) cb.setChecked(True) Label(window, "Combo box :", "sans-bold") cobo = ComboBox(window, ["Item 1", "Item 2", "Item 3"]) cobo.setFontSize(16) cobo.setFixedSize((100, 20)) Label(window, "Color picker :", "sans-bold") cp = ColorPicker(window, Color(255, 120, 0, 255)) cp.setFixedSize((100, 20)) def cp_final_cb(color): print("ColorPicker Final Callback: [{0}, {1}, {2}, {3}]".format( color.r, color.g, color.b, color.w)) cp.setFinalCallback(cp_final_cb) # setup a fast callback for the color picker widget on a new window # for demonstrative purposes window = Window(self, "Color Picker Fast Callback") window.setPosition((425, 300)) layout = GridLayout(Orientation.Horizontal, 2, Alignment.Middle, 15, 5) layout.setColAlignment([Alignment.Maximum, Alignment.Fill]) layout.setSpacing(0, 10) window.setLayout(layout) window.setPosition((425, 500)) Label(window, "Combined: ") b = Button(window, "ColorWheel", entypo.ICON_500PX) Label(window, "Red: ") redIntBox = IntBox(window) redIntBox.setEditable(False) Label(window, "Green: ") greenIntBox = IntBox(window) greenIntBox.setEditable(False) Label(window, "Blue: ") blueIntBox = IntBox(window) blueIntBox.setEditable(False) Label(window, "Alpha: ") alphaIntBox = IntBox(window) def cp_fast_cb(color): b.setBackgroundColor(color) b.setTextColor(color.contrastingColor()) red = int(color.r * 255.0) redIntBox.setValue(red) green = int(color.g * 255.0) greenIntBox.setValue(green) blue = int(color.b * 255.0) blueIntBox.setValue(blue) alpha = int(color.w * 255.0) alphaIntBox.setValue(alpha) cp.setCallback(cp_fast_cb) self.performLayout() try: import numpy as np self.shader = GLShader() self.shader.init( # An identifying name "a_simple_shader", # Vertex shader """#version 330 uniform mat4 modelViewProj; in vec3 position; void main() { gl_Position = modelViewProj * vec4(position, 1.0); }""", """#version 330 out vec4 color; uniform float intensity; void main() { color = vec4(vec3(intensity), 1.0); }""") # Draw 2 triangles indices = np.array([[0, 2], [1, 3], [2, 0]], dtype=np.int32) positions = np.array( [[-1, 1, 1, -1], [-1, -1, 1, 1], [0, 0, 0, 0]], dtype=np.float32) self.shader.bind() self.shader.uploadIndices(indices) self.shader.uploadAttrib("position", positions) self.shader.setUniform("intensity", 0.5) except ImportError: self.shader = None pass
def meter(): print('meter') refresh(st7735, True) # Clear any prior image title = Label(wri, 2, 10, 'SHT30 measurements', fgcolor=Display.WHITE, bdcolor=Display.WHITE) tempLabel = Label(wri, 110, 2, '32.4 deg C', fgcolor=Display.WHITE, bdcolor=Display.BLACK) humiLabel = Label(wri, 110, 80, '42 %', fgcolor=Display.WHITE, bdcolor=Display.BLACK) mtemp = Meter(wri, 25, 2, height=70, divisions=5, ptcolor=Display.YELLOW, label='temperature', style=Meter.BAR, legends=('0', '10', '20', '30', '40', '50')) mhumi = Meter(wri, 25, 80, height=70, divisions=5, ptcolor=Display.YELLOW, label='humidity', style=Meter.BAR, legends=('0', '20', '40', '60', '80', '100')) steps = 11 for i in range(steps): tempC, humi = sht30.getTempAndHumi(clockStretching=SHT3X.CLOCK_STRETCH, repeatability=SHT3X.REP_S_HIGH) #print("Temperature: ",tempC,"°C, Humidity: ",humi,"%") humiText = "{0:.1f} %".format(humi) tempText = "{0:.1f} deg C".format(tempC) t = tempC / 50.0 h = humi / 100.0 mtemp.value(t) mhumi.value(h) tempLabel.value(tempText) humiLabel.value(humiText) #print(humiText) refresh(st7735) utime.sleep(1) refresh(st7735)