Welcome to the World of Linux and Python GUI Programming!

Hey there, fellow Linux enthusiasts! If you’ve recently chosen to step into the exciting universe of Arch Linux or Cachyos, you’ve made a fantastic decision. Not only does Linux offer a powerful and flexible operating system, but it also opens the door to programming—an incredibly rewarding skill that can enhance your career and create a world of opportunities.

In this tutorial, we’ll guide you through setting up a virtual Python environment, installing the necessary tools to develop GUI applications, and creating a simple password generator app. Hopefully, you’ll enjoy this article and develop an interest in programming.

Please note that all commands and instructions provided in this blog post have been tested on CachyOS running KDE Plasma as of September 3, 2024. While these instructions should work on similar environments, results may vary based on different operating systems or configurations. If you encounter any issues, please feel free to reach out in the comments for assistance.

Step 1: Creating a Virtual Python Environment

Since Python is already installed on our system, we can skip the installation step and directly create a virtual environment. Using a virtual environment (venv) helps us manage project-specific dependencies and avoids conflicts with packages in the global Python installation.

To create a new virtual environment named myenv, first navigate to a preferred directory such as /home/username (or where ever you prefer):

Then, run the following command to set up the virtual environment:

This command creates a new directory called my_python_projects and sets up a virtual environment named myenv, allowing us to install packages specifically for this project without affecting the global Python environment.

Step 2: Activating the Virtual Environment

Activate the virtual environment with this command:

Your terminal prompt will change to indicate that we’re now working within the virtual environment. When we’re done, you can deactivate it with:

Step 3: Installing Required Tools for GUI Development

Next, let’s install the Qt6 base tools, which are essential for creating GUI applications. Use pip to install them:

pip install pyqt6 learn python gt applications programming

Step 4: Sample GUI Application

Now that we have installed all the necessary packages, we can write the sample code as shown below. Please use a text editor of your choice, such as Kate, Gnome Text, or any other text editor available on your system.

  1. Open your text editor.
  2. Create a new file and paste the provided sample code into the file.
  3. Save the file with a .py extension (e.g., password_generator.py) to indicate that it’s a Python script.

Make sure to save your work in a directory where you can easily find it later for running the program.

Sample Code

Now, let’s write a simple app that generates a secure password based on user input. Create a new Python file, for example, password_generator.py, and add the following code:

import sys
import random
import string
from PyQt6.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QPushButton, QVBoxLayout, QTextEdit, QMessageBox, QSizePolicy
from PyQt6.QtCore import Qt

def generate_password(length):
    """Generates a random password of specified length."""
    characters = string.ascii_letters + string.digits + string.punctuation.replace('/', '').replace('\\', '').replace('|', '')
    return ''.join(random.choice(characters) for _ in range(length))

class PasswordGeneratorApp(QWidget):
    """Main application class for the password generator GUI."""
    def __init__(self):
        super().__init__()

        self.setWindowTitle("PWGEN")
        self.setGeometry(100, 100, 360, 250)  # Set window size

        # Set up the main layout
        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

        # Instruction Label
        self.length_label = QLabel("Enter password length (1-24):")
        self.length_label.setStyleSheet("font-size: 16px;")  # Set larger font size
        self.layout.addWidget(self.length_label, alignment=Qt.AlignmentFlag.AlignCenter)  # Center the label

        # Spacer between label and input field
        self.layout.addSpacing(10)  # Add spacing

        # Input field for length
        self.length_entry = QLineEdit(self)
        self.length_entry.setMaxLength(2)  # Limit input length to 2 characters (up to 24)
        self.length_entry.setStyleSheet("font-size: 16px; background-color: #1C1C1C; color: white; border: none;")  # Match colors
        self.layout.addWidget(self.length_entry, alignment=Qt.AlignmentFlag.AlignCenter)  # Center the input field

        # Spacer between input field and button
        self.layout.addSpacing(10)  # Add spacing

        # Center-aligned button
        self.generate_button = QPushButton("Generate Password")
        self.generate_button.setStyleSheet("background-color: green; color: white; font-size: 18px;")  # Larger font for the button
        self.generate_button.setFixedSize(200, 50)  # Increased size for the button
        self.layout.addWidget(self.generate_button, alignment=Qt.AlignmentFlag.AlignCenter)

        # Spacer between button and password output field
        self.layout.addSpacing(20)  # More spacing above the output field

        # Output field configured for generated password
        self.password_text_edit = QTextEdit()  # Use QTextEdit for selectable text
        self.password_text_edit.setReadOnly(True)  # Make it read-only
        self.password_text_edit.setStyleSheet("font-size: 16px; background-color: #1C1C1C; color: white; border: none;")  # Match colors
        self.password_text_edit.setMinimumHeight(40)  # Enough height for visibility
        self.password_text_edit.setFixedHeight(40)  # Keep height fixed to avoid wrapping

        # Set a size policy to allow fully expanding the textarea horizontally
        self.password_text_edit.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)

        # Make the output field stretch to fit the width of the window
        self.layout.addWidget(self.password_text_edit, alignment=Qt.AlignmentFlag.AlignCenter)

        # Set button hover effects
        self.generate_button.enterEvent = self.on_hover
        self.generate_button.leaveEvent = self.on_leave

        # Connect button click to the handler
        self.generate_button.clicked.connect(self.on_generate_button_click)

    def on_generate_button_click(self):
        """Handles button click event for password generation."""
        try:
            length = int(self.length_entry.text())
            if length < 1 or length > 24:
                raise ValueError("Length must be between 1 and 24.")

            password = generate_password(length)
            self.password_text_edit.setText(password)  # Update the displayed password

        except ValueError:
            QMessageBox.critical(self, "Invalid Input", "Please enter a valid integer between 1 and 24.")

    def on_hover(self, event):
        """Change button color on hover."""
        self.generate_button.setStyleSheet("background-color: #45a049; color: white; font-size: 18px;")

    def on_leave(self, event):
        """Revert button color when not hovered."""
        self.generate_button.setStyleSheet("background-color: green; color: white; font-size: 18px;")

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

Running The App

To run your application, make sure your virtual environment is activated. Then, in your terminal, execute:

You should see a simple GUI where you can input a password length and generate a random password!

free password generator Python GUI app
Actual screenshot of the app we just made

Did You Know

When utilizing a secure password consisting of 24 characters that incorporates a mix of uppercase letters, lowercase letters, numbers, and special characters, the total number of unique possibilities skyrockets.

With an estimated character set of around 70 (26 uppercase + 26 lowercase + 10 digits + 8 special characters), a 24-character password would yield approximately ( 70^{24} ) unique combinations—an astounding figure around 8.6 quintillion possibilities!

Considering current technology, even with sophisticated brute-force attacks employing powerful graphics processing units (GPUs) that can test billions of combinations per second, it would take even the most determined hacker an astronomical amount of time to crack such a password. In fact, it is estimated that cracking such a robust password could take millions of years, making 24-character passwords an exceptionally secure choice for protecting your sensitive information.

Conclusion

Congratulations on reaching the end of this tutorial! By completing these steps, you’ve not only installed Python, but you’ve also developed your first GUI application.

If you’re interested in learning more about programming, we invite you to start our free course, “I Can Program”, which is designed especially for new Linux users who are just starting their programming journey.

Lastly, remember that while gaming can be fun, dedicating time to learn programming opens up a fascinating world of possibilities and rewards. Every hour you invest in learning could lead to great advancements in your career and personal projects. So dive in, explore, and enjoy all that programming has to offer!

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.