Pergunta

The following code shows my two option menus and the callback function 'VarMenu'. This all works all well and good except as I created several of the same option menus in the loop for each row. When only one of them is changed to 'L', I want only that corresponding row for the unit option menu to be changed to 'N' and not the every single one of them.

I don't want to confuse things too much with lists or huge lines of code but if I created a list self.type = [] would that work?

Thank you in advance!

def VarMenu(self, selection):

    if selection == "L":
        self.variableunit.set("N")
        self.unit.config(state=DISABLED)
    else:
        self.variableunit.set("mm")
        self.unit.config(state=NORMAL)

def import_file(self): # Not complete code
    for row_number, row_data in enumerate(info):
        self.variable = StringVar(self.frame_table)                                
        self.variable.set(pre(code))
        self.type = OptionMenu(self.frame_table, self.variable, "None", "Clear", "F", "L", command=self.VarMenu)
        self.type.grid(row=row_number+i, column=3, sticky="nsew", padx=1, pady=1)

    # Unit drop down menu
        self.unit = OptionMenu(self.frame_table, self.variableunit, "mm", "N")
        self.unit.grid(row=row_number+i, column=5, sticky="nsew", padx=1, pady=1)
Foi útil?

Solução

When you do this:

for row_number, row_data in enumerate(info):
    self.variable = StringVar(...)

... do you realize that you keep overwriting self.variable with the most recently created one? How do you expect it to somehow magically hold more than one variable?

Instead, you simply need to pass the variable to the callback using lambda or functools.partial. For example:

for row_number, row_data in enumerate(info):
    var = StringVar(...)
    self.type = OptionMenu(..., command=lambda new_value, variable=var: self.VarMenu(new_value, variable)

Of course, you can pass in the row number or any other information you want in your callbacks.

Note: the OptionMenu is designed such that when it calls your callback, it will always pass one argument that is the new value selected by the user. This argument will always be present. You can, however, add additional arguments as shown in my example.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top