更新字典变量的原始引用

时间:2019-05-19 14:25:50

标签: python-3.x class

我有一个很大的程序,里面有很多文件,我将程序的设置保存在这样的类上。

class Options:
    BACKGROUND_COLOR = "(217, 217, 217)"
    INPUT_COLOR = "(255, 250, 200)"
    LABEL_COLOR = "(0, 0, 0)"

然后,我从其他文件导入该类,以读取/编辑选项,然后在新类上创建字典以操作多个选项。

然后我捕获特定字段上的事件,如果它们与我的字典中的事件匹配,那么它将进行一些更改。

from myfile import Options
class colorize:
    def __init__(self):
        """
        name = name of this color
        field = field which will define the new color
        current = current color before changing it
        """
        self.color_fields = [
            {"name": "Background", "field": self.Backgroundcolor, "current": Options.BACKGROUND_COLOR},
            {"name": "Input", "field": self.Inputcolor, "current": Options.INPUT_COLOR},
            {"name": "Label", "field": self.Labelcolor, "current": Options.LABEL_COLOR}
            ]

    def change_color(self, target):
        for field in self.color_fields:
            if target == field['field']:
                new_color = "my color"
                field['field'].setStyleSheet(f"background-color: rgb{new_color};")
                field['current'] = new_color  # Doesn't works, expected fix here
                break

我需要更新当前值。但是,class Options中的值没有改变,只是我的字典中的值。如何在没有很多if的情况下更改class Options中的值?因为现在我有几个选项,解决方法看起来像这样:

                if field['name'] == "Background":
                    Options.BACKGROUND_COLOR = new_color
                elif field['name'] == "Background_text":
                    Options.BACKGROUNDTEXT_COLOR = new_color
                elif field['name'] == "Input":
                    Options.INPUT_COLOR = new_color
                elif field['name'] == "Input_readonly_bg":
                    Options.INPUT_COLOR_READONLY = new_color
                elif field['name'] == "Input_text":
                    Options.INPUTTEXT_COLOR = new_color
                elif field['name'] == "Input_border":
                    Options.INPUTBORDER_COLOR = new_color
                elif field['name'] == "Button":
                    Options.BUTTON_COLOR = new_color
                elif field['name'] == "Button_text":
                    Options.BUTTONTEXT_COLOR = new_color
                elif field['name'] == "Dropdown":
                    Options.DROPDOWN_COLOR = new_color
                elif field['name'] == "Dropdown_text":
                    Options.DROPDOWNTEXT_COLOR = new_color
                # And 50 more ELIFs

我如何只用一行就可以做到这一点,就像我在注释(# Doesn't works, expected fix here)处删除所有那些硬编码的Elif一样?

0 个答案:

没有答案
相关问题