Question

Is there a way to store custom information with a widget?

For instance, say I have a list with 20 urls.

I create 20 buttons, one for each url.

I want to make it so when I click a button, a url opens. But i need a way to know which button is linked to which url, so when the button is clciked, i can pass the url to the event-handler function to open it.

Another solution I thought of to accomplish this, was to create a custom class that extends the Gtk.Button class, like so

class MyButton(Gtk.Button)
    def __init__(self, url):
        Gtk.Button.__init__(self)
        self.url = url
        ...

Then I could simply do button = MyButton(url)

But this seems like overkill. So I am wondering if i could store custom information on a widget itself.

Was it helpful?

Solution

The simplest solution is to add the URL as additional data passed to the clicked signal handler:

# handle_click will receive additional url arg along with the button
button.connect('clicked', handle_click, url)

In PyGTK you can also add any attribute to a widget by just assigning to it, even without subclassing:

# handle_click will be called with button and can access button.url
button.url = url
button.connect('clicked', handle_click)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top