动态更新gtk.VBox

3 投票
1 回答
4147 浏览
提问于 2025-04-16 11:34

我经常使用这个网站来解决我在用Python编程时遇到的小问题。这次,我找不到适合我情况的解决办法。所以,我的问题是:

我想动态地往一个gtk.VBox控件里添加内容。问题是,它的工作方式并不是我想要的。我有一个按钮,点击这个按钮的动作是往VBox里添加一个新的控件。可惜的是,这个控件在窗口上并没有显示出来。我想,我可能需要调用一个类似于重绘的函数,但我没有找到这样的东西。下面是一个示例代码,展示了我的问题:

import gtk

class DynamicVbox:

    def __init__(self):
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.connect("destroy", self.close_application)
        self.window.set_size_request(400,320)
        #a hBox to put the button and the dynamic vBox
        hBox = gtk.HBox(False, 0)

        addButton = gtk.Button("add checkbox")
        addButton.connect("clicked", self.AddCheckButton)

        self.vBox = gtk.VBox(False, 0)
        self.vBox.pack_start(gtk.CheckButton("CheckButton"), True, True, 1)
        hBox.pack_start(self.vBox, True, True, 5)
        hBox.pack_end(addButton, False, False, 5)
        self.window.add(hBox)

        #start gtk
        self.window.show_all()
        gtk.main()

    def AddCheckButton(self, button):
        self.vBox.pack_start(gtk.CheckButton("CheckButton"), True, True, 1)
        print "adding checkbox..."

    def close_application(self, widget):
        gtk.main_quit()

 # run it

a = DynamicVbox()

我非常感谢任何帮助。提前谢谢你们。

1 个回答

6

新的检查按钮已经存在,但在你调用 show() 之前,它是看不见的:

def AddCheckButton(self, button):
    button = gtk.CheckButton("CheckButton")
    self.vBox.pack_start(button, True, True, 1)
    button.show()
    print "adding checkbox..."

撰写回答