0

I am trying to create a program containing various drop down menus and writable fields. To simplify adding new menus and writable fields i wanted to loop over a list of tuples containing the information required to create dynamic variable names and the menus.

The problem i am running into is when running the below code where 'name' is the string "Percentage". It should be noted that the code works if i remove 'validate' and 'validatecommand', though obviously the validation isn't done.

def number_validate(char):
    return char.isdigit()
self.percentage_validification = self.root.register(number_validate)

exec("self." + name + "_box" + " = " + "tkinter.Entry(self.root, validate = 'key', self.validatecommand = (self.validation, '%S'))")

The above code gives the following error:

SyntaxError: expression cannot contain assignment, perhaps you meant "=="?

The following code gives the correct output but does not allow dynamic variable naming and creation, which indicates that it is not a problem with the command itself:

self.Percentage_box = tkinter.Entry(self.root, validate = "key", validatecommand = (self.percentage_validification, '%S'))

I assume my problem relates to improper handling of strings in the exec function, but i simply can't figure out how is should be done. Does anyone have an answer.

MikkelDA
  • 37
  • 3
  • 2
    Don't use exec. See [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – Bryan Oakley Jun 25 '22 at 18:36
  • Thanks. I found the issue, but still converted it to dictionaries as you suggested since it seems much easier to use. – MikkelDA Jun 25 '22 at 19:54

0 Answers0