PyQt5 的按钮控件 QPushButton
被点击之后会发射一个 clicked
信号,然后再通过 QLabel
的 setText
方法改变文本控件的内容,以此来实现一个信号连接一个槽函数:
# -*- coding: utf-8 -*-
"""
Created on Sat May 9 11:11:21 2020
@author: Giyn
"""
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QVBoxLayout
class Simple_Window(QWidget):
def __init__(self):
super(Simple_Window, self).__init__() # 使用super函数可以实现子类使用父类的方法
self.label = QLabel("I am a Label", self) # self是指定的父类Simple_Window,表示QLabel属于Simple_Window窗口
self.button = QPushButton("Button", self)
self.button.clicked.connect(self.change_label) # 连接信号和槽
self.v_layout = QVBoxLayout() # 实例化一个QVBoxLayout对象
self.v_layout.addWidget(self.label)
self.v_layout.addWidget(self.button)
self.setLayout(self.v_layout) # 调用窗口的setLayout方法将总布局设置为窗口的整体布局
def change_label(self):
self.label.setText("I am changed") # 改变文本控件的内容
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Simple_Window()
window.show()
sys.exit(app.exec())
Output:
After pushing the button:
Reference:https://study.163.com/course/courseLearn.htm?courseId=1208995818