Create a Random Number Generator with QLCDNumber in PyQt6

In this PyQt6 tutorial, I’ll show you how to build a simple random number generator using the QLCDNumber widget.

It is a step‑by‑step, detailed guide that helps you understand how to create a random number generator in a better way.

You may have come across generating random numbers if you have worked on game dice rolls, lottery simulators to testing tools, and data sampling scripts, etc.

If you are new to learn PyQt6, here is a post where you can learn about some Basic Widgets in PyQt6, that will help you understand the foundation of GUI development with PyQt6.

Step 1: Import Required Modules

To build a random number generator GUI with PyQt6, we start by importing the key modules we’ll need. These include tools to create the main window, design layouts, add buttons and LCDs, and, of course, handle the random number generation.

import sys
import random
from PyQt6.QtWidgets import (
    QApplication, QMainWindow, QWidget,
    QVBoxLayout, QLCDNumber, QPushButton, QLabel,
    QHBoxLayout, QSlider, QSpinBox
)
from PyQt6.QtCore import Qt

This code creates a simple interface where:

  • The LCD initially displays a default value (like 0 or blank)
  • When the button is pressed, the program generates a random number using the randint() function
  • The LCD is updated to show the new random number
  • The system continues to wait for button presses or user interactions like changing the digit count or range

Read Build a Simple Digital Clock with QLCDNumber in PyQt6

Step 2: Create a Basic PyQt6 Window

Now let us move on to setting up the main part of the app—the window itself. Here, we use QMainWindow to create the main application window and add a central layout that will hold and organize all our widgets neatly.

We also add a QLCDNumber widget, which is the cool digital-style display where our random numbers will appear, just like a digital clock.

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Random Number Generator")
        self.setGeometry(100, 100, 400, 250)

        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        self.layout = QVBoxLayout(central_widget)

        # Add LCD Display
        self.lcd = QLCDNumber()
        self.lcd.setDigitCount(3)  # Show 3 digits
        self.layout.addWidget(self.lcd)

This code creates a simple window where:

  • A QMainWindow is initialized with a title and dimensions
  • A vertical layout is used to organize widgets vertically
  • An LCD is added to show up to 3-digit numbers
  • This window now acts as the foundation for adding further interactive features

Check out QSpinBox Widget in PyQt6

Step 3: Generate Random Numbers

Let us add a button that users can click to generate a random number. When the button is pressed, it triggers the generate_random_number() function, which uses Python’s random.randint() to pick a number between 1 and 999.

        # Add Button
        generate_button = QPushButton("Generate Random Number")
        generate_button.clicked.connect(self.generate_random_number)
        self.layout.addWidget(generate_button)

    def generate_random_number(self):
        number = random.randint(1, 999)
        self.lcd.display(number)

This code enables interactive number generation where:

  • A button is displayed below the LCD
  • When the button is clicked, a random number is generated using random.randint()
  • The LCD is immediately updated to display the new random number
  • The user can continue clicking the button to get different random values each time

Read QCheckBox Widget in PyQt6

Step 4: Add Custom Styling

We use setSegmentStyle() to choose how the digits appear—like flat or filled segments—and then apply a stylesheet to tweak the background color, text color, rounded corners, and add some padding. It gives the widget a sleek, user-friendly feel.

        # Change Segment Style (Outline, Filled, Flat)
        self.lcd.setSegmentStyle(QLCDNumber.SegmentStyle.Flat)

        # Set background and text color
        self.lcd.setStyleSheet("""
            background-color: #222;
            color: #00FF00;
            border-radius: 10px;
            padding: 10px;
        """)

The segment style is set to Flat for a smooth, clean appearance. The background is dark (#222) and the text color is bright green (#00FF00) for better contrast. Rounded corners and padding are added for a polished, modern look

Check out QRadioButton Widget in PyQt6

Step 5: Add User Controls

With easy-to-use spin boxes, they can set the minimum and maximum values, and choose how many digits the LCD should show.

        # Min and Max Range Controls
        range_layout = QHBoxLayout()

        range_layout.addWidget(QLabel("Min:"))
        self.min_spin = QSpinBox()
        self.min_spin.setRange(0, 999)
        self.min_spin.setValue(1)
        range_layout.addWidget(self.min_spin)

        range_layout.addWidget(QLabel("Max:"))
        self.max_spin = QSpinBox()
        self.max_spin.setRange(1, 999)
        self.max_spin.setValue(999)
        range_layout.addWidget(self.max_spin)

        self.layout.addLayout(range_layout)

        # Digit Count Control
        digit_layout = QHBoxLayout()
        digit_layout.addWidget(QLabel("Digits:"))
        self.digit_spin = QSpinBox()
        self.digit_spin.setRange(1, 6)
        self.digit_spin.setValue(3)
        self.digit_spin.valueChanged.connect(self.update_digits)
        digit_layout.addWidget(self.digit_spin)

        self.layout.addLayout(digit_layout)

    def update_digits(self):
        self.lcd.setDigitCount(self.digit_spin.value())

Now users can easily choose their number range with the Min and Max spin boxes. The Digit Count box lets them decide how many digits to show on the LCD, making the app more flexible and fun to use.

Read Handle Button Click Events Using Signals and Slots in PyQt6?

Random Number Generator with QLCDNumber in PyQt6

Let us create an interactive GUI to generate and display random numbers using an LCD. It includes user controls to customize the number range and digit count.

import sys
import random
from PyQt6.QtWidgets import (
    QApplication, QMainWindow, QWidget,
    QVBoxLayout, QLCDNumber, QPushButton, QLabel,
    QHBoxLayout, QSpinBox
)
from PyQt6.QtCore import Qt

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Random Number Generator")
        self.setGeometry(100, 100, 400, 300)

        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        self.layout = QVBoxLayout(central_widget)

        # LCD Display
        self.lcd = QLCDNumber()
        self.lcd.setDigitCount(3)
        self.lcd.setSegmentStyle(QLCDNumber.SegmentStyle.Flat)
        self.lcd.setStyleSheet("""
            background-color: #222;
            color: #00FF00;
            border-radius: 10px;
            padding: 10px;
        """)
        self.layout.addWidget(self.lcd)

        # Generate Button
        generate_button = QPushButton("Generate Random Number")
        generate_button.clicked.connect(self.generate_random_number)
        self.layout.addWidget(generate_button)

        # Min/Max Range Controls
        range_layout = QHBoxLayout()
        range_layout.addWidget(QLabel("Min:"))
        self.min_spin = QSpinBox()
        self.min_spin.setRange(0, 999)
        self.min_spin.setValue(1)
        range_layout.addWidget(self.min_spin)

        range_layout.addWidget(QLabel("Max:"))
        self.max_spin = QSpinBox()
        self.max_spin.setRange(1, 999)
        self.max_spin.setValue(999)
        range_layout.addWidget(self.max_spin)

        self.layout.addLayout(range_layout)

        # Digit Count Control
        digit_layout = QHBoxLayout()
        digit_layout.addWidget(QLabel("Digits:"))
        self.digit_spin = QSpinBox()
        self.digit_spin.setRange(1, 6)
        self.digit_spin.setValue(3)
        self.digit_spin.valueChanged.connect(self.update_digits)
        digit_layout.addWidget(self.digit_spin)

        self.layout.addLayout(digit_layout)

    def generate_random_number(self):
        min_val = self.min_spin.value()
        max_val = self.max_spin.value()
        if min_val > max_val:
            min_val, max_val = max_val, min_val
        number = random.randint(min_val, max_val)
        self.lcd.display(number)

    def update_digits(self):
        self.lcd.setDigitCount(self.digit_spin.value())

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())

You can see the output in the screenshot below.

Create a Random Number Generator with QLCDNumber in PyQt6

This code creates a simple interface where:

  • The LCD shows numbers with a customized digit count and style
  • When the button is pressed, a random number is generated using randint() within the selected range
  • The LCD updates to show the new number
  • The user can adjust the range and digit count anytime for dynamic results

Check out Arrange Widgets Using QGridLayout in PyQt6?

Handle Edge Cases

When building a Random Number Generator (RNG) with QLCDNumber in PyQt6, it’s essential to handle edge cases and prevent issues like UI freezes, especially when dealing with real-time updates.

Handle Oversized Numbers for QLCDNumber

  • The QLCDNumber widget can only display as many digits as you configure with setDigitCount().
  • If you generate a number that has more digits than the display allows, the extra leading digits simply won’t appear, and you may end up showing only the least‑significant digits, which can confuse your users.
  • To avoid this, you either need to constrain your random number generator so it never exceeds the digit limit or you need to detect when a number is too large and handle it gracefully, perhaps by truncating it, showing an error indicator, or automatically reducing it to fit the display.

Prevent UI Freezes with QTimer

  • In PyQt6, long‑running or blocking tasks on the main thread will cause the interface to become unresponsive.
  • If you update your random number generator in a tight loop or perform heavy computations directly in your UI code, you’ll see the window hang or stop repainting.
  • Instead, use a QTimer to schedule periodic updates: the timer posts a lightweight event into the Qt event loop at the interval you choose, allowing the GUI to remain responsive between ticks.

Related articles, which may help you to master PyQt6:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.