如何在GTK3中重新绘制(刷新、更新、替换)容器?

问题描述 投票:0回答:1

我需要在收到一些信号后更新一些 GTK 容器。

假设我们有一个GTK_BOX。里面有 GTK_BUTTONGTK_LABEL。点击GTK_BUTTON后,之前的内容应该被删除,并且新的GTK_BUTTON应该插入到同一个GTK_BOX中。

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()

问题是:新对象button4没有添加到self.box,可能是因为这个盒子已经添加到另一个容器(示例中的self

所以我需要的是:

可以向已初始化并显示的 gtk 容器添加新内容。

谢谢你。

gtk gtk3 pygtk
1个回答
0
投票

有点晚了,但这是一种方法:

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):
        # Remove the previous container from the window. This will
        # also remove the "old" button.
        self.remove(self.box)

        # Create the new button and a new box and add the button to
        # this new box. Add this new box to the window.
        button2 = Gtk.Button("_NEW_")
        self.box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        self.box.add(button2)
        self.add(self.box)

        # Show everything.
        self.show_all()
     
if __name__ == "__main__":
    window = MyWindow()
    Gtk.main()

如您所见,诀窍是更改整个容器。

© www.soinside.com 2019 - 2024. All rights reserved.