PyQt5 – 如何更改现有按钮的文本?
在本文中,我们将看到如何更改现有按钮的文本。我们知道,当我们创建一个按钮时,我们会为其设置文本,但有时会发生按钮可重用的情况,即按钮应该执行其正常操作,只是更改它的文本,所以它看起来不同。
为了做到这一点,我们使用setText
方法。此方法将覆盖按钮的现有文本。
Syntax : button.setText(new_text)
Argument : It takes string as argument.
Action performed : It over-write the text of button.
代码 :
# importing libraries
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
class Window(QMainWindow):
def __init__(self):
super().__init__()
# setting title
self.setWindowTitle("Python ")
# setting geometry
self.setGeometry(100, 100, 600, 400)
# calling method
self.UiComponents()
# showing all the widgets
self.show()
# method for widgets
def UiComponents(self):
# creating a push button
button = QPushButton("CLICK", self)
# setting geometry of button
button.setGeometry(200, 150, 100, 30)
# adding action to a button
button.clicked.connect(self.clickme)
# changing the text of button
button.setText("Over-write")
# action method
def clickme(self):
# printing pressed
print("pressed")
# create pyqt5 app
App = QApplication(sys.argv)
# create the instance of our Window
window = Window()
# start the app
sys.exit(App.exec())
输出 :