Gtk 忽略小部件的宽度和高度参数

Gtk ignores width and height parameter of widgets

我正在尝试使用网格在 GTK 中编写一个计算器,但它忽略了按钮的宽度和高度参数。 以下是代码的简短版本:

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

class CalculatorWindow(Gtk.Window):

   def __init__(self):
       Gtk.Window.__init__(self, title='Calculator')
       self.set_border_width(10)

       grid = Gtk.Grid()
       self.add(grid)

       button1 = Gtk.Button.new_with_mnemonic('_1')
       button1.connect('clicked', self.on_1_clicked)
       grid.attach(button1, 0, 3, 1, 2)

       button2 = Gtk.Button.new_with_mnemonic('_2')
       button2.connect('clicked', self.on_2_clicked)
       grid.attach_next_to(button2, button1, Gtk.PositionType.RIGHT, 2, 2)

       button3 = Gtk.Button.new_with_mnemonic('_3')
       button3.connect('clicked', self.on_3_clicked)
       grid.attach(button3, 0, 1, 1, 2)

       button4 = Gtk.Button.new_with_mnemonic('_4')
       button4.connect('clicked', self.on_4_clicked)
       grid.attach_next_to(button4, button3, Gtk.PositionType.RIGHT , 1, 2)



   def on_1_clicked(self, button1):
       print(1)

   def on_2_clicked(self, button2):
       print(2)

   def on_3_clicked(self, button3):
       print(3)

   def on_4_clicked(self, button4):
       print(4)


window = CalculatorWindow()
window.connect('destroy', Gtk.main_quit)
window.show_all()
Gtk.main()

无论我输入什么作为按钮的宽度参数,GTK 只会每行执行一个。如果我更改 button1 和 button2 的宽度,则只会调整 button1。即使它自己进行了调整,也无法正确执行。宽度调整始终保持不变,无论我输入 5 还是 20。

我直接从 GTK+ 3 Tutorial (6.2.1) 编写了一些类似的代码并且它有效。我错过了什么吗?

您需要较小的小部件来设置与跨越多个 columns/rows 的小部件的关系。否则他们将只采用最小尺寸。

也许这个例子很清楚:

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

class CalculatorWindow(Gtk.Window):

   def __init__(self):
       Gtk.Window.__init__(self, title='Calculator')
       self.set_border_width(10)

       grid = Gtk.Grid()
       self.add(grid)

       button1 = Gtk.Button.new_with_mnemonic('_1')
       grid.attach(button1, 0, 0, 1, 1)

       button2 = Gtk.Button.new_with_mnemonic('_2')
       grid.attach(button2, 1, 0, 1, 1)

       button3 = Gtk.Button.new_with_mnemonic('_3')
       grid.attach(button3, 0, 1, 2, 1)

       button4 = Gtk.Button.new_with_mnemonic('_4')
       grid.attach(button4, 2, 0, 1, 2)


window = CalculatorWindow()
window.connect('destroy', Gtk.main_quit)
window.show_all()
Gtk.main()