Skip to content

Gtk.Builder().get_object(id)??? #205

@margual56

Description

@margual56

I'm not sure if this question belongs in this repo...

I just want to be able to get an object from the window in python 😭

Prelude

So, as the title says, you can use the Builder object to get an object by its unique ID. Here's the thing tho, in order to do that you need a previously existing Builder object to which all the widgets are added.
If you execute print(Gtk.Builder().get_object('some_ID_that_exists')) it outputs [] (an empty array), because with Builder() you are creating a new empty object without widgets.

Example

If you create a GTK-Builder project with Python, you might notice that there is no "Builder" object anywhere, the widgets are added from the template (the 'window.ui' file) directly. I leave here a link to my project in case you don't believe me, but trust me: there is none.
The objects Gtk.ApplicationWindow and Gtk.Application do not have a builder attribute as some sources suggest

Confusion

Some sources redirect to the pygobject documentation, but the page does not exist.

What I'm getting at

is that there is no PyGTK resource that actually gives the correct solution!!
The correct solution is to create a variable with the same name as the ID of the object and call Gtk.Template.Child() and magically, it gives you the correct object.
Example (if the ID is 'ok_button'):

ok_button = Gtk.Template.Child()

It's that easy!

PS

I've been searching this question for more than 5h now 😅 we all know this is one of those things I could have missed but... If so, it needs more visibility.

This is where I found the solution: https://stackoverflow.com/questions/56010352/i-need-example-code-for-a-simple-python-gui-script-with-gtk. A simple answer like that, which only has 1 extra line of code, was enough to understand.

References

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions