Question

I use Python 3+PyGObjects+Gtk.Builder I have some window, what I create from glade:

builder = Gtk.Builder()
builder.add_from_file("main.ui")

I create some widgets and add them(i see it in window):

switch = Gtk.Switch()
switch.set_name('test')

hBox = Gtk.HBox()
hBox.pack_start(switch, True, True, 10)

window = builder.get_object("MainWindow")
window.add(hBox)

At another part of program I do not have access to "switch", but have to "builder". I try:

switch = builder.get_object('test')
switch_active = switch.get_active()

But receive error:

AttributeError: 'NoneType' object has no attribute 'get_active'

How I can get it from "builder"?

Was it helpful?

Solution

You can't. Builder can only give you objects defined in the ui file.

You should modify your program so that you do have access to switch in the part that needs to get the active value.

OTHER TIPS

Another option is to name your container in ui file, retrieve the container in code using get_object and set your new widget as its child. Then, retrieve later the container and ask for its child.

Yet another option: if you require to modify one attribute of a widget at runtime (quite common, for example, for combo boxes and treeviews), instead of creating it in code and append it later, you better retrieve it from the ui a changed it. You can particularly changed the visibility attribute, so it can be shown depending of context.

In conclusion is very uncommon to have to create widgets in code when using GtkBuilder. Even for contributed widgets you can create a catalog. You can also have many GtkBuilders if you don't want to load all yours screens at once.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top