Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add custom attributes to a Tk widget

Tags:

python

tkinter

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?

like image 228
Matteo Secco Avatar asked Aug 31 '25 02:08

Matteo Secco


1 Answers

You need to access your custom options as object attributes:

print(aria1.tag)
like image 105
Bryan Oakley Avatar answered Sep 02 '25 14:09

Bryan Oakley