I'm trying to write a calculator in GTK using a grid and it ignores the width and height parameter of the buttons. The following is a short version of the code:
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()
No matter what I enter as width parameter for the buttons, GTK only ever carries out one per row. If I change the widths of button1 and button2 only button1 gets adjusted. And even if it adjusts itself, it doesn't do it correctly. The width adjustment always remains the same, no matter if I enter 5 or 20.
I've coded something similar straight from the GTK+ 3 Tutorial (6.2.1) and it worked. Is there something I missed?
You need smaller widgets to set the relation to those which span multiple columns/rows. Otherwise they will just take their smallest size.
Maybe this example makes it clear:
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()