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