当前位置:首页 > 技术知识 > 正文内容

惊了!原来 Python PySide6 GUI 开发的按钮有这么多玩法

maynowei6个月前 (09-18)技术知识57

点赞、收藏、加关注,下次找我不迷路

为什么选择 PySide6 进行 GUI 开发


在众多 Python GUI 框架中,如 Tkinter、PyQt、wxPython 等,PySide6 脱颖而出。它是 Qt 框架的官方 Python 绑定,具有跨平台特性,能在 Windows、Mac、Linux 等系统上运行。PySide6 不仅提供丰富的 GUI 组件,还使用 LGPL 许可证,这意味着开发者在商业项目中使用它时更加自由,无需担心许可证问题。同时,它对 Python 的支持非常友好,代码简洁易懂,适合新手入门。

PySide6 中的按钮类型概览


在 PySide6 的 QtWidgets 模块中,提供了多种按钮类型,每种按钮都有其独特的用途和特点。下面我们通过表格来简单了解一下:

名称

翻译

PySide6 对应的类

意义

Push Button

按钮

QPushButton

普通按钮,点击触发事件

Tool Button

工具按钮

QToolButton

通常是带图标的按钮

Radio Button

单选按钮

QRadioButton

一组选项中只能选择一个

Check Box

复选框

QCheckBox

允许选择多个选项

Command Link Button

命令链接按钮

QCommandLinkButton

带描述的链接按钮,常用于对话框中,外观像链接

Dialog Button Box

对话框按钮框

QDialogButtonBox

标准对话框按钮框,包含常见按钮,如 “确定”“取消” 等

接下来,我们详细介绍每种按钮类型。

Push Button(QPushButton)

Push Button 是最常见的按钮类型,就像我们日常使用软件时点击的各种确认、提交按钮。在 PySide6 中创建一个 Push Button 非常简单,以下是一个示例代码:

import sys
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton


class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Push Button示例")
        self.setGeometry(100, 100, 400, 300)
        layout = QVBoxLayout()
        button = QPushButton("点击我")
        button.clicked.connect(self.on_button_click)
        layout.addWidget(button)
        self.setLayout(layout)

    def on_button_click(self):
        print("按钮被点击了!")


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

在这段代码中,我们创建了一个继承自 QWidget 的 MainWindow 类。在类的初始化方法中,设置了窗口的标题和大小,并创建了一个垂直布局(QVBoxLayout)。然后创建了一个 QPushButton,按钮上的文本为 “点击我”,并通过button.clicked.connect(self.on_button_click)将按钮的点击事件与on_button_click方法绑定。当按钮被点击时,会在控制台打印 “按钮被点击了!”。

Push Button 还有很多属性可以设置,比如按钮的字体、图标、快捷键等。例如,要设置按钮的图标,可以这样做:

icon = QIcon("icon.png")
button.setIcon(icon)

这样就可以为按钮添加一个图标,使按钮更加直观和美观。

Tool Button(QToolButton)

Tool Button 通常用于提供快速访问常用工具或操作的功能,一般以图标显示为主,尺寸相对较小。比如在绘图软件中,用于选择画笔、橡皮擦等工具的按钮就可能是 Tool Button。以下是创建一个 Tool Button 的示例代码:

import sys
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout, QToolButton
from PySide6.QtGui import QIcon


class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Tool Button示例")
        self.setGeometry(100, 100, 400, 300)
        layout = QVBoxLayout()
        tool_button = QToolButton()
        tool_button.setIcon(QIcon("brush_icon.png"))
        tool_button.setToolTip("选择画笔工具")
        tool_button.clicked.connect(self.on_tool_button_click)
        layout.addWidget(tool_button)
        self.setLayout(layout)

    def on_tool_button_click(self):
        print("画笔工具被点击了!")


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

在这个示例中,我们创建了一个 QToolButton,通过setIcon方法设置了按钮的图标,使用setToolTip方法为按钮添加了提示信息,当鼠标悬停在按钮上时会显示该提示。同样,通过clicked.connect方法将按钮的点击事件与相应的处理方法绑定。



Radio Button(QRadioButton)

Radio Button 用于在一组选项中只能选择一个的场景。比如在设置性别时,“男” 和 “女” 两个选项通常会使用 Radio Button。以下是一个简单的示例:

import sys
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout, QRadioButton


class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Radio Button示例")
        self.setGeometry(100, 100, 400, 300)
        layout = QVBoxLayout()
        male_radio = QRadioButton("男")
        female_radio = QRadioButton("女")
        male_radio.toggled.connect(lambda: self.on_radio_toggled(male_radio))
        female_radio.toggled.connect(lambda: self.on_radio_toggled(female_radio))
        layout.addWidget(male_radio)
        layout.addWidget(female_radio)
        self.setLayout(layout)

    def on_radio_toggled(self, radio_button):
        if radio_button.isChecked():
            print(f"{radio_button.text()}被选中了")


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

在这段代码中,我们创建了两个 QRadioButton,分别为 “男” 和 “女”。通过
radio_button.toggled.connect方法将按钮的状态切换事件与on_radio_toggled方法绑定。在on_radio_toggled方法中,通过isChecked方法判断按钮是否被选中,如果被选中则打印相应的信息。



Check Box(QCheckBox)

Check Box 允许用户选择多个选项。例如在一个文件下载任务中,用户可以选择多个文件进行下载,这时就可以使用 Check Box。以下是示例代码:

import sys
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout, QCheckBox


class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Check Box示例")
        self.setGeometry(100, 100, 400, 300)
        layout = QVBoxLayout()
        file1_checkbox = QCheckBox("文件1")
        file2_checkbox = QCheckBox("文件2")
        file3_checkbox = QCheckBox("文件3")
        file1_checkbox.stateChanged.connect(lambda: self.on_checkbox_changed(file1_checkbox))
        file2_checkbox.stateChanged.connect(lambda: self.on_checkbox_changed(file2_checkbox))
        file3_checkbox.stateChanged.connect(lambda: self.on_checkbox_changed(file3_checkbox))
        layout.addWidget(file1_checkbox)
        layout.addWidget(file2_checkbox)
        layout.addWidget(file3_checkbox)
        self.setLayout(layout)

    def on_checkbox_changed(self, checkbox):
        if checkbox.isChecked():
            print(f"{checkbox.text()}被选中了")
        else:
            print(f"{checkbox.text()}被取消选中了")


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

这里创建了三个 QCheckBox,分别代表 “文件 1”“文件 2”“文件 3”。通过stateChanged.connect方法将复选框状态改变事件与on_checkbox_changed方法绑定。在on_checkbox_changed方法中,根据isChecked方法的返回值判断复选框是被选中还是取消选中,并打印相应信息。



Command Link Button(QCommandLinkButton)

Command Link Button 是一种带描述的链接按钮,通常用于对话框中,外观像链接。它可以提供更多的信息给用户,引导用户进行操作。以下是创建一个 Command Link Button 的示例:

import sys
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout, QCommandLinkButton


class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Command Link Button示例")
        self.setGeometry(100, 100, 400, 300)
        layout = QVBoxLayout()
        command_link_button = QCommandLinkButton("重要操作", "这是一个重要操作的详细描述")
        command_link_button.clicked.connect(self.on_command_link_click)
        layout.addWidget(command_link_button)
        self.setLayout(layout)

    def on_command_link_click(self):
        print("重要操作按钮被点击了!")


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

在这个示例中,创建了一个 QCommandLinkButton,第一个参数是按钮的主要文本,第二个参数是描述性文本。通过clicked.connect方法将按钮点击事件与处理方法绑定,当按钮被点击时,会在控制台打印相应信息。



Dialog Button Box(QDialogButtonBox)

Dialog Button Box 是标准对话框按钮框,包含常见的按钮,如 “确定”“取消”“应用” 等。它可以方便地管理对话框中的按钮布局和行为。以下是一个简单示例:

import sys
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout, QDialogButtonBox, QMessageBox


class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Dialog Button Box示例")
        self.setGeometry(100, 100, 400, 300)
        layout = QVBoxLayout()
        button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        button_box.accepted.connect(self.on_accept)
        button_box.rejected.connect(self.on_reject)
        layout.addWidget(button_box)
        self.setLayout(layout)

    def on_accept(self):
        QMessageBox.information(self, "提示", "你点击了确定按钮")

    def on_reject(self):
        QMessageBox.information(self, "提示", "你点击了取消按钮")


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

在这段代码中,创建了一个 QDialogButtonBox,通过QDialogButtonBox.Ok | QDialogButtonBox.Cancel指定了按钮框中包含 “确定” 和 “取消” 按钮。通过accepted.connect和rejected.connect方法分别将 “确定” 按钮的点击事件(对应 accepted 信号)和 “取消” 按钮的点击事件(对应 rejected 信号)与相应的处理方法绑定。当点击 “确定” 或 “取消” 按钮时,会弹出一个消息框提示用户。

相关文章

Oracel:ORA-12518:监听程序无法分发客户机连接

一、【问题描述】 最近,在系统高峰期的时候,会提示如上的错误,致使无法连接到服务器上的数据库。二、【分析过程】 1、首先判断是否由于监听配置不正确的原因导致? 系统在正常情况下都可以正常的使用,检查监...

美文欣赏:Learn to think—学会思考

Learning to think is one of the important tasks in life.学会思考,是人生的重要任务之一。Cultivating the ability of i...

我们生活在模拟世界中吗?(我们生活在虚拟世界的一些证据)

Are We Living in a Simulation? 我们生活在模拟世界中吗Annie Palmer 安妮·帕尔默The idea of humans living in a simulate...

在w3cschool上学完html、css后要怎么提升

原标题:在w3cschool学完html,css,javascript,jquery以后,还是不会做前端怎么办?w3cschool是一个非盈利性的在线技术学习网站,提供按W3C标准编写的基础教程。完整...

被 OpenAI 点名后,智谱刚刚发布新开源模型:国产最全能,一句话造出搜索引擎

国产大模型厂商的开源,还在提速。就在刚刚,智谱正式发布最新旗舰模型 GLM-4.5。按照智谱官方说法,这是一款「专为 Agent 应用打造的基础模型」。延续一贯的开源原则,目前这款模型已经在 Hugg...

一文带你彻底搞懂Proxy和Reflect!

有一道面试题,题目要求应用 Proxy 实现数据倒序访问,如: var arr=[1, 2, 3, 4]; arr[-1] 返回 4,arr[-2] 返回 3。这个题目很显然在考察 Proxy 对象的...