Python 3.x - using text string as variable name

后端 未结 3 692
难免孤独
难免孤独 2021-01-28 19:32

I\'m trying to avoid to multiply functions in code by using

def Return_Label(self,number)  

with a parameter.

Any Idea how to use st

3条回答
  •  礼貌的吻别
    2021-01-28 20:31

    Dynamicly computing variable names should be avoided at all costs. They are difficult to do correctly, and it makes your code hard to understand, hard to maintain, and hard to debug.

    Instead, store the widgets in a dictionary or list. For example:

    def __init___(self):
        ...
        self.vars = {}
        ...
        self.vars[1] = StringVar()
        self.vars[2] = StringVar()
        ...
    
    def Return_Label(self,number):
        self.entry_field_value = self.entry.get()
        var = self.vars[number]
        var.set(self.entry_field_value)
    

    Though, you really don't need to use StringVar at all -- they usually just add extra overhead without providing any extra value. You can save the labels instead of the variables, and call configure on the labels

    self.labels[1] = Label(...)
    ...
    self.labels[number].configure(text=self.entry_field_value)
    

提交回复
热议问题