Tkinter:在自定义小部件中,如何通过 .configure 设置自定义变量的值?

Tkinter: In a custom widget, how do I set the value of a custom variable through .configure?

我想使用这个命令来设置我的自定义变量,如何操作:

self.ent1.configure(my_custom_var='teste')

我希望我的自定义变量成为 .configure 字典的一部分

示例代码:

from tkinter import *

class My_Entry(Entry):
    def __init__(self, parent, my_custom_var='', *args, **kwargs):

        super().__init__(parent, *args, **kwargs)


        #print('my_custom value: ', my_custom_var)
        print(self['my_custom_var'])

        return


    def configure(self, **kwargs):
        super().configure(**kwargs)
        print(kwargs) #<--- my custom var here in kwargs

#--------------


class Mainframe(Tk):
    def __init__(self):
        Tk.__init__(self)

        #self.ent1 = My_Entry(self, my_custom_var='teste')
        self.ent1 = My_Entry(self)
        self.ent1.configure(show='*')
        #self.ent1.configure(show='*', my_custom_var='teste')
        self.ent1.pack()
        return


if __name__== '__main__':
    app = Mainframe()
    app.mainloop()

Tkinter 无法添加与内置选项完全相同的选项。但是,您可以覆盖 configurecget 来处理您的自定义选项和默认选项。

这是一种方法的示例,但这不是唯一的方法。

class My_Entry(tk.Entry):
    # tuple of supported custom option names
    custom_options = ("my_custom_var",)

    def __init__(self, parent, *args, my_custom_var='', **kwargs):
        super().__init__(parent)
        self.configure(my_custom_var=my_custom_var, **kwargs)

    def configure(self, **kwargs):
        for key in self.custom_options:
            if key in kwargs:
                setattr(self, key, kwargs.pop(key))
        if kwargs:
            super().configure(**kwargs)

    def cget(self, key):
        if key in self.custom_options:
            return getattr(self, key)
        else:
            return super().cget(key)

这让您可以使用 cget 或直接访问 class 属性:

entry = My_Entry(root, width=40, my_custom_var="Hello, world")
print(f"custom var via cget: {entry.cget('my_custom_var')}")
print(f"custom var via attribute: {entry.my_custom_var}")

在 class 内,您也可以这样做:

print(f"custom var via cget: {self.cget('my_custom_var')}")
print(f"custom var via attribute: {self.my_custom_var}")