【问题标题】:How to use dictionary instead of if statement in python?如何在python中使用字典而不是if语句?
【发布时间】:2018-04-17 14:43:15
【问题描述】:

我有一个函数,当你在 python 中使用 PyQt4 单击按钮后会弹出一个消息框。我使用 'sender()' 来确定单击了哪个按钮,然后相应地设置弹出窗口的文本。此功能与“if 语句”完美配合。但是我想知道如何使用字典编写具有相同功能的函数(因为 python 中没有 switch 语句并且我的代码中有太多的 if 语句)?

def pop_up(self):
    msg = QtGui.QMessageBox()
    msg.setIcon(QtGui.QMessageBox.Information)
    sender = self.MainWindow.sender()

    if sender is self.button1:
        msg.setText("show message 1")
    elif sender is self.button2:
        msg.setText("show message 2")
    elif sender is self.button3:
        msg.setText("show message 3")
    elif sender is self.button4:
        msg.setText("show message 4")
    elif sender is self.button5:
        msg.setText("show message 5")
    elif sender is self.button6:
        msg.setText("show message 6")
    .
    .
    .
    .
    .
    elif sender is self.button36:
        msg.setText("show message 36")


    msg.exec()

【问题讨论】:

标签: python dictionary if-statement switch-statement pyqt4


【解决方案1】:

你的字典看起来像

button_dict = {
    self.button1: "Message 1",
    self.button2: "Message 2",
    self.button36: "Message 36",
}

然后您可以像访问任何字典一样访问值

def pop_up(self):
    msg = QtGui.QMessageBox()
    msg.setIcon(QtGui.QMessageBox.Information)
    sender = self.MainWindow.sender()
    message_text = button_dict[sender]
    msg.setText(message_text)
    msg.exec()

【讨论】:

    猜你喜欢
    • 2016-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-23
    • 2011-11-02
    • 2021-11-15
    • 2015-10-24
    • 1970-01-01
    相关资源
    最近更新 更多