如何用pyqt5连接按键调用两个class
时间: 2023-05-21 17:01:38 浏览: 97
PyQt5基础-创建对话框,简述了PyQt5使用过程,使用QtWidgets、QPushButton类说明
您可以使用以下代码来连接按键并调用两个类:
```python
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtCore import QObject, pyqtSlot
import sys
class Class1:
def __init__(self):
print("Class1 initialized")
class Class2:
def __init__(self):
print("Class2 initialized")
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'PyQt5 button - pythonspot.com'
self.left = 10
self.top = 10
self.width = 320
self.height = 200
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
button1 = QPushButton('Class1', self)
button1.setToolTip('This is an example button')
button1.move(100,70)
button1.clicked.connect(self.on_button1_clicked)
button2 = QPushButton('Class2', self)
button2.setToolTip('This is an example button')
button2.move(100,100)
button2.clicked.connect(self.on_button2_clicked)
self.show()
@pyqtSlot()
def on_button1_clicked(self):
class1 = Class1()
@pyqtSlot()
def on_button2_clicked(self):
class2 = Class2()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
```
在这个例子中,我们创建了两个类Class1和Class2。我们使用PyQt5创建了一个窗口,并在窗口中添加了两个按钮。当用户单击按钮时,我们将调用与该按钮关联的函数。在这些函数中,我们将创建Class1或Class2的实例。
阅读全文