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

Time:01-04

I would like to use this command to set my custom variable, how to do this:

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

I want my custom variable to be part of the .configure dictionary

sample code:

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

CodePudding user response:

Tkinter doesn't have a way to add an option that works exactly like the built-in options. However, you can override configure and cget to handle both your custom options and the default options.

Here's an example of one way to do it, though it's not the only way.

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)

This lets you use either cget or directly access the class attribute:

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}")

And within the class, you can do likewise:

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