无法在GTK中垂直排列按钮

2 投票
1 回答
1843 浏览
提问于 2025-04-17 15:23

我想把这两个按钮垂直放在框里,为什么不行呢?这是我的代码。

from gi.repository import Gtk
class MyWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="Hello World")
        self.box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        self.box = Gtk.Box(spacing=6)
        self.add(self.box)
        self.button1 = Gtk.Button(label="Hello")
        self.box.pack_start(self.button1, True, True, 0)
        self.button2 = Gtk.Button(label="Goodbye")
        self.box.pack_start(self.button2, True, True, 0)


win = MyWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()

1 个回答

7

你创建了一个叫 self.box 的盒子,这个盒子是竖着放的。然后你立刻用另一个完全不同的新盒子把它覆盖掉了,这个新盒子的间距是6,而且默认是横着放的。其实你应该这样做:

self.box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)

撰写回答