python - 如何对以编程方式设置的属性调用方法?

标签 python tkinter iterable setattr

这是 How do you programmatically set an attribute? 的后续问题.

我了解了如何使用 setattr(x, attr, value) 设置属性值。

我如何调用 attr 上的方法?

举个例子,我想创建并设置与字典相对应的 Tkinter Entry 对象的值,其中键是属性,值是要分配给属性的值。

我的蛮力方法有效:

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()

循环方法看起来像这样:

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()

如何重写标有“# 不起作用”的行以使循环起作用?

这不仅仅是一个 Tkinter 问题。我可以想到其他情况,人们可能想要调用属性上的方法,该方法的名称被分配给字符串变量。我将不胜感激指导。

最佳答案

我不会为此使用单独的属性;我将使用关联的 EntryStringVar 对象对的 dict

getattrsetattr各有其用处,但不能取代dict的合理使用。

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.entries = {}

        for rowCount, (key, value) in enumerate(myDict.items()):
            sv = StringVar()
            sv.set(value)

            e = Entry(self, textvariable=sv)
            e.grid(row=rowCount, column=1)

            self.entries[key] = (e, sv)

        self.pack(fill=BOTH, expand=1)

关于python - 如何对以编程方式设置的属性调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49518479/

相关文章:

java - 如何创建只接受实现 Iterable 的元素的方法

python - tensorflow :random_crop 中的类型错误

python - 在路径中包含 Python 库?

python - 在 networkx 中着色步行边缘

python - 无法导入 tkinter(或 Tkinter)

c++ - 检查变量类型是否可迭代?

python - 如何在 pyjade 中包含内联内容

python - 使用 dill 库时出现 TypeError : can't pickle _tkinter. tkapp 对象

PYTHON:使用条目/按钮 tkinter 错误发送电子邮件

python - 需要 : simple way to force json to decode to "normal" iterable python lists