python pyside2:点击按钮事件 作者:马育民 • 2022-10-22 17:14 • 阅读:10509 # 简单方式 不传递参数 ``` import os import sys import PySide2 from PySide2.QtWidgets import QApplication, QPushButton dirname = os.path.dirname(PySide2.__file__) plugin_path = os.path.join(dirname, 'plugins', 'platforms') os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = plugin_path # 槽函数 def sayHello(): print("Hello World!") # Create the Qt Application app = QApplication(sys.argv) # Create a button, connect it and show it button = QPushButton("Click me") # 点击事件连接槽函数 button.clicked.connect(sayHello) button.show() # Run the main Qt loop app.exec_() ``` # 传递参数 定义带有形参的槽函数 ``` # 槽函数,有形参 def sayHello(arg): print("Hello World!",arg) ``` ### 方式一 通过 lambda 表达式 ``` button.clicked.connect(lambda : sayHello(1)) ``` ### 方式二 使用functools里的partial函数 ``` button.clicked.connect(partial(sayHello, 1)) ``` ### 完整代码 ``` import os import sys import PySide2 from PySide2.QtWidgets import QApplication, QPushButton dirname = os.path.dirname(PySide2.__file__) plugin_path = os.path.join(dirname, 'plugins', 'platforms') os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = plugin_path # 槽函数,有形参 def sayHello(arg): print("Hello World!",arg) # Create the Qt Application app = QApplication(sys.argv) # Create a button, connect it and show it button = QPushButton("Click me") # 点击事件连接槽函数,通过lambda方式传参 # button.clicked.connect(lambda : sayHello(1)) button.clicked.connect(lambda : sayHello(1)) button.show() # Run the main Qt loop app.exec_() ``` 原文出处:http://malaoshi.top/show_1IX4H6900NTq.html