This is a follow-up question to How do you programmatically set an attribute?.
I see how I can set an attribute value using setattr(x, attr, value).
How might I invoke a method on attr?
For one example, I want to create and set the value of Tkinter Entry objects corresponding to a dictionary wherein the keys are attributes and the values are values to be assigned to the attributes.
My brute force approach works:
from tkinter import Tk, Button, filedialog, Label, Frame, BOTH, Entry, END, StringVar
class Example(Frame):
def __init__(self, master=None):
"""Initialize UI and set default values."""
# https://stackoverflow.com/questions/285061/how-do-you-programmatically-set-an-attribute.
Frame.__init__(self, master)
self.master = master
myDict = {'a': 'String A', 'b': 'String B', 'c': 'String C'}
self.a = StringVar()
self.a.set(myDict['a'])
self.aEntry = Entry(self, textvariable=self.a)
self.aEntry.grid(row=0, column=1)
self.b = StringVar()
self.b.set(myDict['b'])
self.bEntry = Entry(self, textvariable=self.b)
self.bEntry.grid(row=1, column=1)
self.c = StringVar()
self.c.set(myDict['c'])
self.cEntry = Entry(self, textvariable=self.c)
self.cEntry.grid(row=2, column=1)
self.pack(fill=BOTH, expand=1)
root = Tk()
app = Example(root)
root.mainloop()
A loop approach would look something like this:
from tkinter import Tk, Button, filedialog, Label, Frame, BOTH, Entry, END, StringVar
class Example(Frame):
def __init__(self, master=None):
"""Initialize UI and set default values."""
# https://stackoverflow.com/questions/285061/how-do-you-programmatically-set-an-attribute.
Frame.__init__(self, master)
self.master = master
myDict = {'a': 'String A', 'b': 'String B', 'c': 'String C'}
rowCount = 0
for key, value in myDict.items():
setattr(self, key, StringVar()) # Works
# self.a.set('String A')
self.key.set(value) # Does not work
# self.aEntry = Entry(self, textvariable=self.a)
setattr(self, key + 'Entry', Entry(self, textvariable=???)) # Does not work
# self.aEntry.grid(row=0, column=1)
self.key + 'Entry'.grid(row=rowCount, column=1) # Does not work
rowCount += 1
self.pack(fill=BOTH, expand=1)
root = Tk()
app = Example(root)
root.mainloop()
How might I rewrite the lines labelled "# Does not work" so the loop works?
This isn't just a Tkinter question. I can think of other cases where one might want to invoke a method on an attribute, the name of which is assigned to a string variable. I would appreciate coaching.