Nuno Bispo
1 supporter
An Intro to NiceGUI: A Modern Python Fra ...

An Intro to NiceGUI: A Modern Python Framework for Building Web UIs

Apr 23, 2024

NiceGUI is a new and easy-to-use tool for making web interfaces using Python.

It was created by a company called Zauberzeug to make it simpler for developers to build web UIs without having to worry about the complex details of web development.

In this article, we will introduce NiceGUI, explain its features, and discuss what it can be used for.


What is NiceGUI?

NiceGUI is a tool for Python developers to make web interfaces easily.

It uses popular web development libraries like Svelte and WebSocket to provide a smooth and quick user experience.

The best thing about NiceGUI is that it's simple and easy to use.

With NiceGUI, developers can create complicated web interfaces using only Python, without needing to write HTML, CSS, or JavaScript code.


Key Features of NiceGUI

NiceGUI has several useful features:

  • Easy to use: NiceGUI is designed to be simple and straightforward, so developers can create web interfaces with just a few lines of Python code. This makes it a great choice for both beginners and experienced developers.

  • Real-time interactivity: NiceGUI supports real-time interactivity, which means that any changes made to the interface are immediately shown in the web browser. This makes it perfect for creating dynamic web applications.

  • Customizable: Despite being simple to use, NiceGUI still allows for customization. Developers can use standard CSS to change the appearance and feel of their interfaces.

  • Integration: NiceGUI can be used with other Python tools and frameworks, such as NumPy, Pandas, and Flask. This allows developers to take advantage of these tools when creating web applications.

  • Easy deployment: NiceGUI provides a simple command-line interface for deploying applications. With just one command, developers can deploy their applications to a local server or a cloud-based platform.


Excited to dive deeper into the world of Python programming? Look no further than my latest ebook, "Python Tricks - A Collection of Tips and Techniques".

Get the eBook

Inside, you'll discover a plethora of Python secrets that will guide you through a journey of learning how to write cleaner, faster, and more Pythonic code. Whether it's mastering data structures, understanding the nuances of object-oriented programming, or uncovering Python's hidden features, this ebook has something for everyone.


Potential Applications of NiceGUI

NiceGUI's easy-to-use and interactive features, along with its ability to work with other tools, make it useful for many different types of projects.

Here are some examples:

  • Data Visualization: NiceGUI can be used with data analysis libraries like Pandas and Matplotlib to create interactive visualizations of data.

  • Control Systems: NiceGUI's real-time interactivity makes it a good choice for building control systems, such as those used in robotics or Internet of Things (IoT) devices.

  • Educational Tools: NiceGUI's simplicity makes it a great tool for teaching programming concepts, as it allows students to focus on understanding the logic rather than getting bogged down in syntax.


Code Examples

Before we go through the examples, first we need to install NiceGUI:

pip install nicegui

Here's a simple example of how to create a UI with a button and a label using NiceGUI.

from nicegui import ui


def button_clicked():
    ui.label('Button was clicked!')


ui.button('Click me!', on_click=button_clicked)
ui.run()
  • In this example, we start by importing the ui object from NiceGUI.

  • Next, we create a function called button_clicked that will be triggered when the button is clicked.

  • This function creates a new label that displays the text "Button was clicked!".

  • Lastly, we create a button with the text "Click me!" and tell NiceGUI to call the button_clicked function when the button is clicked by a user.

You can run NiceGUI applications as normal:

python main.py

Running the example:

Creating an Interactive UI

Here's an example of how to create an interactive UI with a slider and a label that displays the slider's value.

from nicegui import ui


def slider_changed(event):
    ui.label(f'Slider value: {event.value}')


ui.slider(min=0, max=100, on_change=slider_changed)
ui.run()
  • In this example, we start by importing the ui object from NiceGUI.

  • Then, we make a slider that can be moved between 0 and 100.

  • Whenever the slider's position is changed, a function called slider_changed is automatically run passing the slider change event.

  • This function then creates a new label that shows the current value of the slider on the screen, retrieved from the event.

Running the example:

Integration with Other Libraries

Here's an example of how to use NiceGUI with the NumPy library to create an interactive plot.

import numpy as np
from nicegui import ui

# Initialize the plot using a dictionary approach
fig = {
    'data': [{
        'x': [],
        'y': [],
        'type': 'scatter',
        'mode': 'lines'
    }],
    'layout': {
        'xaxis': {'title': 'Time'},
        'yaxis': {'title': 'Amplitude'},
        'margin': {'l': 40, 'r': 40, 't': 40, 'b': 40}
    }
}


def plot_changed(event):
    time = np.linspace(0, 1, 1000)
    data = np.sin(2 * np.pi * event.value * time)
    # Update the plot data directly
    plot.figure['data'] = [{
        'x': time,
        'y': data,
        'type': 'scatter',
        'mode': 'lines'
    }]
    plot.update()  # Explicitly call update to send the new plot to the browser


ui.slider(min=0, max=10, value=1, on_change=plot_changed)
plot = ui.plotly(fig)

ui.run()
  • First, we import the necessary libraries, np from numpy, and the ui object from NiceGUI.

  • We create a dictionary called fig that contains the initial data and layout for the plot. The plot will have one line that is initially empty. The layout specifies the titles for the x and y axes and sets the margins.

  • We define a function called plot_changed that will be called whenever the value of a slider changes. This function generates a new set of data based on the current value of the slider using numpy. It then updates the plot data directly with the new data and calls the update function to send the new plot to the browser.

  • After defining the function, we create a slider using NiceGUI and assign the plot_changed function to its on_change event. This means that whenever the slider value changes, the plot_changed function will be called.

  • Finally, we create the plot using the plotly function from NiceGUI and passing the fig dictionary. We then call the run function to start the NiceGUI loop.

  • When the user interacts with the slider, the plot_changed function is called, generating new data and updating the plot in real-time.

For this example, you also need to install numpy and the NiceGUI's plotly support:

pip install numpy nicegui[plotly]

Running the example:


Building a Calculator

This calculator example has two spaces where you can enter numbers, a dropdown menu to choose an operation (add, subtract, multiply, or divide), and a button to perform the calculation. When you click the button, the result of the calculation will appear in a label on the screen.

from nicegui import ui

def calculate():
    num1 = float(ui.input_number1.value)
    num2 = float(ui.input_number2.value)
    operation = ui.select.value

    if operation == 'add':
        result = num1 + num2
    elif operation == 'subtract':
        result = num1 - num2
    elif operation == 'multiply':
        result = num1 * num2
    elif operation == 'divide':
        result = num1 / num2
    else:
        result = 'Invalid operation'

    ui.label(f'Result: {result}')

ui.label('Number 1:')
ui.input_number1 = ui.number_input()

ui.label('Number 2:')
ui.input_number2 = ui.number_input()

ui.label('Operation:')
ui.select = ui.select(options=['add', 'subtract', 'multiply', 'divide'])

ui.button('Calculate', on_click=calculate)

ui.run()
  • In this example, we start by importing the ui object from NiceGUI.

  • We create a function called calculate that will be used when the 'Calculate' button is clicked.

  • This function takes the values from the two input fields and the dropdown menu, performs the selected mathematical operation, and shows the result in a label.

  • Next, we create the user interface (UI) components: two labels and input fields for entering the numbers, a label and a dropdown menu for selecting the operation, and a button for triggering the calculation.

  • We also specify that the calculate function should be called when the button is clicked.

  • Finally, we use the command ui.run() to start the application and display the UI on the screen.

Running the example:


Best practices for using NiceGUI

Here are some best practices for using NiceGUI:

  • Keep it Simple: NiceGUI is designed to be simple, so try to keep your code as simple and straightforward as possible. If you find yourself writing complex code, think about whether there's an easier way to achieve the same result.

  • Use Reactive Programming: NiceGUI supports reactive programming, which can make your code simpler and easier to understand. Try to use it wherever possible.

  • Create Custom Components: If you find yourself writing the same UI logic multiple times, consider creating a custom component. This can make your code more modular and easier to maintain.

  • Test Your Application: Make sure to thoroughly test your application before deploying it. NiceGUI provides a simple way to run your application locally, which can be used for testing.


Conclusion

NiceGUI is a strong and easy-to-use Python tool for making web interfaces.

Its simple design, interactive features, and ability to work with other tools make it useful for many different types of projects.

If you're just starting out and want to make your first web application, or if you're an experienced developer looking for a more efficient way to create interfaces, NiceGUI is a great option to consider.


Article originally published at: https://developer-service.blog/an-intro-to-nicegui-a-modern-python-framework-for-building-web-uis/

Enjoy this post?

Buy Nuno Bispo a coffee

More from Nuno Bispo