1
Current Location:
>
GUI Development
Python GUI Development from Beginner to Advanced
Release time:2024-10-22 07:43:31 read 46
Copyright Statement: This article is an original work of the website and follows the CC 4.0 BY-SA copyright agreement. Please include the original source link and this statement when reprinting.

Article link: https://yigebao.com/en/content/aid/494

Opening Topic

Hello, dear Python programmer friends! Today we're going to talk about Python GUI development. GUI (Graphical User Interface) development is an important area in Python programming. Whether you're making desktop software, web applications, or games, you can't do without beautiful and user-friendly GUIs. So what excellent GUI libraries does Python have? What are their respective features, advantages, and disadvantages? This article will explain it all to you one by one.

Tkinter: Your Best Choice for Beginners

Have you heard of Tkinter? As Python's built-in standard GUI library, Tkinter is absolutely the best choice for beginners. Not only is the code concise and easy to understand, but it also has excellent cross-platform support. Let's start with a super simple example:

import tkinter as tk

root = tk.Tk()
root.title("Hello Tkinter!")

label = tk.Label(root, text="Hello, Python GUI!")
label.pack()

root.mainloop()

This code can create a small window displaying "Hello, Python GUI!". Simple, right? Let's break it down step by step:

  1. First, import the tkinter module
  2. Create a top-level window root
  3. Set the window title to "Hello Tkinter!"
  4. Create a Label widget, set the display text
  5. Use the pack() method to add the Label to the window layout
  6. Finally, run the main event loop

With just these few lines of code, a small window is born. Isn't that cool?

Adding Interaction: Let's Play with a Button

However, just displaying information is not enough, we also need some interactive controls. For example, the most common button, let's add one and try:

import tkinter as tk

root = tk.Tk()

def hello():
    print("Hello, thanks for clicking!")

label = tk.Label(root, text="Dear, try clicking the button below?")
label.pack()

button = tk.Button(root, text="Click me", command=hello)
button.pack()

root.mainloop()

Run this code, and you'll see a window displaying "Dear, try clicking the button below?", with a "Click me" button below. Click this button, and the console will output "Hello, thanks for clicking!".

We define a hello() function and pass it as the command parameter of the button. When the button is clicked, this function will be executed. Isn't that clever?

A Small Test with Tkinter

You can develop quite nice GUI programs with Tkinter. I once used it to write a small English-Chinese dictionary lookup tool. Interested friends can download the source code from my GitHub:

https://github.com/pythonista-x/TkinterDict

Of course, if you find Tkinter a bit rudimentary or lacking some advanced features, don't worry, Python has more excellent third-party GUI libraries to choose from, such as PyQt, which we'll introduce next.

PyQt: A Professional Cross-platform Choice

PyQt is one of the most popular Python GUI libraries currently, developed based on the Qt framework. It's not only powerful and has a modern interface, but also has excellent cross-platform support, running nicely on Windows, macOS, or Linux.

Let's look at an example of creating a simple window using PyQt:

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel

app = QApplication(sys.argv)

window = QMainWindow()
window.setWindowTitle("Hello PyQt!")

label = QLabel("Welcome to PyQt!")
window.setCentralWidget(label)

window.show()
app.exec_()

Although the code is a bit longer than Tkinter's, it's not hard to understand. We first create a QApplication instance, then create a QMainWindow as the main window. Then we add a QLabel widget to the center of the window, and finally call the show() method to display the window and the exec_() method to run the event loop.

Run the code, and you'll see a window titled "Hello PyQt!" with "Welcome to PyQt!" displayed in the center.

Layout Design: PyQt is More Professional

However, just such a simple label is not enough to see. Let's add some other widgets to make the interface look more professional. The following code demonstrates how to use PyQt for layout and adding common widgets:

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QLineEdit, QPushButton, QVBoxLayout, QWidget

app = QApplication(sys.argv)
window = QMainWindow()
window.setWindowTitle("PyQt Layout Example")


central_widget = QWidget()
window.setCentralWidget(central_widget)


layout = QVBoxLayout(central_widget)


label = QLabel("Enter some text:")
layout.addWidget(label)


text_edit = QLineEdit()
layout.addWidget(text_edit)


button = QPushButton("Click me")
layout.addWidget(button)

window.show()
app.exec_()

In the code, we first create a central QWidget, then add a QVBoxLayout vertical layout on it. Then we create QLabel, QLineEdit, and QPushButton respectively, and add them to the layout in order.

Run the code, and you'll see a window with labels, text boxes, and buttons, laid out very neatly and orderly. PyQt has built-in various common layouts and rich widgets that can meet most interface design needs.

Signals and Slots: Implementing Event Handling

With the interface, we also need to handle various events, such as button clicks. In PyQt, we achieve this by connecting signals and slots. Look at the following example:

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QLineEdit, QPushButton, QVBoxLayout, QWidget

def on_button_click():
    text = text_edit.text()
    label.setText(f"You entered: {text}")

app = QApplication(sys.argv)
window = QMainWindow()
window.setWindowTitle("PyQt Signals and Slots Example")

central_widget = QWidget()
window.setCentralWidget(central_widget)

layout = QVBoxLayout(central_widget)

label = QLabel()
layout.addWidget(label)

text_edit = QLineEdit()
layout.addWidget(text_edit)

button = QPushButton("Click me")
layout.addWidget(button)

button.clicked.connect(on_button_click)

window.show()
app.exec_()

We define an on_button_click() function to respond to button click events. In this function, we get the text from the text box and set it as the display content of the label.

Then, we connect the clicked signal of the button to the on_button_click() slot function. This way, whenever the button is clicked, on_button_click() will be called to perform the corresponding operation.

Signals and slots are the core mechanism for implementing event handling in PyQt, not only convenient to use but also able to achieve low-coupling maintainable design.

Other Excellent GUI Libraries

Besides Tkinter and PyQt, Python has many other excellent GUI libraries, each with its own characteristics and advantages:

  • wxPython: Cross-platform, feature-rich, once a leader among Python GUI libraries
  • Kivy: Born for developing multi-touch applications, especially suitable for developing mobile/tablet apps
  • PyGTK: Developed based on GTK+, commonly used for Linux desktop application development
  • PySide2: Another Python binding based on Qt, can be used as an alternative to PyQt
  • Pygame: Focused on game development, can be used to make 2D games

Different libraries have their own characteristics, you can choose the appropriate one according to your needs and preferences. Regardless of which library you use, mastering the basic principles of Python GUI programming is the key.

Summary

Alright, that's all I'll share with you today. We've introduced from Tkinter's Hello World small window all the way to PyQt's signal and slot mechanism. I believe you now have a preliminary understanding of Python GUI development. Now it's up to you to practice! Remember to write some interesting small programs, accumulate experience in constant practice, and you will definitely be able to develop beautiful and practical GUI applications. Come on, looking forward to your work!

Python GUI Programming: A Constant Companion
2024-10-22 07:43:31
Next
Related articles