Python - Create a box in GTK+ 3

Python - Create a box in GTK+ 3

In GTK+ 3, a popular GUI toolkit used with Python, a box is a container widget that can arrange its child widgets in a vertical or horizontal line. The Gtk.Box widget is versatile and can be used to create complex user interfaces.

To create a box in GTK+ 3 using Python, you need to have PyGObject installed, which provides bindings for GTK+ 3. Here's a basic example of how to create a vertical and horizontal box and add some buttons to them:

Step 1: Install PyGObject

First, make sure you have PyGObject installed. You can install it using pip:

pip install PyGObject 

Step 2: Create a Box in GTK+

Here's a simple script to create a GTK window with a horizontal and a vertical box:

import gi gi.require_version("Gtk", "3.0") from gi.repository import Gtk class MyWindow(Gtk.Window): def __init__(self): super().__init__(title="GTK Box Example") # Create a vertical box with 10 pixels spacing vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10) self.add(vbox) # Create a horizontal box hbox = Gtk.Box(spacing=10) vbox.pack_start(hbox, True, True, 0) # Create and add buttons to the horizontal box button1 = Gtk.Button(label="Button 1") button2 = Gtk.Button(label="Button 2") hbox.pack_start(button1, True, True, 0) hbox.pack_start(button2, True, True, 0) # Create and add another button to the vertical box button3 = Gtk.Button(label="Button 3") vbox.pack_start(button3, True, True, 0) win = MyWindow() win.connect("destroy", Gtk.main_quit) win.show_all() Gtk.main() 

In this script:

  • A MyWindow class is created, inheriting from Gtk.Window.
  • A vertical box (Gtk.Box with Gtk.Orientation.VERTICAL) is created and added to the window.
  • A horizontal box is created (default orientation is horizontal) and added to the vertical box.
  • Buttons are created and added to both the horizontal and vertical boxes using the pack_start() method.
  • The show_all() method displays the window and its child widgets.

When you run this script, it will display a window with two buttons aligned horizontally and one button aligned vertically below them.

Customizing the Box

  • The spacing parameter in the Gtk.Box constructor sets the number of pixels to place between children.
  • pack_start(child, expand, fill, padding) adds the child widget to the box. expand and fill parameters determine whether the child expands or fills the space allocated, and padding adds padding around the child.
  • You can also use Gtk.Box to create more complex layouts by nesting boxes or combining them with other container widgets.

More Tags

least-squares yuv sql-server aac google-query-language roi google-sheets apache-spark-ml uiscrollview realm

More Programming Guides

Other Guides

More Programming Examples