0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

NiceGUIで電卓的なもの

Posted at

NiceGUI

NiceGUI(https://nicegui.io/) はPythonのGUIライブラリで、Webブラウザに表示するもの。まだあまり記事がないみたいなので、テストとして書いた簡単な電卓プログラムをおいておく。

image.png

ポイント

  • ボタンのコールバック関数は一つにして、ボタンのテキストで分岐
  • ShutdownボタンでUIを停止。これでui.run()のブロックがほどけるので、スレッドも死ぬ。
  • 表示領域のアップデートは _handle_text_change で行っている。これはもっといい方法がありそう。
  • スタイルはcssで制御するのだと思うが、やり方がよくわからない。
import threading
from nicegui import ui, app

ui_thread = threading.Thread(target=lambda: ui.run(reload=False))
ui_thread.start()

class Calculator:
    def __init__(self, ui):
        ui.label("Calclator")
        self.val = 0
        self.prev = 0
        self.op = None
        # 表示部
        self.display = ui.label().classes('p-3 bg-blue-100')

        # グリッド状にボタンを配置
        with ui.grid(columns=3):
            for i in range(10):
                ui.button(str(i), on_click=self.clicked)
            ui.label("")
            ui.label("")            
            ui.button('+', on_click=self.clicked)
            ui.button('-', on_click=self.clicked)
            ui.button('=', on_click=self.clicked)
        # このボタンを押すとGUIプロセスが死ぬ
        ui.button('shutdown', on_click=lambda : app.shutdown())            
        self.display_update()

    def display_update(self):
        self.display._handle_text_change(str(self.val))

    def clicked(self, e):
        print(e.sender.text)
        try:
            self.val = self.val * 10 + int(e.sender.text)
        except ValueError:
            if e.sender.text == '+':
                self.op = '+'
                self.prev = self.val
                self.val = 0
            elif e.sender.text == '-':
                self.op = '-'
                self.prev = self.val
                self.val = 0
            elif e.sender.text == '=':
                if self.op == '+':
                    self.val = self.prev + self.val
                elif self.op == '-':
                    self.val = self.prev - self.val
                self.op == None                    

        self.display_update()

c = Calculator(ui)
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?