I have a class in which I find myself define similar groups of variables many times, to the point that I believe it would be clearer if I were able to do so in a loop, as follows:
import tkinter as tk
from tkinter import ttk
class MyClass:
def __init__(self):
self.initializeVariables()
def initializeVariables(self):
varnames = ['a', 'b', 'c', 'd']
for var in varnames:
exec("self.bg{0} = ttk.Frame(self.Frame)".format(var))
exec("self.tb{0} = ttk.Entry(bg{0}, width=4)".format(var))
exec("self.tb{0}.grid(row=i)".format(var))
I have more elements than this, this example is just meant to be illustrative. I would like to know:
- Is there a way to accomplish this without using the
execfunction? I tried withglobals(), but was not successful - Is doing this inadvisable? In my opinion, this makes the code easier to read, but I am not aware of typical conventions in this arena.
setattr(self, 'tb' + var, ttk.Entry(self.Frame, width=4)