将 if 语句更改为 Python 中的 switch 条件语句 3
Change if sentences to a switch conditional in Python 3
我正在使用 PyQT6。我正在尝试从更改标签的复选框中获取文本,例如 "You have selected: " + value
。所以问题是,如何将这些 if 条件转换为 switch case?
这里是if条件的方法
def item_selected(self):
value = ""
if self.check1.isChecked():
value = self.check1.text()
if self.check2.isChecked():
value = self.check2.text()
if self.check3.isChecked():
value = self.check3.text()
if self.check4.isChecked():
value = self.check4.text()
self.label.setText("You have selected: " + value)
如何用switch case实现这段代码?
我试过这个:
def item_selected(self):
value = ""
match value:
case bool(self.check1.isChecked()):
value = (self.check1.text())
case bool(self.check2.isChecked()):
value = (self.check2.text())
case bool(self.check3.isChecked()):
value = (self.check3.text())
case bool(self.check4.isChecked()):
value = (self.check4.text())
self.label.setText("You have selected: " + value)
但是当我选中复选框时我没有得到值
我看不出如何将此表达式转换为 switch-conditional,因为它基于变量的状态。另外,如果你想减少表达式,那么你可以使用 for-loop:
value = ""
for checkbox in (self.check4, self.check3, self.check2, self.check1):
if checkbox.isChecked():
value = checkbox.text()
break
self.label.setText(f"You have selected: {value}")
我正在使用 PyQT6。我正在尝试从更改标签的复选框中获取文本,例如 "You have selected: " + value
。所以问题是,如何将这些 if 条件转换为 switch case?
这里是if条件的方法
def item_selected(self):
value = ""
if self.check1.isChecked():
value = self.check1.text()
if self.check2.isChecked():
value = self.check2.text()
if self.check3.isChecked():
value = self.check3.text()
if self.check4.isChecked():
value = self.check4.text()
self.label.setText("You have selected: " + value)
如何用switch case实现这段代码? 我试过这个:
def item_selected(self):
value = ""
match value:
case bool(self.check1.isChecked()):
value = (self.check1.text())
case bool(self.check2.isChecked()):
value = (self.check2.text())
case bool(self.check3.isChecked()):
value = (self.check3.text())
case bool(self.check4.isChecked()):
value = (self.check4.text())
self.label.setText("You have selected: " + value)
但是当我选中复选框时我没有得到值
我看不出如何将此表达式转换为 switch-conditional,因为它基于变量的状态。另外,如果你想减少表达式,那么你可以使用 for-loop:
value = ""
for checkbox in (self.check4, self.check3, self.check2, self.check1):
if checkbox.isChecked():
value = checkbox.text()
break
self.label.setText(f"You have selected: {value}")