I'm new to Python and PyQt and this is my first application. Currently when a button is clicked, toggleLED()
checks self.LedOn
to decide whether to turn an LED on.
class Screen(QWidget):
def initUI(self):
self.LedOn = 0
btn = QPushButton('Off', self)
btn.setCheckable(True)
btn.clicked.connect(self.toggleLED)
def toggleLED(self, pressed):
source = self.sender()
if self.LedOn:
source.setText('Off')
source.LedOn = 0
self.serial.write('L')
else:
source.setText('On')
source.LedOn = 1
self.serial.write('H')
Problem: Now if we want to control multiple LEDs and remember their individual toggle state, what is the best practice?
I also cant seem to pass an additional value to toggleLED()
with btn.clicked.connect(self.toggleLED(btnNumber))
class Screen(QWidget):
def initUI(self):
btn1 = QPushButton('Off', self)
btn1.setCheckable(True)
btn1.LedOn= 0
btn1.clicked.connect(selftoggleLED(1))
btn2 = QPushButton('Off', self)
btn2.setCheckable(True)
btn2.LedOn= 0
btn2.clicked.connect(selftoggleLED(2))
def toggleLED(self, pressed, value):
source = self.sender()
if self.LedOn:
source.setText('Off')
self.serial.write(value)
self.serial.write('L')
else:
source.setText('On')
self.serial.write(value)
self.serial.write('H')
You can use partial
for that:
from functools import partial
btn1.clicked.connect(partial(self.toggleLED, 1))
This allows you to pass multiple arguments to a function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With