How to re-draw (refresh, update, replace) container in GTK3?

61 Views Asked by At

I need update some GTK container after some signal.

Let's imagine we have a Gtk.Box. Inside we have a Gtk.Button and a Gtk.Label. After clicking on the Gtk.Button, the previous content should be deleted, and a new Gtk.Button should be inserted in the same Gtk.Box.

Code example on Python:

import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk

class MyWindow(Gtk.Window):
    def __init__(self):
        super().__init__()
        self.set_default_size(200, 200)
        self.box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        button1 = Gtk.Button("_OLD_")
        button1.connect("clicked", self.on_button_click)
        self.box.add(button1)
        self.add(self.box)
        self.show_all()

    def on_button_click(self, button):
        for child in self.box.get_children():
            child.destroy()
        button2 = Gtk.Button("_NEW_")
        self.box.add(button2)
     
if __name__ == "__main__":
    window = MyWindow()
    Gtk.main()

The problem is: new object button2 doesn't add to self.box. May be because of this box was already added to another container (self in example)?

So what I need: The possibility to replace content in a GTK container, which already was initialized and displayed.

1

There are 1 best solutions below

0
BobMorane On

A bit late, but here is one way to do it:

import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk

class MyWindow(Gtk.Window):
    def __init__(self):
        super().__init__()
        self.set_default_size(200, 200)
        self.box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        button1 = Gtk.Button("_OLD_")
        button1.connect("clicked", self.on_button_click)
        self.box.add(button1)
        self.add(self.box)
        self.show_all()

    def on_button_click(self, button):
        # The button that triggered the handler (i.e. button1) is
        # removed from the container.
        self.box.remove(button)

        # A new button is created and added to the container in its place.
        button1 = Gtk.Button("_NEW_")
        self.box.add(button1)

        # The window is re-shown
        self.show_all()
     
if __name__ == "__main__":
    window = MyWindow()
    Gtk.main()