PyQt5 – 为单选按钮添加动作
在这篇文章中,我们将看到如何为单选按钮设置动作。为单选按钮设置动作意味着为它添加一个动作,当单选按钮被选中或取消时,这个动作会被调用并执行一些任务。
为了给单选按钮添加动作,我们将使用toggled.connect方法。
语法: radio_button.toggled.connect(method_name)
参数: 它需要方法名称作为参数。
执行的动作: 当单选按钮被拨动时,它将调用与之相关的方法。
下面是实现方法。
# importing libraries
from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtGui
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 radio button
self.radio_button = QRadioButton(self)
# setting geometry of radio button
self.radio_button.setGeometry(200, 150, 120, 40)
# setting text to radio button
self.radio_button.setText("GEEK ?")
# creating label to display if it is checked or not
self.label = QLabel("", self)
# setting geometry of label
self.label.setGeometry(200, 200, 150, 40)
# adding action to radio button
self.radio_button.toggled.connect(self.action)
# method called by radio button
def action(self):
# changing the content of label
self.label.setText("Action performed")
# create pyqt5 app
App = QApplication(sys.argv)
# create the instance of our Window
window = Window()
# start the app
sys.exit(App.exec())