首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在GTK3 (PyGObject)中动态更新widget?

如何在GTK3 (PyGObject)中动态更新widget?
EN

Stack Overflow用户
提问于 2021-09-16 15:05:34
回答 1查看 45关注 0票数 1

在本例中,我尝试在每次按下按钮时添加另一个按钮(或任何小部件)。

代码语言:javascript
复制
from gi.repository import Gtk


class ButtonWindow(Gtk.Window):
    def __init__(self):
        super().__init__(title="Button Demo")
        self.hbox = Gtk.HBox()
        self.add(self.hbox)
        button = Gtk.Button.new_with_label("Click Me")
        button.connect("clicked", self.on_clicked)
        self.hbox.pack_start(button, False, True, 0)

    def on_clicked(self, button):
        print("This prints...")
        button = Gtk.Button.new_with_label("Another button")
        self.hbox.pack_start(button, False, True, 0)  # ... but the new button doesn't appear


win = ButtonWindow()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()

我已经尝试过queue_draw()和其他黑客技术,但到目前为止都没有起作用。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-16 21:28:03

调用show_all()方法可以更新小部件的子项。以下是使用了show_all()的代码,并相应地标记了添加的行:

代码语言:javascript
复制
from gi.repository import Gtk


class ButtonWindow(Gtk.Window):
    def __init__(self):
        super().__init__(title="Button Demo")
        self.hbox = Gtk.HBox()
        self.add(self.hbox)
        button = Gtk.Button.new_with_label("Click Me")
        button.connect("clicked", self.on_clicked)
        self.hbox.pack_start(button, False, True, 0)

    def on_clicked(self, button):
        print("This prints...")
        button = Gtk.Button.new_with_label("Another button")
        self.hbox.pack_start(button, False, True, 0)
        self.hbox.show_all() ### ADDED LINE


win = ButtonWindow()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()

因此,调用self.hbox.show_all()将显示self.hbox的所有子对象。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69210896

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档