Python – Add custom properties to the Tk widget

Add custom properties to the Tk widget… here is a solution to the problem.

Add custom properties to the Tk widget

My main goal is to add something like a hidden label or string to the widget to save short information on it.
I thought of creating a new custom Button class (in this case I need the button) that inherits all the old options.

Here is the code:

form tkinter import *

class NButton(Button):
    def __init__(self, master, tag=None, *args, **kwargs):
        Button.__init__(self, master, *args, **kwargs)
        self.master, self.tag = master, tag

No problem creating a new NButton instance:

aria1 = NButton(treewindow, bd=2, relief=GROOVE, text="Trasmissione\naerea 1", bg="#99c4ff", tag="aria 1")
aria1.place(x=20, y=20)

There was a problem when I tried to get the value of tag:

aria1["tag"]

It returns:

_tkinter. TclError: unknown option “-tag”

How do I fix this?

Solution

You need to access the custom option as an object property:

print(aria1.tag)

Related Problems and Solutions