3

My main target is to add something like an hidden tag or string to a widget, to save short information on it. I got the idea of creating a new custom Button class (in this case I need buttons), which inherits all the old options.

This 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 trouble when 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)

The problems come out when I try to get the value of tag:

aria1["tag"]

it returns:

_tkinter.TclError: unknown option "-tag"

How can I solve this?

Wolf
  • 9,679
  • 7
  • 62
  • 108
Matteo Secco
  • 613
  • 4
  • 10
  • 19
  • While subclassing can be used to add custom attributes to `Tk` widgets, it's not necessary to explicitly assign the `master` attribute to `self`. It's already done by`Button.__init__(self, master, *args, **kwargs)`. – Wolf May 12 '21 at 08:51

1 Answers1

3

You need to access your custom options as object attributes:

print(aria1.tag)
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685