Another Python graphical interface library, simple and easy to use

a5552ab468ec495f816495575adb4b57.png

Lost Little Book Boy's Note

need to finish reading

10

minute

Speed ​​reading in just 4 minutes

1

   

environment

  • python 3.9.16

  • nicegui 1.3.9

2

   

foreword

In modern computer application development, the graphical user interface (GUI) is an important part of the user's interaction with the program. However, GUI development often requires a large amount of code and complex layout, which brings certain challenges to developers. In this blog post, I will introduce nicegui, an easy-to-use graphical user interface library that provides a way to simplify GUI development and enable developers to build attractive user interfaces more quickly.

3

   

Realization principle

nicegui is developed based on the Python programming language and uses a declarative way to describe the user interface. Its design is inspired by HTML and CSS in web development, and describes the components and styles of the interface through a similar structured syntax.

The core idea of ​​nicegui is to divide the user interface into multiple components, each with its own properties and styles. Developers can use the component libraries provided by nicegui, such as buttons, text boxes, drop-down menus, etc., to define and layout these components through simple code. At the same time, nicegui also supports custom components, and developers can expand the component library according to their own needs.

4

   

Install

You can use pip to install, the specific operation is as follows

pip install nicegui

5

   

sample code

Below is a simple nicegui sample code

from nicegui import ui


ui.label('Hello NiceGUI!')
ui.button('BUTTON', on_click=lambda: ui.notify('button was pressed'))


ui.run()

In the above code, first import the ui module in nicegui, which contains commonly used components

f5a9faa3038691b56632b6b902304a28.png

The label and button are used in the example, by default, they are vertically laid out, and the run method is used to start the service

Execute the above script, you can visit http://127.0.0.1:8080 in the browser to see the effect

0f13173cffaedbb6100703aebd338aaa.png

Click the BUTTON button, and a prompt message will be displayed below

919da90921f0c2b7645b72be4ee78726.png

Next, let's look at a complete example

from dataclasses import dataclass, field
from typing import Callable, List


from nicegui import ui




@dataclass
class TodoItem:
    name: str
    done: bool = False




@dataclass
class ToDoList:
    title: str
    on_change: Callable
    items: List[TodoItem] = field(default_factory=list)


    def add(self, name: str, done: bool = False) -> None:
        self.items.append(TodoItem(name, done))
        self.on_change()


    def remove(self, item: TodoItem) -> None:
        self.items.remove(item)
        self.on_change()




@ui.refreshable
def todo_ui():
    if not todos.items:
        ui.label('List is empty.').classes('mx-auto')
        return
    ui.linear_progress(sum(item.done for item in todos.items) / len(todos.items), show_value=False)
    with ui.row().classes('justify-center w-full'):
        ui.label(f'Completed: {sum(item.done for item in todos.items)}')
        ui.label(f'Remaining: {sum(not item.done for item in todos.items)}')
    for item in todos.items:
        with ui.row().classes('items-center'):
            ui.checkbox(value=item.done, on_change=todo_ui.refresh).bind_value(item, 'done')
            ui.input(value=item.name).classes('flex-grow').bind_value(item, 'name')
            ui.button(on_click=lambda item=item: todos.remove(item), icon='delete').props('flat fab-mini color=grey')




todos = ToDoList('My Weekend', on_change=todo_ui.refresh)
todos.add('Order pizza', done=True)
todos.add('New NiceGUI Release')
todos.add('Clean the house')
todos.add('Call mom')


with ui.card().classes('w-80 items-stretch'):
    ui.label().bind_text_from(todos, 'title').classes('text-semibold text-2xl')
    todo_ui()
    add_input = ui.input('New item').classes('mx-12')
    add_input.on('keydown.enter', lambda: (todos.add(add_input.value), add_input.set_value('')))


ui.run()

This code creates a simple to-do list application using nicegui. Let's analyze its function and logic step by step

First, the necessary modules and classes are imported. The dataclasses module provides a decorator dataclass for creating concise and powerful data classes. A data class is a special class primarily used to store data, and usually contains only properties and no methods.

Next, two data classes are defined: TodoItem and ToDoList. TodoItem represents a to-do item, and has two properties of name and done, where done indicates whether the to-do item has been completed. ToDoList represents the list of to-do items, and has three attributes: title, on_change and items, among which items is a list of TodoItem objects. ToDoList also provides add and remove methods for adding and removing to-do items.

Next, a UI function called todo_ui is defined and marked as a refreshable UI function using the @ui.refreshable decorator. The todo_ui function is used to render the interface of the todo list.

In the todo_ui function, first check whether the to-do list is empty, if it is empty, display a label with the content List is empty., and display it in the center. Then, use ui.linear_progress to create a linear progress bar that shows the proportion of completed tasks, calculate the number of completed tasks and divide by the total number of tasks, and pass this value to the ui.linear_progress function. Next, use ui.row to create a row layout container, and add two labels to the container to display the number of completed tasks and the number of remaining tasks. By iterating through each item in the to-do list, the number of completed tasks and the number of remaining tasks are calculated and displayed in the label. Next, use ui.row and ui.checkbox to create a row layout and a checkbox to display and edit the completion status of the todo. Bind the value of the checkbox by setting the value parameter, and use the on_change parameter to specify the callback function to be called when the state of the checkbox changes. Use the bind_value method to bind the value of the check box with the done attribute of the to-do item object to realize dynamic update. Then, use ui.row and ui.input to create a row layout and an input box to display and edit the name of the todo. Bind the value of the input box with the name attribute of the to-do object by setting the initial value of the input box and using the bind_value method.

Finally, use ui.row and ui.button to create a row layout and a delete button to delete the todo. Specify the callback function to be called when the button is clicked by setting the on_click parameter of the button, and use a lambda expression to pass the todo object as a parameter. Use the props method to set the button's style and icon.

In the main program, a ToDoList instance todos is created, the title is set as My Weekend, and the function todo_ui is specified to refresh the interface when the to-do list changes. Then, some initial todos are added by calling the todos.add method. Next, use ui.card to create a card container and set its style. In the card container, create a label and use the bind_text_from method to bind its text to the title attribute of the todos instance to achieve dynamic update. Then, call the todo_ui function to render the todo list interface. Create an input box add_input to add a new to-do item. By listening to the keydown.enter event of the add_input input box, when the user presses the Enter key, call the todos.add method to use the value of the input box as a new to-do item Adds the item to the list and resets the value of the input box to an empty string.

Finally, call ui.run to start the event loop of the nicegui application, display the interface and wait for user interaction.

1052c3e5a4381fa0a099e1910f13b20a.png

Through this sample project, we can see the simplicity and ease of use of nicegui, and developers can quickly build a fully functional application interface.

6

   

References

  • https://github.com/zauberzeug/nicegui ( https://github.com/zauberzeug/nicegui )

  • https://nicegui.io/documentation ( https://nicegui.io/documentation )

7

   

Free Knowledge Planet

52709214c4860c1ea14ec48162e1da19.jpeg

Guess you like

Origin blog.csdn.net/djstavaV/article/details/132388054