Search code examples
pythonlistvariablestkintertkinter-entry

How to use list items as variables?


I need to use variables called 'apple' 'banana' and 'orange' in Tkinter.

In my real script, they're called differently and I have a lot more, which would make it a lot of work to manually type:

apple.delete(0, END)    
banana.delete(0, END)

etc.

I wanted to use a list

lst = ['apple', 'banana', 'orange']

so that I could use:

for i in lst:
    i.delete(0, END)

But this gives me the error:

AttributeError: 'str' object has no attribute 'delete'

How could I use those list items as variables in an operation?


Solution

  • You can save the widgets to a list. They are python objects, so you can use them like any other object.

    apple = tk.Text(...)
    banana = tk.Text(...)
    orange = tk.Text(...)
    ...
    lst = [apple, banana, orange, ...]
    ...
    for widget in lst:
        widget.delete(0, "end")