下面是一个使用 PyQt5 创建的简单表单提交界面的示例。该界面包含文本输入框、下拉选择框、复选框等字段,包括姓名、年龄、性别和学历等。

示例代码

import sys
from PyQt5.QtWidgets import (
    QApplication, QWidget, QVBoxLayout, QHBoxLayout,
    QLabel, QLineEdit, QComboBox, QCheckBox, QPushButton, QMessageBox
)

class FormWindow(QWidget):
    def __init__(self):
        super().__init__()

        # 设置窗口标题和尺寸
        self.setWindowTitle('Form Submission Example')
        self.resize(300, 300)

        # 创建主布局
        layout = QVBoxLayout()

        # 姓名输入
        self.name_label = QLabel('姓名:')
        self.name_input = QLineEdit()
        layout.addWidget(self.name_label)
        layout.addWidget(self.name_input)

        # 年龄输入
        self.age_label = QLabel('年龄:')
        self.age_input = QLineEdit()
        layout.addWidget(self.age_label)
        layout.addWidget(self.age_input)

        # 性别选择
        self.gender_label = QLabel('性别:')
        self.gender_combo = QComboBox()
        self.gender_combo.addItems(['男', '女', '其他'])
        layout.addWidget(self.gender_label)
        layout.addWidget(self.gender_combo)

        # 学历选择
        self.education_label = QLabel('学历:')
        self.education_combo = QComboBox()
        self.education_combo.addItems(['高中', '大专', '本科', '研究生'])
        layout.addWidget(self.education_label)
        layout.addWidget(self.education_combo)

        # 复选框
        self.subscribe_checkbox = QCheckBox('我希望接收通知')
        layout.addWidget(self.subscribe_checkbox)

        # 提交按钮
        self.submit_button = QPushButton('提交')
        self.submit_button.clicked.connect(self.submit_form)
        layout.addWidget(self.submit_button)

        # 设置主布局
        self.setLayout(layout)

    def submit_form(self):
        # 获取输入的内容
        name = self.name_input.text()
        age = self.age_input.text()
        gender = self.gender_combo.currentText()
        education = self.education_combo.currentText()
        subscribe = self.subscribe_checkbox.isChecked()

        # 显示提交的信息
        message = f"姓名: {name}\n年龄: {age}\n性别: {gender}\n学历: {education}\n希望接收通知: {'是' if subscribe else '否'}"
        
        QMessageBox.information(self, '提交信息', message)

# 主程序
if __name__ == '__main__':
    app = QApplication(sys.argv)
    form_window = FormWindow()
    form_window.show()
    sys.exit(app.exec_())

效果图:

代码解释

  1. 导入必要的模块:导入 PyQt5 的组件。
  2. 创建窗口类FormWindow 类继承自 QWidget,用于构建表单界面。
  3. 设置窗口属性:设置窗口标题和初始尺寸。
  4. 创建布局:使用 QVBoxLayout 创建主布局。
  5. 添加输入控件
    • 文本输入框:用于输入姓名和年龄。
    • 下拉选择框:用于选择性别和学历。
    • 复选框:用于选择是否希望接收通知。
  6. 添加提交按钮:设置按钮的点击事件,连接到 submit_form 方法。
  7. 提交表单
    • 在 submit_form 方法中,获取用户输入的信息,并使用 QMessageBox 显示提交的信息。
  8. 主程序:创建应用实例并显示窗口。

总结:

该示例展示了如何使用 PyQt5 创建一个简单的表单提交界面。用户可以输入姓名、年龄,选择性别和学历,并选择是否希望接收通知。点击提交按钮后,会弹出一个消息框显示提交的信息。这是一个基础的表单界面,可以根据需要进行扩展和修改。

👆🏻👆🏻👆🏻扫码关注👆🏻👆🏻👆🏻

▼点个「」赞,是我持续更新的动力 

博客地址:blog.codeceo.net