这是一个来自Zetcode.com的简单代码,我正在学习:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
ZetCode PyQt5 tutorial
In this example, we create a skeleton
of a calculator using a QGridLayout.
author: Jan Bodnar
website: zetcode.com
last edited: January 2015
"""
import sys
from PyQt5.QtWidgets import (QWidget, QGridLayout,
QPushButton, QApplication)
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
grid = QGridLayout()
self.setLayout(grid)
names = ['Cls', 'Bck', '', 'Close',
'7', '8', '9', '/',
'4', '5', '6', '*',
'1', '2', '3', '-',
'0', '.', '=', '+']
positions = [(i,j) for i in range(5) for j in range(4)]
for position, name in zip(positions, names):
if name == '':
continue
button = QPushButton(name)
grid.addWidget(button, *position)
self.move(300, 150)
self.setWindowTitle('Calculator')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
现在,我正试图将button.setDisable
选项应用于点击的每个按钮。
button_list[0].clicked.connect(self.on_click):
button_list[1].clicked.connect(self.on_click1):
对于每个新方法,我们需要定义:
def on.click(self):
button_list[0].setEnabled(False)
这是一个有效的解决方案。但是有没有更有活力的方法来解决这个问题呢?
欢迎指教
对于lambda
或functools.partial
,您可以这样做:
def on.click(self, numb):
button_list[numb].setEnabled(False)
调用lambda
:
button_list[1].clicked.connect(lambda: self.on_click(1))
或与partial
:
button_list[1].clicked.connect(partial(self.on_click, 1))