Widgets#

Gtk.ActionBar#

Gtk.ActionBar

Gtk.ActionBar#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.ActionBar"""

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()


class ExampleWindow(Gtk.ApplicationWindow):
    icons = ['call-start-symbolic', 'call-stop-symbolic',
             'contact-new-symbolic', 'address-book-new-symbolic']

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.set_title(title='Python and GTK: PyGObject Gtk.ActionBar')
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append(
            label='Preferences',
            detailed_action='app.preferences',
        )

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        vbox = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=0)
        vbox.set_margin_top(margin=12)
        vbox.set_margin_end(margin=12)
        vbox.set_margin_bottom(margin=12)
        vbox.set_margin_start(margin=12)
        self.set_child(child=vbox)

        actionbar = Gtk.ActionBar.new()
        actionbar.set_valign(Gtk.Align.END)
        actionbar.set_vexpand(expand=True)
        vbox.append(child=actionbar)

        for icon in self.icons:
            button = Gtk.Button.new_from_icon_name(icon_name=icon)
            button.connect('clicked', self.on_button_clicked)
            actionbar.pack_start(child=button)

    def on_button_clicked(self, button):
        print('Button pressed.')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.ActionBar."""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent


@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    @Gtk.Template.Callback()
    def on_button_clicked(self, button):
        print('Button pressed.')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject Gtk.ActionBar.</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar" id="header_bar">
        <child type="end">
          <object class="GtkMenuButton">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
    <child>
      <object class="GtkBox">
        <property name="orientation">1</property>
        <property name="margin-top">12</property>
        <property name="margin-end">12</property>
        <property name="margin-bottom">12</property>
        <property name="margin-start">12</property>
        <property name="spacing">12</property>
        <child>
          <object class="GtkActionBar">
            <property name="valign">2</property>
            <property name="vexpand">true</property>
            <child>
              <object class="GtkButton">
                <property name="icon-name">call-start-symbolic</property>
                <signal name="clicked" handler="on_button_clicked"/>
              </object>
            </child>
            <child>
              <object class="GtkButton">
                <property name="icon-name">call-stop-symbolic</property>
                <signal name="clicked" handler="on_button_clicked"/>
              </object>
            </child>
            <child>
              <object class="GtkButton">
                <property name="icon-name">contact-new-symbolic</property>
                <signal name="clicked" handler="on_button_clicked"/>
              </object>
            </child>
            <child>
              <object class="GtkButton">
                <property name="icon-name">address-book-new-symbolic</property>
                <signal name="clicked" handler="on_button_clicked"/>
              </object>
            </child>
          </object>
        </child>
      </object>
    </child>
  </template>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
    </section>
  </menu>
</interface>
using Gtk 4.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject Gtk.ActionBar.';
  default-width: 683;
  default-height: 384;
  
  [titlebar]
  Gtk.HeaderBar header_bar {
    [end]
    Gtk.MenuButton {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }

  Gtk.Box {
    orientation: vertical;
    margin-top: 12;
    margin-end: 12;
    margin-bottom: 12;
    margin-start: 12;
    spacing: 12;

    Gtk.ActionBar {
      valign: end;
      vexpand: true;

      Gtk.Button {
        icon-name: 'call-start-symbolic';
        clicked => $on_button_clicked();
      }

      Gtk.Button {
        icon-name: 'call-stop-symbolic';
        clicked => $on_button_clicked();
      }

      Gtk.Button {
        icon-name: 'contact-new-symbolic';
        clicked => $on_button_clicked();
      }

      Gtk.Button {
        icon-name: 'address-book-new-symbolic';
        clicked => $on_button_clicked();
      }
    }
  }
}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
  }
}

Gtk.Application#

Gtk.Application

Gtk.Application#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.Application"""



import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()


class ExampleWindow(Gtk.ApplicationWindow):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.set_title(title='Python and GTK: PyGObject Gtk.Application')
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append(
            label='Preferences',
            detailed_action='app.preferences',
        )

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        # Your code here:
        # ...


# This class can be placed in a separate file (e.g. main.py).
class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        # Menu actions.
        # `<primary>q` = `Ctrl + q`.
        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        """Callback for the `app.preferences` action of the interface file."""
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        """Callback is executed when the shortcut keys `Ctrl + q` are pressed."""
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        """Adds an action to the application.

        Args:
            name (str): Name of the action.
            callback (def): Function that will be called when the action is active.
            shortcuts (list[str]): List of shortcuts that trigger the action.
        """
        action = Gio.SimpleAction.new(name, None)
        action.connect('activate', callback)
        self.add_action(action)
        if shortcuts:
            self.set_accels_for_action(f'app.{name}', shortcuts)


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.Application."""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent


@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        # Your code here:
        # ...


# This class can be placed in a separate file (e.g. main.py).
class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        # Menu actions.
        # `<primary>q` = `Ctrl + q`.
        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        """Callback for the `app.preferences` action of the interface file."""
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        """Callback is executed when the shortcut keys `Ctrl + q` are pressed."""
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        """Adds an action to the application.

        Args:
            name (str): Name of the action.
            callback (def): Function that will be called when the action is active.
            shortcuts (list[str]): List of shortcuts that trigger the action.
        """
        action = Gio.SimpleAction.new(name, None)
        action.connect('activate', callback)
        self.add_action(action)
        if shortcuts:
            self.set_accels_for_action(f'app.{name}', shortcuts)


if __name__ == '__main__':
    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject Gtk.Application.</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar" id="header_bar">
        <child type="end">
          <object class="GtkMenuButton">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
  </template>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
    </section>
  </menu>
</interface>
using Gtk 4.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject Gtk.Application.';
  default-width: 683;
  default-height: 384;

  [titlebar]
  Gtk.HeaderBar header_bar {
    [end]
    Gtk.MenuButton {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }
}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
  }
}

Gtk.ApplicationWindow#

Gtk.ApplicationWindow

Gtk.ApplicationWindow#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.ApplicationWindow"""



import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()


class ExampleWindow(Gtk.ApplicationWindow):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.set_title(title='Python and GTK: PyGObject Gtk.Application')
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append(
            label='Preferences',
            detailed_action='app.preferences',
        )

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        # Your code here:
        # ...


# This class can be placed in a separate file (e.g. main.py).
class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        # Menu actions.
        # `<primary>q` = `Ctrl + q`.
        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        """Callback for the `app.preferences` action of the interface file."""
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        """Callback is executed when the shortcut keys `Ctrl + q` are pressed."""
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        """Adds an action to the application.

        Args:
            name (str): Name of the action.
            callback (def): Function that will be called when the action is active.
            shortcuts (list[str]): List of shortcuts that trigger the action.
        """
        action = Gio.SimpleAction.new(name, None)
        action.connect('activate', callback)
        self.add_action(action)
        if shortcuts:
            self.set_accels_for_action(f'app.{name}', shortcuts)


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.ApplicationWindow."""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent


@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        # Your code here:
        # ...


# This class can be placed in a separate file (e.g. main.py).
class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        # Menu actions.
        # `<primary>q` = `Ctrl + q`.
        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        """Callback for the `app.preferences` action of the interface file."""
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        """Callback is executed when the shortcut keys `Ctrl + q` are pressed."""
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        """Adds an action to the application.

        Args:
            name (str): Name of the action.
            callback (def): Function that will be called when the action is active.
            shortcuts (list[str]): List of shortcuts that trigger the action.
        """
        action = Gio.SimpleAction.new(name, None)
        action.connect('activate', callback)
        self.add_action(action)
        if shortcuts:
            self.set_accels_for_action(f'app.{name}', shortcuts)


if __name__ == '__main__':
    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject Gtk.ApplicationWindow.</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar" id="header_bar">
        <child type="end">
          <object class="GtkMenuButton">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
  </template>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
    </section>
  </menu>
</interface>
using Gtk 4.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject Gtk.ApplicationWindow.';
  default-width: 683;
  default-height: 384;

  [titlebar]
  Gtk.HeaderBar header_bar {
    [end]
    Gtk.MenuButton {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }
}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
  }
}

Gtk.Box (horizontal)#

Gtk.Box (horizontal)

Gtk.Box (horizontal)#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.Box() horizontal."""



import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()


class ExampleWindow(Gtk.ApplicationWindow):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.set_title(title='Python and GTK: PyGObject Gtk.Box() horizontal')
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append(
            label='Preferences',
            detailed_action='app.preferences',
        )

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        hbox = Gtk.Box.new(orientation=Gtk.Orientation.HORIZONTAL, spacing=12)
        hbox.set_homogeneous(homogeneous=True)
        hbox.set_margin_top(margin=12)
        hbox.set_margin_end(margin=12)
        hbox.set_margin_bottom(margin=12)
        hbox.set_margin_start(margin=12)
        self.set_child(child=hbox)

        for n in range(1, 4):
            button = Gtk.Button.new_with_label(label=f'Button {n}')
            button.connect('clicked', self.on_button_clicked)
            hbox.prepend(child=button)

        for n in range(1, 4):
            button = Gtk.Button.new_with_label(label=f'Button {n}')
            button.connect('clicked', self.on_button_clicked)
            hbox.append(child=button)

    def on_button_clicked(self, button):
        print('Button pressed.')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.Box() horizontal ui file."""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent


@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject Gtk.Box() horizontal ui file.</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar" id="header_bar">
        <child type="end">
          <object class="GtkMenuButton">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
    <child>
      <object class="GtkBox">
        <property name="orientation">0</property>
        <property name="homogeneous">true</property>
        <property name="margin-top">12</property>
        <property name="margin-end">12</property>
        <property name="margin-bottom">12</property>
        <property name="margin-start">12</property>
        <property name="spacing">12</property>
        <child>
          <object class="GtkButton">
            <property name="label">Button 03</property>
          </object>
        </child>
        <child>
          <object class="GtkButton">
            <property name="label">Button 02</property>
          </object>
        </child>
        <child>
          <object class="GtkButton">
            <property name="label">Button 01</property>
          </object>
        </child>
        <child>
          <object class="GtkButton">
            <property name="label">Button 01</property>
          </object>
        </child>
        <child>
          <object class="GtkButton">
            <property name="label">Button 02</property>
          </object>
        </child>
        <child>
          <object class="GtkButton">
            <property name="label">Button 03</property>
          </object>
        </child>
      </object>
    </child>
  </template>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
    </section>
  </menu>
</interface>
using Gtk 4.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject Gtk.Box() horizontal ui file.';
  default-width: 683;
  default-height: 384;

  [titlebar]
  Gtk.HeaderBar header_bar {
    [end]
    Gtk.MenuButton {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }

  Gtk.Box {
    orientation: horizontal;
    homogeneous: true;
    margin-top: 12;
    margin-end: 12;
    margin-bottom: 12;
    margin-start: 12;
    spacing: 12;

    Gtk.Button {
      label: 'Button 03';
    }

    Gtk.Button {
      label: 'Button 02';
    }

    Gtk.Button {
      label: 'Button 01';
    }

    Gtk.Button {
      label: 'Button 01';
    }

    Gtk.Button {
      label: 'Button 02';
    }

    Gtk.Button {
      label: 'Button 03';
    }
  }
}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
  }
}

Gtk.Box (vertical)#

Gtk.Box (vertical)

Gtk.Box (vertical)#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.Box() vertical."""



import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()


class ExampleWindow(Gtk.ApplicationWindow):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.set_title(title='Python and GTK: PyGObject Gtk.Box() vertical')
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append(
            label='Preferences',
            detailed_action='app.preferences',
        )

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        vbox = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=12)
        vbox.set_homogeneous(homogeneous=True)
        vbox.set_margin_top(margin=12)
        vbox.set_margin_end(margin=12)
        vbox.set_margin_bottom(margin=12)
        vbox.set_margin_start(margin=12)
        self.set_child(child=vbox)

        for n in range(1, 4):
            button = Gtk.Button.new_with_label(label=f'Button {n}')
            button.connect('clicked', self.on_button_clicked)
            vbox.prepend(child=button)

        for n in range(1, 4):
            button = Gtk.Button.new_with_label(label=f'Button {n}')
            button.connect('clicked', self.on_button_clicked)
            vbox.append(child=button)

    def on_button_clicked(self, button):
        print('Button pressed.')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.Box() vertical ui file."""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent


@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject Gtk.Box() vertical ui file.</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar" id="header_bar">
        <child type="end">
          <object class="GtkMenuButton">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
    <child>
      <object class="GtkBox">
        <property name="orientation">1</property>
        <property name="homogeneous">true</property>
        <property name="margin-top">12</property>
        <property name="margin-end">12</property>
        <property name="margin-bottom">12</property>
        <property name="margin-start">12</property>
        <property name="spacing">12</property>
        <child>
          <object class="GtkButton">
            <property name="label">Button 03</property>
          </object>
        </child>
        <child>
          <object class="GtkButton">
            <property name="label">Button 02</property>
          </object>
        </child>
        <child>
          <object class="GtkButton">
            <property name="label">Button 01</property>
          </object>
        </child>
        <child>
          <object class="GtkButton">
            <property name="label">Button 01</property>
          </object>
        </child>
        <child>
          <object class="GtkButton">
            <property name="label">Button 02</property>
          </object>
        </child>
        <child>
          <object class="GtkButton">
            <property name="label">Button 03</property>
          </object>
        </child>
      </object>
    </child>
  </template>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
    </section>
  </menu>
</interface>
using Gtk 4.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject Gtk.Box() vertical ui file.';
  default-width: 683;
  default-height: 384;

  [titlebar]
  Gtk.HeaderBar header_bar {
    [end]
    Gtk.MenuButton {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }

  Gtk.Box {
    orientation: vertical;
    homogeneous: true;
    margin-top: 12;
    margin-end: 12;
    margin-bottom: 12;
    margin-start: 12;
    spacing: 12;

    Gtk.Button {
      label: 'Button 03';
    }

    Gtk.Button {
      label: 'Button 02';
    }

    Gtk.Button {
      label: 'Button 01';
    }

    Gtk.Button {
      label: 'Button 01';
    }

    Gtk.Button {
      label: 'Button 02';
    }

    Gtk.Button {
      label: 'Button 03';
    }
  }
}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
  }
}

Gtk.Button#

Gtk.Button

Gtk.Button#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.Button"""



import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()


class ExampleWindow(Gtk.ApplicationWindow):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.set_title(title='Python and GTK: PyGObject Gtk.Button')
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append(
            label='Preferences',
            detailed_action='app.preferences',
        )

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        vbox = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=0)
        vbox.set_margin_top(margin=12)
        vbox.set_margin_end(margin=12)
        vbox.set_margin_bottom(margin=12)
        vbox.set_margin_start(margin=12)
        self.set_child(child=vbox)

        button = Gtk.Button.new_with_label(label='Click here')
        button.set_valign(Gtk.Align.CENTER)
        button.set_vexpand(expand=True)
        button.connect('clicked', self.on_button_clicked)
        vbox.append(child=button)

    def on_button_clicked(self, button):
        print('Button pressed.')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.Button."""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent


@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    @Gtk.Template.Callback()
    def on_button_clicked(self, button):
        print('Button pressed.')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':

    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject Gtk.Button</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar" id="header_bar">
        <child type="end">
          <object class="GtkMenuButton">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
    <child>
      <object class="GtkBox">
        <property name="orientation">1</property>
        <property name="margin-top">12</property>
        <property name="margin-end">12</property>
        <property name="margin-bottom">12</property>
        <property name="margin-start">12</property>
        <property name="spacing">12</property>
        <child>
          <object class="GtkButton">
            <property name="label">Click here</property>
            <property name="valign">3</property>
            <property name="vexpand">true</property>
            <signal name="clicked" handler="on_button_clicked"/>
          </object>
        </child>
      </object>
    </child>
  </template>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
    </section>
  </menu>
</interface>
using Gtk 4.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject Gtk.Button';
  default-width: 683;
  default-height: 384;

  [titlebar]
  Gtk.HeaderBar header_bar {
    [end]
    Gtk.MenuButton {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }

  Gtk.Box {
    orientation: vertical;
    margin-top: 12;
    margin-end: 12;
    margin-bottom: 12;
    margin-start: 12;
    spacing: 12;

    Gtk.Button {
      label: 'Click here';
      valign: center;
      vexpand: true;
      clicked => $on_button_clicked();
    }
  }
}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
  }
}

Gtk.Calendar#

Gtk.Calendar

Gtk.Calendar#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.Calendar"""



import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()


class ExampleWindow(Gtk.ApplicationWindow):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.set_title(title='Python and GTK: PyGObject Gtk.Calendar')
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append(
            label='Preferences',
            detailed_action='app.preferences',
        )

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        vbox = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=12)
        vbox.set_homogeneous(homogeneous=True)
        vbox.set_margin_top(margin=12)
        vbox.set_margin_end(margin=12)
        vbox.set_margin_bottom(margin=12)
        vbox.set_margin_start(margin=12)
        self.set_child(child=vbox)

        calendar = Gtk.Calendar.new()
        # calendar.connect('day-selected-double-click', self.day_double_click)
        calendar.connect('day-selected', self.on_day_selected)
        vbox.append(child=calendar)

    def on_day_selected(self, calendar):
        date = calendar.get_date()
        print(f'Dia: {date.get_day_of_month()}')
        print(f'Mês: {date.get_month()}')
        print(f'Ano: {date.get_year()}')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.Calendar."""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent


@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    @Gtk.Template.Callback()
    def on_day_selected(self, calendar):
        date = calendar.get_date()
        print(f'Dia: {date.get_day_of_month()}')
        print(f'Mês: {date.get_month()}')
        print(f'Ano: {date.get_year()}')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject Gtk.Calendar</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar" id="header_bar">
        <child type="end">
          <object class="GtkMenuButton">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
    <child>
      <object class="GtkBox">
        <property name="orientation">1</property>
        <property name="homogeneous">true</property>
        <property name="margin-top">12</property>
        <property name="margin-end">12</property>
        <property name="margin-bottom">12</property>
        <property name="margin-start">12</property>
        <property name="spacing">12</property>
        <child>
          <object class="GtkCalendar">
            <signal name="day-selected" handler="on_day_selected"/>
          </object>
        </child>
      </object>
    </child>
  </template>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
    </section>
  </menu>
</interface>
using Gtk 4.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject Gtk.Calendar';
  default-width: 683;
  default-height: 384;

  [titlebar]
  Gtk.HeaderBar header_bar {
    [end]
    Gtk.MenuButton {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }

  Gtk.Box {
    orientation: vertical;
    homogeneous: true;
    margin-top: 12;
    margin-end: 12;
    margin-bottom: 12;
    margin-start: 12;
    spacing: 12;

    Gtk.Calendar {
      day-selected => $on_day_selected();
    }
  }
}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
  }
}

Gtk.CheckButton#

Gtk.CheckButton

Gtk.CheckButton#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.CheckButton"""



import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()


class ExampleWindow(Gtk.ApplicationWindow):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.set_title(title='Python and GTK: PyGObject Gtk.CheckButton')
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append(
            label='Preferences',
            detailed_action='app.preferences',
        )

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        vbox = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=12)
        vbox.set_margin_top(margin=12)
        vbox.set_margin_end(margin=12)
        vbox.set_margin_bottom(margin=12)
        vbox.set_margin_start(margin=12)
        self.set_child(child=vbox)

        check_button = Gtk.CheckButton.new_with_label(label='Accept?')
        check_button.connect('toggled', self.on_check_button_toggled)
        vbox.append(child=check_button)

    def on_check_button_toggled(self, checkbutton):
        if checkbutton.get_active():
            print('Button checked')
        else:
            print('Button unchecked')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.CheckButton."""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent


@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    @Gtk.Template.Callback()
    def on_check_button_toggled(self, checkbutton):
        if checkbutton.get_active():
            print('Button checked')
        else:
            print('Button unchecked')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject Gtk.CheckButton</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar" id="header_bar">
        <child type="end">
          <object class="GtkMenuButton">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
    <child>
      <object class="GtkBox">
        <property name="orientation">1</property>
        <property name="margin-top">12</property>
        <property name="margin-end">12</property>
        <property name="margin-bottom">12</property>
        <property name="margin-start">12</property>
        <property name="spacing">12</property>
        <child>
          <object class="GtkCheckButton">
            <property name="label">Accept?</property>
            <signal name="toggled" handler="on_check_button_toggled"/>
          </object>
        </child>
      </object>
    </child>
  </template>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
    </section>
  </menu>
</interface>
using Gtk 4.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject Gtk.CheckButton';
  default-width: 683;
  default-height: 384;

  [titlebar]
  Gtk.HeaderBar header_bar {
    [end]
    Gtk.MenuButton {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }

  Gtk.Box {
    orientation: vertical;
    margin-top: 12;
    margin-end: 12;
    margin-bottom: 12;
    margin-start: 12;
    spacing: 12;

    Gtk.CheckButton {
      label: 'Accept?';
      toggled => $on_check_button_toggled();
    }
  }
}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
  }
}

Gtk.CheckButton (radio)#

Gtk.CheckButton (radio)

Gtk.CheckButton (radio)#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.CheckButton() radio.

In GTK 4 or higher, the RadioButton is a CheckButton that has a group.
"""



import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()


class ExampleWindow(Gtk.ApplicationWindow):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.set_title(
            title='Python and GTK: PyGObject Gtk.CheckButton() radio')
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append(
            label='Preferences',
            detailed_action='app.preferences',
        )

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        vbox = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=12)
        vbox.set_margin_top(margin=12)
        vbox.set_margin_end(margin=12)
        vbox.set_margin_bottom(margin=12)
        vbox.set_margin_start(margin=12)
        self.set_child(child=vbox)

        check_button_group = Gtk.CheckButton.new()

        check_button_01 = Gtk.CheckButton.new_with_label(label='Item 01')
        check_button_01.set_name(name='check_button_01')
        check_button_01.set_active(setting=True)
        check_button_01.set_group(group=check_button_group)
        check_button_01.connect('toggled', self.on_radio_button_toggled)
        vbox.append(child=check_button_01)

        check_button_02 = Gtk.CheckButton.new_with_label(label='Item 02')
        check_button_02.set_name(name='check_button_02')
        check_button_02.set_group(group=check_button_group)
        check_button_02.connect('toggled', self.on_radio_button_toggled)
        vbox.append(child=check_button_02)

        check_button_03 = Gtk.CheckButton.new_with_label(label='Item 03')
        check_button_03.set_name(name='check_button_03')
        check_button_03.set_group(group=check_button_group)
        check_button_03.connect('toggled', self.on_radio_button_toggled)
        vbox.append(child=check_button_03)

    def on_radio_button_toggled(self, widget):
        if widget.get_active():
            print(f'Radio text: {widget.get_label()}')
            print(f'Widget name: {widget.get_name()}')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.CheckButton() radio ui file.

In GTK 4 or higher, the RadioButton is a CheckButton that has a group.
"""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent


@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    @Gtk.Template.Callback()
    def on_radio_button_toggled(self, widget):
        if widget.get_active():
            print(f'Radio text: {widget.get_label()}')
            print(f'Widget name: {widget.get_name()}')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject Gtk.CheckButton() radio ui file</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar" id="header_bar">
        <child type="end">
          <object class="GtkMenuButton">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
    <child>
      <object class="GtkBox">
        <property name="orientation">1</property>
        <property name="margin-top">12</property>
        <property name="margin-end">12</property>
        <property name="margin-bottom">12</property>
        <property name="margin-start">12</property>
        <property name="spacing">12</property>
        <child>
          <object class="GtkCheckButton" id="check_button_01">
            <property name="name">check_button_01</property>
            <property name="label">Item 01</property>
            <property name="active">true</property>
            <property name="group">check_button_group</property>
            <signal name="toggled" handler="on_radio_button_toggled"/>
          </object>
        </child>
        <child>
          <object class="GtkCheckButton" id="check_button_02">
            <property name="name">check_button_02</property>
            <property name="label">Item 02</property>
            <property name="group">check_button_group</property>
            <signal name="toggled" handler="on_radio_button_toggled"/>
          </object>
        </child>
        <child>
          <object class="GtkCheckButton" id="check_button_03">
            <property name="name">check_button_03</property>
            <property name="label">Item 03</property>
            <property name="group">check_button_group</property>
            <signal name="toggled" handler="on_radio_button_toggled"/>
          </object>
        </child>
      </object>
    </child>
  </template>
  <object class="GtkCheckButton" id="check_button_group"></object>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
    </section>
  </menu>
</interface>
using Gtk 4.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject Gtk.CheckButton() radio ui file';
  default-width: 683;
  default-height: 384;

  [titlebar]
  Gtk.HeaderBar header_bar {
    [end]
    Gtk.MenuButton {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }

  Gtk.Box {
    orientation: vertical;
    margin-top: 12;
    margin-end: 12;
    margin-bottom: 12;
    margin-start: 12;
    spacing: 12;

    Gtk.CheckButton check_button_01 {
      name: 'check_button_01';
      label: 'Item 01';
      active: true;
      group: check_button_group;
      toggled => $on_radio_button_toggled();
    }
    
    Gtk.CheckButton check_button_02 {
      name: 'check_button_02';
      label: 'Item 02';
      group: check_button_group;
      toggled => $on_radio_button_toggled();
    }
    
    Gtk.CheckButton check_button_03 {
      name: 'check_button_03';
      label: 'Item 03';
      group: check_button_group;
      toggled => $on_radio_button_toggled();
    }
  }
}

Gtk.CheckButton check_button_group {
}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
  }
}

Gtk.ColorDialogButton#

Gtk.ColorDialogButton

Gtk.ColorDialogButton#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.ColorDialogButton"""



import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()


class ExampleWindow(Gtk.ApplicationWindow):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.set_title(title='Python and GTK: PyGObject Gtk.ColorDialogButton')
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append(
            label='Preferences',
            detailed_action='app.preferences',
        )

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        vbox = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=12)
        vbox.set_homogeneous(homogeneous=True)
        vbox.set_margin_top(margin=12)
        vbox.set_margin_end(margin=12)
        vbox.set_margin_bottom(margin=12)
        vbox.set_margin_start(margin=12)
        self.set_child(child=vbox)

        label = Gtk.Label.new(str='Click on the Button to select a color.')
        vbox.append(child=label)

        color_dialog = Gtk.ColorDialog.new()
        color_dialog.set_modal(modal=True)
        color_dialog.set_title(title='Select a color.')

        color_dialog_button = Gtk.ColorDialogButton.new(dialog=color_dialog)
        color_dialog_button.connect('notify::rgba', self.on_color_selected)
        color_dialog_button.set_halign(Gtk.Align.CENTER)
        color_dialog_button.set_valign(Gtk.Align.CENTER)
        vbox.append(child=color_dialog_button)

    def on_color_selected(self, color_dialog_button, g_param_boxed):
        gdk_rgba = color_dialog_button.get_rgba()
        print(f'Color RGB = {gdk_rgba.to_string()}')
        print(f'Alpha = {gdk_rgba.alpha}')
        print(f'Red = {gdk_rgba.red}')
        print(f'Green = {gdk_rgba.green}')
        print(f'Blue = {gdk_rgba.blue}')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.ColorDialogButton."""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent


@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    @Gtk.Template.Callback()
    def on_color_selected(self, color_dialog_button, g_param_boxed):
        gdk_rgba = color_dialog_button.get_rgba()
        print(f'Color RGB = {gdk_rgba.to_string()}')
        print(f'Alpha = {gdk_rgba.alpha}')
        print(f'Red = {gdk_rgba.red}')
        print(f'Green = {gdk_rgba.green}')
        print(f'Blue = {gdk_rgba.blue}')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject Gtk.ColorDialogButton.</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar" id="header_bar">
        <child type="end">
          <object class="GtkMenuButton">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
    <child>
      <object class="GtkBox">
        <property name="orientation">1</property>
        <property name="homogeneous">true</property>
        <property name="margin-top">12</property>
        <property name="margin-end">12</property>
        <property name="margin-bottom">12</property>
        <property name="margin-start">12</property>
        <property name="spacing">12</property>
        <child>
          <object class="GtkLabel">
            <property name="label">Click on the Button to select a color.</property>
          </object>
        </child>
        <child>
          <object class="GtkColorDialogButton">
            <property name="dialog">color_dialog</property>
            <property name="halign">3</property>
            <property name="valign">3</property>
            <signal name="notify::rgba" handler="on_color_selected"/>
          </object>
        </child>
      </object>
    </child>
  </template>
  <object class="GtkColorDialog" id="color_dialog">
    <property name="title">Select a color.</property>
    <property name="modal">true</property>
  </object>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
    </section>
  </menu>
</interface>
using Gtk 4.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject Gtk.ColorDialogButton.';
  default-width: 683;
  default-height: 384;

  [titlebar]
  Gtk.HeaderBar header_bar {
    [end]
    Gtk.MenuButton {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }

  Gtk.Box {
    orientation: vertical;
    homogeneous: true;
    margin-top: 12;
    margin-end: 12;
    margin-bottom: 12;
    margin-start: 12;
    spacing: 12;

    Gtk.Label {
      label: 'Click on the Button to select a color.';
    }

    Gtk.ColorDialogButton {
      dialog: color_dialog;
      halign: center;
      valign: center;
      notify::rgba => $on_color_selected();
    }
  }
}

Gtk.ColorDialog color_dialog {
  title: 'Select a color.';
  modal: true;
}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
  }
}

Drag and drop#

Drag and drop

Drag and drop#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject drag and drop."""



import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gdk, Gio, GObject, Gtk

Adw.init()


class DropArea(Gtk.Label):

    def __init__(self):
        super().__init__()

        self.set_label(str='Drag and drop the file here (class DropArea)')
        drag_source = Gtk.DragSource.new()
        drag_source.set_actions(Gdk.DragAction.COPY)
        drag_source.connect('prepare', self.on_prepare)
        drag_source.connect('drag-begin', self.on_drag_begin)
        drag_source.connect('drag-end', self.on_drag_end)
        drag_source.connect('drag-cancel', self.on_drag_cancel)

        drop_target = Gtk.DropTarget.new(
            GObject.TYPE_STRING, Gdk.DragAction.COPY)
        drop_target.connect('drop', self.on_drop)

        self.add_controller(drag_source)
        self.add_controller(drop_target)

    def on_prepare(self, DropTarget, x, y):
        print('[!] drag_source (prepare) [!]')
        print(f'Widget = {DropTarget}')
        print(f'Position on the x-axis = {x}')
        print(f'Position on the y-axis = {y}')

    def on_drag_begin(self):
        print('[!] drag_source (drag_begin) [!]')

    def on_drag_end(self):
        print('[!] drag_source (drag_end) [!]')

    def on_drag_cancel(self):
        print('[!] drag_source (drag_cancel) [!]')

    def on_drop(self, DropTarget, data, x, y):
        print('[!] drop_target (drop) [!]')
        print(f'Widget = {DropTarget}')
        print(f'Data = {data}')
        print(f'Position on the x-axis = {x}')
        print(f'Position on the y-axis = {y}')


class ExampleWindow(Gtk.ApplicationWindow):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.set_title(title='Python and GTK: PyGObject drag and drop')
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append(
            label='Preferences',
            detailed_action='app.preferences',
        )

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        vbox = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=12)
        vbox.set_homogeneous(homogeneous=True)
        # No GTK 3: set_border_width().
        vbox.set_margin_top(margin=12)
        vbox.set_margin_end(margin=12)
        vbox.set_margin_bottom(margin=12)
        vbox.set_margin_start(margin=12)
        # Adicionando o box na janela principal.
        # No GTK 3: add().
        self.set_child(child=vbox)

        drag_source = Gtk.DragSource.new()
        drag_source.set_actions(Gdk.DragAction.COPY)
        drag_source.connect('prepare', self.on_prepare)
        drag_source.connect('drag-begin', self.on_drag_begin)
        drag_source.connect('drag-end', self.on_drag_end)
        drag_source.connect('drag-cancel', self.on_drag_cancel)

        drop_target = Gtk.DropTarget.new(
            GObject.TYPE_STRING, Gdk.DragAction.COPY)
        drop_target.connect('drop', self.on_drop)

        label = Gtk.Label.new('Drag and drop the file here.')
        label.add_controller(drag_source)
        label.add_controller(drop_target)
        vbox.append(child=label)

        # class DropArea(Gtk.Label).
        drop_area = DropArea()
        vbox.append(child=drop_area)

    def on_prepare(self, DropTarget, x, y):
        print('[!] drag_source (prepare) [!]')
        print(f'Widget = {DropTarget}')
        print(f'Position on the x-axis = {x}')
        print(f'Position on the y-axis = {y}')

    def on_drag_begin(self):
        print('[!] drag_source (drag_begin) [!]')

    def on_drag_end(self):
        print('[!] drag_source (drag_end) [!]')

    def on_drag_cancel(self):
        print('[!] drag_source (drag_cancel) [!]')

    def on_drop(self, DropTarget, data, x, y):
        print('[!] drop_target (drop) [!]')
        print(f'Widget = {DropTarget}')
        print(f'Data = {data}')
        print(f'Position on the x-axis = {x}')
        print(f'Position on the y-axis = {y}')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)

Gtk.DropDown#

Gtk.DropDown

Gtk.DropDown#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.DropDown"""



import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()


class ExampleWindow(Gtk.ApplicationWindow):
    brazilian_states = [
        'Acre', 'Alagoas', 'Amapá', 'Amazonas', 'Bahia', 'Ceará',
        'Distrito Federal', 'Espírito Santo', 'Goiás', 'Maranhão',
        'Mato Grosso', 'Mato Grosso do Sul', 'Minas Gerais', 'Pará', 'Paraíba',
        'Paraná', 'Pernambuco', 'Piauí', 'Rio de Janeiro',
        'Rio Grande do Norte', 'Rio Grande do Sul', 'Rondônia', 'Roraima',
        'Santa Catarina', 'São Paulo', 'Sergipe', 'Tocantins',
    ]

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.set_title(title='Python and GTK: PyGObject Gtk.DropDown')
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append(
            label='Preferences',
            detailed_action='app.preferences',
        )

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        vbox = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=12)
        vbox.set_margin_top(margin=12)
        vbox.set_margin_end(margin=12)
        vbox.set_margin_bottom(margin=12)
        vbox.set_margin_start(margin=12)
        self.set_child(child=vbox)

        drop_down = Gtk.DropDown.new_from_strings(
            strings=self.brazilian_states,
        )
        drop_down.set_selected(position=1)
        drop_down.connect('notify::selected-item', self.on_selected_item)
        # drop_down.connect('notify::selected', self.on_selected_item)
        vbox.append(child=drop_down)

    def on_selected_item(self, drop_down, g_param_object):
        string_object = drop_down.get_selected_item()
        index = drop_down.get_selected()
        print(f'Position: {index} - value: {string_object.get_string()}')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.DropDown."""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent


@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    @Gtk.Template.Callback()
    def on_selected_item(self, drop_down, g_param_object):
        string_object = drop_down.get_selected_item()
        index = drop_down.get_selected()
        print(f'Position: {index} - value: {string_object.get_string()}')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject Gtk.DropDown</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar" id="header_bar">
        <child type="end">
          <object class="GtkMenuButton">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
    <child>
      <object class="GtkBox">
        <property name="orientation">1</property>
        <property name="margin-top">12</property>
        <property name="margin-end">12</property>
        <property name="margin-bottom">12</property>
        <property name="margin-start">12</property>
        <property name="spacing">12</property>
        <child>
          <object class="GtkDropDown">
            <property name="model">brazilian_states</property>
            <property name="selected">2</property>
            <signal name="notify::selected-item" handler="on_selected_item"/>
          </object>
        </child>
      </object>
    </child>
  </template>
  <object class="GtkStringList" id="brazilian_states">
    <items>
      <item>Acre</item>
      <item>Alagoas</item>
      <item>Amapá</item>
      <item>Amazonas</item>
      <item>Bahia</item>
      <item>Ceará</item>
      <item>Distrito Federal</item>
      <item>Espírito Santo</item>
      <item>Goiás</item>
      <item>Maranhão</item>
      <item>Mato Grosso</item>
      <item>Mato Grosso do Sul</item>
      <item>Minas Gerais</item>
      <item>Pará</item>
      <item>Paraíba</item>
      <item>Paraná</item>
      <item>Pernambuco</item>
      <item>Piauí</item>
      <item>Rio de Janeiro</item>
      <item>Rio Grande do Norte</item>
      <item>Rio Grande do Sul</item>
      <item>Rondônia</item>
      <item>Roraima</item>
      <item>Santa Catarina</item>
      <item>São Paulo</item>
      <item>Sergipe</item>
      <item>Tocantins</item>
    </items>
  </object>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
    </section>
  </menu>
</interface>
using Gtk 4.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject Gtk.DropDown';
  default-width: 683;
  default-height: 384;

  [titlebar]
  Gtk.HeaderBar header_bar {
    [end]
    Gtk.MenuButton {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }

  Gtk.Box {
    orientation: vertical;
    margin-top: 12;
    margin-end: 12;
    margin-bottom: 12;
    margin-start: 12;
    spacing: 12;

    Gtk.DropDown {
      model: brazilian_states;
      selected: 2;
      notify::selected-item => $on_selected_item();
    }
  }
}

Gtk.StringList brazilian_states {
  strings [
    'Acre', 'Alagoas', 'Amapá', 'Amazonas', 'Bahia', 'Ceará',
    'Distrito Federal', 'Espírito Santo', 'Goiás', 'Maranhão',
    'Mato Grosso', 'Mato Grosso do Sul', 'Minas Gerais', 'Pará',
    'Paraíba', 'Paraná', 'Pernambuco', 'Piauí', 'Rio de Janeiro',
    'Rio Grande do Norte', 'Rio Grande do Sul', 'Rondônia', 'Roraima',
    'Santa Catarina', 'São Paulo', 'Sergipe', 'Tocantins',
  ]
}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
  }
}

Gtk.Entry#

Gtk.Entry

Gtk.Entry#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.Entry"""



import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()


class ExampleWindow(Gtk.ApplicationWindow):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.set_title(title='Python and GTK: PyGObject Gtk.Entry')
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append(
            label='Preferences',
            detailed_action='app.preferences',
        )

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        vbox = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=12)
        vbox.set_margin_top(margin=12)
        vbox.set_margin_end(margin=12)
        vbox.set_margin_bottom(margin=12)
        vbox.set_margin_start(margin=12)
        self.set_child(child=vbox)

        label = Gtk.Label.new(
            str='Type something and click on the icon or press Enter:',
        )
        vbox.append(child=label)

        entry = Gtk.Entry.new()
        entry.set_icon_from_icon_name(
            # icon_pos=Gtk.EntryIconPosition.PRIMARY,
            icon_pos=Gtk.EntryIconPosition.SECONDARY,
            icon_name='system-search-symbolic',
        )
        entry.connect('activate', self.on_key_enter_pressed)
        entry.connect('icon-press', self.on_icon_pressed)
        vbox.append(child=entry)

    def on_key_enter_pressed(self, entry):
        print(f'(activate) Value entered in entry: {entry.get_text()}')

    def on_icon_pressed(self, entry, entryiconposition):
        print(f'(icon-press) Value entered in the entry: {entry.get_text()}')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.Entry."""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent


@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    @Gtk.Template.Callback()
    def on_key_enter_pressed(self, entry):
        print(f'(activate) Value entered in entry: {entry.get_text()}')

    @Gtk.Template.Callback()
    def on_icon_pressed(self, entry, entryiconposition):
        print(f'(icon-press) Value entered in the entry: {entry.get_text()}')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject Gtk.Entry</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar" id="header_bar">
        <child type="end">
          <object class="GtkMenuButton">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
    <child>
      <object class="GtkBox">
        <property name="orientation">1</property>
        <property name="margin-top">12</property>
        <property name="margin-end">12</property>
        <property name="margin-bottom">12</property>
        <property name="margin-start">12</property>
        <property name="spacing">12</property>
        <child>
          <object class="GtkLabel">
            <property name="label">Type something and click on the icon or press Enter:</property>
          </object>
        </child>
        <child>
          <object class="GtkEntry">
            <property name="secondary-icon-name">system-search-symbolic</property>
            <signal name="activate" handler="on_key_enter_pressed"/>
            <signal name="icon-press" handler="on_icon_pressed"/>
          </object>
        </child>
      </object>
    </child>
  </template>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
    </section>
  </menu>
</interface>
using Gtk 4.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject Gtk.Entry';
  default-width: 683;
  default-height: 384;

  [titlebar]
  Gtk.HeaderBar header_bar {
    [end]
    Gtk.MenuButton {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }

  Gtk.Box {
    orientation: vertical;
    margin-top: 12;
    margin-end: 12;
    margin-bottom: 12;
    margin-start: 12;
    spacing: 12;

    Gtk.Label {
      label: 'Type something and click on the icon or press Enter:';
    }

    Gtk.Entry {
      // primary-icon-name: 'system-search-symbolic';
      secondary-icon-name: 'system-search-symbolic';
      activate => $on_key_enter_pressed();
      icon-press => $on_icon_pressed();
    }
  }
}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
  }
}

Gtk.FileDialog (folder)#

Gtk.FileDialog (folder)

Gtk.FileDialog (folder)#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.FileDialog() folder."""



import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()


class ExampleWindow(Gtk.ApplicationWindow):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.set_title(
            title='Python and GTK: PyGObject Gtk.FileDialog() folder',
        )
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append(
            label='Preferences',
            detailed_action='app.preferences',
        )

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        vbox = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=12)
        vbox.set_margin_top(margin=12)
        vbox.set_margin_end(margin=12)
        vbox.set_margin_bottom(margin=12)
        vbox.set_margin_start(margin=12)
        self.set_child(child=vbox)

        button_select_file = Gtk.Button.new_with_label(
            label='Select folder',
        )
        button_select_file.connect(
            'clicked',
            self.on_button_select_folder_clicked,
        )
        vbox.append(child=button_select_file)

        button_select_files = Gtk.Button.new_with_label(
            label='Select folders',
        )
        button_select_files.connect(
            'clicked',
            self.on_button_select_folders_clicked,
        )
        vbox.append(child=button_select_files)

    def on_button_select_folder_clicked(self, widget):
        file_dialog = Gtk.FileDialog.new()
        file_dialog.set_title(title='Select folder')
        file_dialog.set_modal(modal=True)
        file_dialog.select_folder(
            parent=self,
            callback=self.on_file_dialog_dismissed,
        )

    def on_button_select_folders_clicked(self, widget):
        file_dialog = Gtk.FileDialog.new()
        file_dialog.set_title(title='Select folders')
        file_dialog.set_modal(modal=True)
        file_dialog.select_multiple_folders(
            parent=self,
            callback=self.on_files_dialog_dismissed,
        )

    def on_file_dialog_dismissed(self, file_dialog, gio_task):
        folder = file_dialog.select_folder_finish(gio_task)
        print(f'Folder name: {folder.get_basename()}')
        print(f'Folder path: {folder.get_path()}')
        print(f'Folder URI: {folder.get_uri()}\n')

    def on_files_dialog_dismissed(self, file_dialog, gio_task):
        folders = file_dialog.select_multiple_folders_finish(gio_task)
        for folder in folders:
            print(f'Folder name: {folder.get_basename()}')
            print(f'Folder path: {folder.get_path()}')
            print(f'Folder URI: {folder.get_uri()}\n')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.FileDialog() (folder) ui file."""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent


@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    @Gtk.Template.Callback()
    def on_button_select_folder_clicked(self, widget):
        file_dialog = Gtk.FileDialog.new()
        file_dialog.set_title(title='Select folder')
        file_dialog.set_modal(modal=True)
        file_dialog.select_folder(
            parent=self,
            callback=self.on_file_dialog_dismissed,
        )

    @Gtk.Template.Callback()
    def on_button_select_folders_clicked(self, widget):
        file_dialog = Gtk.FileDialog.new()
        file_dialog.set_title(title='Select folders')
        file_dialog.set_modal(modal=True)
        file_dialog.select_multiple_folders(
            parent=self,
            callback=self.on_files_dialog_dismissed,
        )

    def on_file_dialog_dismissed(self, file_dialog, gio_task):
        folder = file_dialog.select_folder_finish(gio_task)
        print(f'Folder name: {folder.get_basename()}')
        print(f'Folder path: {folder.get_path()}')
        print(f'Folder URI: {folder.get_uri()}\n')

    def on_files_dialog_dismissed(self, file_dialog, gio_task):
        folders = file_dialog.select_multiple_folders_finish(gio_task)
        for folder in folders:
            print(f'Folder name: {folder.get_basename()}')
            print(f'Folder path: {folder.get_path()}')
            print(f'Folder URI: {folder.get_uri()}\n')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject Gtk.FileDialog() (folder) ui file</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar" id="header_bar">
        <child type="end">
          <object class="GtkMenuButton">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
    <child>
      <object class="GtkBox">
        <property name="orientation">1</property>
        <property name="margin-top">12</property>
        <property name="margin-end">12</property>
        <property name="margin-bottom">12</property>
        <property name="margin-start">12</property>
        <property name="spacing">12</property>
        <child>
          <object class="GtkButton">
            <property name="label">Select folder</property>
            <signal name="clicked" handler="on_button_select_folder_clicked"/>
          </object>
        </child>
        <child>
          <object class="GtkButton">
            <property name="label">Select folders</property>
            <signal name="clicked" handler="on_button_select_folders_clicked"/>
          </object>
        </child>
      </object>
    </child>
  </template>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
    </section>
  </menu>
</interface>
using Gtk 4.0;
using Gio 2.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject Gtk.FileDialog() (folder) ui file';
  default-width: 683;
  default-height: 384;

  [titlebar]
  Gtk.HeaderBar header_bar {
    [end]
    Gtk.MenuButton {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }

  Gtk.Box {
    orientation: vertical;
    margin-top: 12;
    margin-end: 12;
    margin-bottom: 12;
    margin-start: 12;
    spacing: 12;

    Gtk.Button {
      label: 'Select folder';
      clicked => $on_button_select_folder_clicked();
    }

    Gtk.Button {
      label: 'Select folders';
      clicked => $on_button_select_folders_clicked();
    }
  }
}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
  }
}

Gtk.FileDialog (open)#

Gtk.FileDialog (open)

Gtk.FileDialog (open)#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.FileDialog() open."""



import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

FILTER_ALL_FILES = Gtk.FileFilter()
FILTER_ALL_FILES.set_name(name='All')
FILTER_ALL_FILES.add_pattern(pattern='*')

FILTER_PY_FILES = Gtk.FileFilter()
FILTER_PY_FILES.set_name(name='Python')
FILTER_PY_FILES.add_pattern(pattern='*.py')
FILTER_PY_FILES.add_mime_type(mime_type='text/x-python')

FILTER_TXT_FILES = Gtk.FileFilter()
FILTER_TXT_FILES.set_name(name='txt')
FILTER_TXT_FILES.add_pattern(pattern='*.txt')
FILTER_TXT_FILES.add_mime_type(mime_type='text/plain')


class ExampleWindow(Gtk.ApplicationWindow):
    gio_list_store = Gio.ListStore.new(Gtk.FileFilter)
    gio_list_store.append(item=FILTER_ALL_FILES)
    gio_list_store.append(item=FILTER_PY_FILES)
    gio_list_store.append(item=FILTER_TXT_FILES)

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.set_title(
            title='Python and GTK: PyGObject Gtk.FileDialog() open',
        )
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append(
            label='Preferences',
            detailed_action='app.preferences',
        )

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        vbox = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=12)
        vbox.set_margin_top(margin=12)
        vbox.set_margin_end(margin=12)
        vbox.set_margin_bottom(margin=12)
        vbox.set_margin_start(margin=12)
        self.set_child(child=vbox)

        button_select_file = Gtk.Button.new_with_label(
            label='Select file',
        )
        button_select_file.connect(
            'clicked',
            self.on_button_select_file_clicked,
        )
        vbox.append(child=button_select_file)

        button_select_files = Gtk.Button.new_with_label(
            label='Select files',
        )
        button_select_files.connect(
            'clicked',
            self.on_button_select_files_clicked,
        )
        vbox.append(child=button_select_files)

    def on_button_select_file_clicked(self, widget):
        file_dialog = Gtk.FileDialog.new()
        file_dialog.set_title(title='Select file.')
        file_dialog.set_modal(modal=True)
        file_dialog.set_filters(filters=self.gio_list_store)
        file_dialog.open(parent=self, callback=self.on_file_dialog_dismissed)

    def on_button_select_files_clicked(self, widget):
        file_dialog = Gtk.FileDialog.new()
        file_dialog.set_title(title='Select files.')
        file_dialog.set_modal(modal=True)
        file_dialog.set_filters(filters=self.gio_list_store)
        file_dialog.open_multiple(
            parent=self,
            callback=self.on_files_dialog_dismissed,
        )

    def on_file_dialog_dismissed(self, file_dialog, gio_task):
        local_file = file_dialog.open_finish(gio_task)
        print(f'File name: {local_file.get_basename()}')
        print(f'File path: {local_file.get_path()}')
        print(f'File URI: {local_file.get_uri()}\n')

    def on_files_dialog_dismissed(self, file_dialog, gio_task):
        local_files = file_dialog.open_multiple_finish(gio_task)
        for local_file in local_files:
            print(f'File name: {local_file.get_basename()}')
            print(f'File path: {local_file.get_path()}')
            print(f'File URI: {local_file.get_uri()}\n')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.FileDialog() (open) ui file."""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent


@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    gio_list_store = Gtk.Template.Child(name='gio_list_store')

    filter_all_files = Gtk.Template.Child(name='filter_all_files')
    filter_py_files = Gtk.Template.Child(name='filter_py_files')
    filter_txt_files = Gtk.Template.Child(name='filter_txt_files')

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.gio_list_store.append(item=self.filter_all_files)
        self.gio_list_store.append(item=self.filter_py_files)
        self.gio_list_store.append(item=self.filter_txt_files)

    @Gtk.Template.Callback()
    def on_button_select_file_clicked(self, widget):
        file_dialog = Gtk.FileDialog.new()
        file_dialog.set_title(title='Select file')
        file_dialog.set_modal(modal=True)
        file_dialog.set_filters(filters=self.gio_list_store)
        file_dialog.open(parent=self, callback=self.on_file_dialog_dismissed)

    @Gtk.Template.Callback()
    def on_button_select_files_clicked(self, widget):
        file_dialog = Gtk.FileDialog.new()
        file_dialog.set_title(title='Select files')
        file_dialog.set_modal(modal=True)
        file_dialog.set_filters(filters=self.gio_list_store)
        file_dialog.open_multiple(
            parent=self,
            callback=self.on_files_dialog_dismissed,
        )

    def on_file_dialog_dismissed(self, file_dialog, gio_task):
        local_file = file_dialog.open_finish(gio_task)
        print(f'File name: {local_file.get_basename()}')
        print(f'File path: {local_file.get_path()}')
        print(f'File URI: {local_file.get_uri()}\n')

    def on_files_dialog_dismissed(self, file_dialog, gio_task):
        local_files = file_dialog.open_multiple_finish(gio_task)
        print(local_files)
        for local_file in local_files:
            print(f'File name: {local_file.get_basename()}')
            print(f'File path: {local_file.get_path()}')
            print(f'File URI: {local_file.get_uri()}\n')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':

    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject Gtk.FileDialog() (open) ui file</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar" id="header_bar">
        <child type="end">
          <object class="GtkMenuButton">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
    <child>
      <object class="GtkBox">
        <property name="orientation">1</property>
        <property name="margin-top">12</property>
        <property name="margin-end">12</property>
        <property name="margin-bottom">12</property>
        <property name="margin-start">12</property>
        <property name="spacing">12</property>
        <child>
          <object class="GtkButton">
            <property name="label">Select file</property>
            <signal name="clicked" handler="on_button_select_file_clicked"/>
          </object>
        </child>
        <child>
          <object class="GtkButton">
            <property name="label">Select files</property>
            <signal name="clicked" handler="on_button_select_files_clicked"/>
          </object>
        </child>
      </object>
    </child>
  </template>
  <object class="GtkFileFilter" id="filter_all_files">
    <property name="name">All</property>
    <patterns>
      <pattern>*</pattern>
    </patterns>
    <suffixes>
      <suffix>*</suffix>
    </suffixes>
  </object>
  <object class="GtkFileFilter" id="filter_py_files">
    <mime-types>
      <mime-type>text/x-python</mime-type>
    </mime-types>
    <patterns>
      <pattern>*.py</pattern>
    </patterns>
    <suffixes>
      <suffix>py</suffix>
    </suffixes>
  </object>
  <object class="GtkFileFilter" id="filter_txt_files">
    <mime-types>
      <mime-type>text/plain</mime-type>
    </mime-types>
    <patterns>
      <pattern>*.txt</pattern>
    </patterns>
    <suffixes>
      <suffix>txt</suffix>
    </suffixes>
  </object>
  <object class="GListStore" id="gio_list_store">
    <property name="item-type">GtkFileFilter</property>
  </object>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
    </section>
  </menu>
</interface>
using Gtk 4.0;
using Gio 2.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject Gtk.FileDialog() (open) ui file';
  default-width: 683;
  default-height: 384;

  [titlebar]
  Gtk.HeaderBar header_bar {
    [end]
    Gtk.MenuButton {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }

  Gtk.Box {
    orientation: vertical;
    margin-top: 12;
    margin-end: 12;
    margin-bottom: 12;
    margin-start: 12;
    spacing: 12;

    Gtk.Button {
      label: 'Select file';
      clicked => $on_button_select_file_clicked();
    }

    Gtk.Button {
      label: 'Select files';
      clicked => $on_button_select_files_clicked();
    }
  }
}

Gtk.FileFilter filter_all_files {
  name: 'All';
  patterns [ '*' ]
  suffixes [ '*' ]
}

Gtk.FileFilter filter_py_files {
  mime-types [ 'text/x-python' ]
  patterns [ '*.py' ]
  suffixes [ 'py' ]
}

Gtk.FileFilter filter_txt_files {
  mime-types [ 'text/plain' ]
  patterns [ '*.txt' ]
  suffixes [ 'txt' ]
}

Gio.ListStore gio_list_store {
  item-type: typeof<Gtk.FileFilter>;
}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
  }
}

Gtk.FileDialog (save)#

Gtk.FileDialog (save)

Gtk.FileDialog (save)#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.FileDialog() save."""



import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

FILTER_ALL_FILES = Gtk.FileFilter()
FILTER_ALL_FILES.set_name(name='All')
FILTER_ALL_FILES.add_pattern(pattern='*')

FILTER_PY_FILES = Gtk.FileFilter()
FILTER_PY_FILES.set_name(name='Python')
FILTER_PY_FILES.add_pattern(pattern='*.py')
FILTER_PY_FILES.add_mime_type(mime_type='text/x-python')

FILTER_TXT_FILES = Gtk.FileFilter()
FILTER_TXT_FILES.set_name(name='txt')
FILTER_TXT_FILES.add_pattern(pattern='*.txt')
FILTER_TXT_FILES.add_mime_type(mime_type='text/plain')


class ExampleWindow(Gtk.ApplicationWindow):
    gio_list_store = Gio.ListStore.new(Gtk.FileFilter)
    gio_list_store.append(item=FILTER_ALL_FILES)
    gio_list_store.append(item=FILTER_PY_FILES)
    gio_list_store.append(item=FILTER_TXT_FILES)

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.set_title(
            title='Python and GTK: PyGObject Gtk.FileDialog() save',
        )
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append(
            label='Preferences',
            detailed_action='app.preferences',
        )

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        vbox = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=12)
        vbox.set_margin_top(margin=12)
        vbox.set_margin_end(margin=12)
        vbox.set_margin_bottom(margin=12)
        vbox.set_margin_start(margin=12)
        self.set_child(child=vbox)

        button_save = Gtk.Button.new_with_label(label='Save')
        button_save.connect('clicked', self.on_button_save_clicked)
        vbox.append(child=button_save)

    def on_button_save_clicked(self, widget):
        file_dialog = Gtk.FileDialog.new()
        file_dialog.set_title(title='Save')
        file_dialog.set_initial_name(name='file-name')
        file_dialog.set_modal(modal=True)
        file_dialog.set_filters(filters=self.gio_list_store)
        file_dialog.save(parent=self, callback=self.on_file_dialog_dismissed)

    def on_file_dialog_dismissed(self, file_dialog, gio_task):
        local_file = file_dialog.save_finish(gio_task)
        print(f'File name: {local_file.get_basename()}')
        print(f'File path: {local_file.get_path()}')
        print(f'File URI: {local_file.get_uri()}\n')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.FileDialog() (save) ui file."""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent


@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    gio_list_store = Gtk.Template.Child(name='gio_list_store')

    filter_all_files = Gtk.Template.Child(name='filter_all_files')
    filter_py_files = Gtk.Template.Child(name='filter_py_files')
    filter_txt_files = Gtk.Template.Child(name='filter_txt_files')

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.gio_list_store.append(item=self.filter_all_files)
        self.gio_list_store.append(item=self.filter_py_files)
        self.gio_list_store.append(item=self.filter_txt_files)

    @Gtk.Template.Callback()
    def on_button_save_clicked(self, widget):
        file_dialog = Gtk.FileDialog.new()
        file_dialog.set_title(title='Save')
        file_dialog.set_initial_name(name='file-name')
        file_dialog.set_modal(modal=True)
        file_dialog.set_filters(filters=self.gio_list_store)
        file_dialog.save(parent=self, callback=self.on_file_dialog_dismissed)

    def on_file_dialog_dismissed(self, file_dialog, gio_task):
        local_file = file_dialog.save_finish(gio_task)
        print(f'File name: {local_file.get_basename()}')
        print(f'File path: {local_file.get_path()}')
        print(f'File URI: {local_file.get_uri()}\n')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject Gtk.FileDialog() (save) ui file</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar" id="header_bar">
        <child type="end">
          <object class="GtkMenuButton">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
    <child>
      <object class="GtkBox">
        <property name="orientation">1</property>
        <property name="margin-top">12</property>
        <property name="margin-end">12</property>
        <property name="margin-bottom">12</property>
        <property name="margin-start">12</property>
        <property name="spacing">12</property>
        <child>
          <object class="GtkButton">
            <property name="label">Save</property>
            <signal name="clicked" handler="on_button_save_clicked"/>
          </object>
        </child>
      </object>
    </child>
  </template>
  <object class="GtkFileFilter" id="filter_all_files">
    <property name="name">All</property>
    <patterns>
      <pattern>*</pattern>
    </patterns>
    <suffixes>
      <suffix>*</suffix>
    </suffixes>
  </object>
  <object class="GtkFileFilter" id="filter_py_files">
    <mime-types>
      <mime-type>text/x-python</mime-type>
    </mime-types>
    <patterns>
      <pattern>*.py</pattern>
    </patterns>
    <suffixes>
      <suffix>py</suffix>
    </suffixes>
  </object>
  <object class="GtkFileFilter" id="filter_txt_files">
    <mime-types>
      <mime-type>text/plain</mime-type>
    </mime-types>
    <patterns>
      <pattern>*.txt</pattern>
    </patterns>
    <suffixes>
      <suffix>txt</suffix>
    </suffixes>
  </object>
  <object class="GListStore" id="gio_list_store">
    <property name="item-type">GtkFileFilter</property>
  </object>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
    </section>
  </menu>
</interface>
using Gtk 4.0;
using Gio 2.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject Gtk.FileDialog() (save) ui file';
  default-width: 683;
  default-height: 384;

  [titlebar]
  Gtk.HeaderBar header_bar {
    [end]
    Gtk.MenuButton {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }

  Gtk.Box {
    orientation: vertical;
    margin-top: 12;
    margin-end: 12;
    margin-bottom: 12;
    margin-start: 12;
    spacing: 12;

    Gtk.Button {
      label: 'Save';
      clicked => $on_button_save_clicked();
    }
  }
}

Gtk.FileFilter filter_all_files {
  name: 'All';
  patterns [ '*' ]
  suffixes [ '*' ]
}

Gtk.FileFilter filter_py_files {
  mime-types [ 'text/x-python' ]
  patterns [ '*.py' ]
  suffixes [ 'py' ]
}

Gtk.FileFilter filter_txt_files {
  mime-types [ 'text/plain' ]
  patterns [ '*.txt' ]
  suffixes [ 'txt' ]
}

Gio.ListStore gio_list_store {
  item-type: typeof<Gtk.FileFilter>;
}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
  }
}

Gtk.Fixed#

Gtk.Fixed

Gtk.Fixed#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.Fixed"""



import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()


class ExampleWindow(Gtk.ApplicationWindow):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.set_title(title='Python and GTK: PyGObject Gtk.Fixed')
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append(
            label='Preferences',
            detailed_action='app.preferences',
        )

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        self.fixed = Gtk.Fixed.new()
        self.fixed.set_margin_top(margin=12)
        self.fixed.set_margin_end(margin=12)
        self.fixed.set_margin_bottom(margin=12)
        self.fixed.set_margin_start(margin=12)
        self.set_child(child=self.fixed)

        button = Gtk.Button.new_with_label(label='Click here')
        button.connect('clicked', self.on_button_clicked)
        self.fixed.put(widget=button, x=0, y=0)

    def on_button_clicked(self, widget):
        self.fixed.move(widget=widget, x=100, y=100)
        widget.set_label(label='Moved')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.Fixed."""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent


@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    fixed = Gtk.Template.Child()

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    @Gtk.Template.Callback()
    def on_button_clicked(self, button):
        self.fixed.move(widget=button, x=100, y=100)
        button.set_label(label='Moved')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject Gtk.Fixed</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar" id="header_bar">
        <child type="end">
          <object class="GtkMenuButton">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
    <child>
      <object class="GtkFixed" id="fixed">
        <property name="margin-top">12</property>
        <property name="margin-end">12</property>
        <property name="margin-bottom">12</property>
        <property name="margin-start">12</property>
        <child>
          <object class="GtkButton">
            <property name="label">Click here</property>
            <signal name="clicked" handler="on_button_clicked"/>
          </object>
        </child>
      </object>
    </child>
  </template>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
    </section>
  </menu>
</interface>
using Gtk 4.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject Gtk.Fixed';
  default-width: 683;
  default-height: 384;

  [titlebar]
  Gtk.HeaderBar header_bar {
    [end]
    Gtk.MenuButton {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }

  Gtk.Fixed fixed {
    margin-top: 12;
    margin-end: 12;
    margin-bottom: 12;
    margin-start: 12;

    Gtk.Button {
      label: 'Click here';
      clicked => $on_button_clicked();
    }
  }
}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
  }
}

Gtk.FlowBox#

Gtk.FlowBox

Gtk.FlowBox#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.FlowBox"""



import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()


class ExampleWindow(Gtk.ApplicationWindow):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.set_title(title='Python and GTK: PyGObject Gtk.FlowBox')
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 6), height=int(768 / 6))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append(
            label='Preferences',
            detailed_action='app.preferences',
        )

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        scrolled_window = Gtk.ScrolledWindow.new()
        self.set_child(child=scrolled_window)

        flowbox = Gtk.FlowBox.new()
        flowbox.set_margin_top(margin=12)
        flowbox.set_margin_end(margin=12)
        flowbox.set_margin_bottom(margin=12)
        flowbox.set_margin_start(margin=12)
        flowbox.set_valign(align=Gtk.Align.START)
        flowbox.set_max_children_per_line(n_children=5)
        flowbox.set_selection_mode(mode=Gtk.SelectionMode.NONE)
        scrolled_window.set_child(child=flowbox)

        for n in range(100):
            button = Gtk.Button.new_with_label(label=f'Button {n}')
            flowbox.insert(widget=button, position=n)


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.FlowBox."""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent


@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject Gtk.FlowBox</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar" id="header_bar">
        <child type="end">
          <object class="GtkMenuButton">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
    <child>
      <object class="GtkScrolledWindow">
        <child>
          <object class="GtkFlowBox">
            <property name="margin-top">12</property>
            <property name="margin-end">12</property>
            <property name="margin-bottom">12</property>
            <property name="margin-start">12</property>
            <property name="valign">1</property>
            <property name="max-children-per-line">5</property>
            <property name="selection-mode">0</property>
            <child>
              <object class="GtkButton">
                <property name="label">Button 01</property>
              </object>
            </child>
            <child>
              <object class="GtkButton">
                <property name="label">Button 02</property>
              </object>
            </child>
            <child>
              <object class="GtkButton">
                <property name="label">Button 03</property>
              </object>
            </child>
            <child>
              <object class="GtkButton">
                <property name="label">Button 04</property>
              </object>
            </child>
            <child>
              <object class="GtkButton">
                <property name="label">Button 05</property>
              </object>
            </child>
            <child>
              <object class="GtkButton">
                <property name="label">Button 06</property>
              </object>
            </child>
          </object>
        </child>
      </object>
    </child>
  </template>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
    </section>
  </menu>
</interface>
using Gtk 4.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject Gtk.FlowBox';
  default-width: 683;
  default-height: 384;

  [titlebar]
  Gtk.HeaderBar header_bar {
    [end]
    Gtk.MenuButton {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }

  Gtk.ScrolledWindow {
    Gtk.FlowBox {
      margin-top: 12;
      margin-end: 12;
      margin-bottom: 12;
      margin-start: 12;
      valign: start;
      max-children-per-line: 5;
      selection-mode: none;

      Gtk.Button {
        label: 'Button 01';
      }

      Gtk.Button {
        label: 'Button 02';
      }

      Gtk.Button {
        label: 'Button 03';
      }

      Gtk.Button {
        label: 'Button 04';
      }

      Gtk.Button {
        label: 'Button 05';
      }

      Gtk.Button {
        label: 'Button 06';
      }
    }
  }
}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
  }
}

Gtk.Grid#

Gtk.Grid

Gtk.Grid#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.Grid"""



import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()


class ExampleWindow(Gtk.ApplicationWindow):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.set_title(title='Python and GTK: PyGObject Gtk.Grid')
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append(
            label='Preferences',
            detailed_action='app.preferences',
        )

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        grid = Gtk.Grid.new()
        grid.set_margin_top(margin=12)
        grid.set_margin_end(margin=12)
        grid.set_margin_bottom(margin=12)
        grid.set_margin_start(margin=12)
        grid.set_row_spacing(spacing=12)
        grid.set_column_spacing(spacing=12)
        self.set_child(child=grid)

        button1 = Gtk.Button.new_with_label(label='Button 1')
        button2 = Gtk.Button.new_with_label(label='Button 2')
        button3 = Gtk.Button.new_with_label(label='Button 3')
        button4 = Gtk.Button.new_with_label(label='Button 4')
        button5 = Gtk.Button.new_with_label(label='Button 5')
        button6 = Gtk.Button.new_with_label(label='Button 6')

        # Adding sequentially.
        # grid.add(widget=button1)
        # grid.add(widget=button2)
        # grid.add(widget=button3)
        # grid.add(widget=button4)
        # grid.add(widget=button5)
        # grid.add(widget=button6)

        # Positioning using attach()
        # Determining the position based on columns and rows.
        # grid.attach(child=button1, left=0, top=0, width=1, height=1)
        # grid.attach(child=button2, left=1, top=0, width=1, height=1)
        # grid.attach(child=button3, left=0, top=1, width=1, height=1)
        # grid.attach(child=button4, left=1, top=1, width=1, height=1)
        # grid.attach(child=button5, left=0, top=2, width=1, height=1)
        # grid.attach(child=button6, left=1, top=2, width=1, height=1)

        # Positioning using attach_next_to()
        # In this positioning we use other widgets as references.
        # Button 1 is in column 0 and row 0
        grid.attach(child=button1, column=0, row=0, width=1, height=1)
        # Button 2 is in column 1 and row 0 and merges 2 columns and 1 row.
        grid.attach(child=button2, column=1, row=0, width=2, height=1)
        # Button 3 is referenced to Button 1, it should be below
        # Button 1 (BOTTOM), it merges 1 column and 2 rows.
        grid.attach_next_to(
            child=button3,
            sibling=button1,
            side=Gtk.PositionType.BOTTOM,
            width=1, height=2
        )
        # Button 4 is referenced to Button 3, it should be to the right of
        # Button 3 (RIGHT), it merges 2 columns and 1 row.
        grid.attach_next_to(
            child=button4,
            sibling=button3,
            side=Gtk.PositionType.RIGHT,
            width=2,
            height=1
        )
        # Button 5 is in column 1, row 2 and merges 1 column and 1 row.
        grid.attach(child=button5, column=1, row=2, width=1, height=1)
        # Button 6 is referenced to Button 5, it should be to the right of
        # Button 5 (RIGHT), it merges 1 column and 1 row.
        grid.attach_next_to(
            child=button6,
            sibling=button5,
            side=Gtk.PositionType.RIGHT,
            width=1,
            height=1
        )


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.Grid."""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent


@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject Gtk.Grid</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar" id="header_bar">
        <child type="end">
          <object class="GtkMenuButton">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
    <child>
      <object class="GtkGrid">
        <property name="margin-top">12</property>
        <property name="margin-end">12</property>
        <property name="margin-bottom">12</property>
        <property name="margin-start">12</property>
        <property name="row-spacing">12</property>
        <property name="column-spacing">12</property>
        <child>
          <object class="GtkButton">
            <property name="label">Button 01</property>
            <layout>
              <property name="column">0</property>
              <property name="row">0</property>
            </layout>
          </object>
        </child>
        <child>
          <object class="GtkButton">
            <property name="label">Button 02</property>
            <layout>
              <property name="column">1</property>
              <property name="row">0</property>
              <property name="column-span">2</property>
            </layout>
          </object>
        </child>
        <child>
          <object class="GtkButton">
            <property name="label">Button 03</property>
            <layout>
              <property name="column">0</property>
              <property name="row">1</property>
              <property name="row-span">2</property>
            </layout>
          </object>
        </child>
        <child>
          <object class="GtkButton">
            <property name="label">Button 04</property>
            <layout>
              <property name="column">1</property>
              <property name="row">1</property>
              <property name="column-span">2</property>
            </layout>
          </object>
        </child>
        <child>
          <object class="GtkButton">
            <property name="label">Button 05</property>
            <layout>
              <property name="column">1</property>
              <property name="row">2</property>
            </layout>
          </object>
        </child>
        <child>
          <object class="GtkButton">
            <property name="label">Button 06</property>
            <layout>
              <property name="column">2</property>
              <property name="row">2</property>
            </layout>
          </object>
        </child>
      </object>
    </child>
  </template>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
    </section>
  </menu>
</interface>
using Gtk 4.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject Gtk.Grid';
  default-width: 683;
  default-height: 384;

  [titlebar]
  Gtk.HeaderBar header_bar {
    [end]
    Gtk.MenuButton {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }

  Gtk.Grid {
    margin-top: 12;
    margin-end: 12;
    margin-bottom: 12;
    margin-start: 12;
    row-spacing: 12;
    column-spacing: 12;

    Gtk.Button {
      label: 'Button 01';
      layout {
        column: '0';
        row: '0';
      }
    }

    Gtk.Button {
      label: 'Button 02';
      layout {
        column: '1';
        row: '0';
        column-span: '2';
      }
    }

    Gtk.Button {
      label: 'Button 03';
      layout {
        column: '0';
        row: '1';
        row-span: '2';
      }
    }

    Gtk.Button {
      label: 'Button 04';
      layout {
        column: '1';
        row: '1';
        column-span: '2';
      }
    }

    Gtk.Button {
      label: 'Button 05';
      layout {
        column: '1';
        row: '2';
      }
    }

    Gtk.Button {
      label: 'Button 06';
      layout {
        column: '2';
        row: '2';
      }
    }
  }
}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
  }
}

Gtk.HeaderBar#

Gtk.HeaderBar

Gtk.HeaderBar#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.HeaderBar"""



import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()


class ExampleWindow(Gtk.ApplicationWindow):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.set_title(title='Python and GTK: PyGObject Gtk.HeaderBar')
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append(
            label='Preferences',
            detailed_action='app.preferences',
        )

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        button_mail = Gtk.Button.new_from_icon_name(
            icon_name='mail-send-receive-symbolic',
        )
        button_mail.connect('clicked', self.on_button_send_mail_cliqued)
        header_bar.pack_end(child=button_mail)

        hbox = Gtk.Box.new(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
        header_bar.pack_start(child=hbox)

        button_left_arrow = Gtk.Button.new_from_icon_name(
            icon_name='go-previous-symbolic',
        )
        button_left_arrow.connect('clicked', self.on_button_left_arrow_cliqued)
        hbox.append(child=button_left_arrow)

        button_right_arrow = Gtk.Button.new_from_icon_name(
            icon_name='go-previous-symbolic-rtl',
        )
        button_right_arrow.connect(
            'clicked', self.on_button_right_arrow_cliqued)
        hbox.append(child=button_right_arrow)

    @staticmethod
    def on_button_send_mail_cliqued(button):
        print('You clicked on the button with the send/receive email icon')

    @staticmethod
    def on_button_left_arrow_cliqued(butthon):
        print('You clicked on the button with the left arrow')

    @staticmethod
    def on_button_right_arrow_cliqued(button):
        print('You clicked on the button with the right arrow')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.HeaderBar."""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent


@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    @Gtk.Template.Callback()
    def on_button_left_arrow_cliqued(self, butthon):
        print('You clicked on the button with the left arrow')

    @Gtk.Template.Callback()
    def on_button_right_arrow_cliqued(self, button):
        print('You clicked on the button with the right arrow')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject Gtk.HeaderBar</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar" id="header_bar">
        <child type="start">
          <object class="GtkBox">
            <property name="orientation">0</property>
            <child>
              <object class="GtkButton">
                <property name="icon-name">go-previous-symbolic</property>
                <signal name="clicked" handler="on_button_left_arrow_cliqued"/>
              </object>
            </child>
            <child>
              <object class="GtkButton">
                <property name="icon-name">go-previous-symbolic-rtl</property>
                <signal name="clicked" handler="on_button_right_arrow_cliqued"/>
              </object>
            </child>
          </object>
        </child>
        <child type="end">
          <object class="GtkMenuButton">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
    <child>
      <object class="GtkBox">
        <property name="orientation">1</property>
        <property name="homogeneous">true</property>
        <property name="margin-top">12</property>
        <property name="margin-end">12</property>
        <property name="margin-bottom">12</property>
        <property name="margin-start">12</property>
        <property name="spacing">12</property>
      </object>
    </child>
  </template>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
    </section>
  </menu>
</interface>
using Gtk 4.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject Gtk.HeaderBar';
  default-width: 683;
  default-height: 384;

  [titlebar]
  Gtk.HeaderBar header_bar {
    [start]
    Gtk.Box {
      orientation: horizontal;

      Gtk.Button {
        icon-name: 'go-previous-symbolic';
        clicked => $on_button_left_arrow_cliqued();
      }

      Gtk.Button {
        icon-name: 'go-previous-symbolic-rtl';
        clicked => $on_button_right_arrow_cliqued();
      }
    }

    [end]
    Gtk.MenuButton {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }

  Gtk.Box {
    orientation: vertical;
    homogeneous: true;
    margin-top: 12;
    margin-end: 12;
    margin-bottom: 12;
    margin-start: 12;
    spacing: 12;
  }
}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
  }
}

Gtk.Image#

Gtk.Image

Gtk.Image#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.Image().

It is suitable for loading icons.

The size is calculated automatically by GTK.

If you want to load an image, use `Gtk.Picture()`.
"""

import pathlib



import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()


SRC_DIR = BASE_DIR.parent.parent
CUSTOM_IMAGE = str(
    SRC_DIR.joinpath('data', 'icons', 'br.com.justcode.Exemplo.png')
)


class ExampleWindow(Gtk.ApplicationWindow):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.set_title(title='Python and GTK: PyGObject Gtk.Image')
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append(
            label='Preferences',
            detailed_action='app.preferences',
        )

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        vbox = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=0)
        vbox.set_homogeneous(homogeneous=True)
        vbox.set_margin_top(margin=12)
        vbox.set_margin_end(margin=12)
        vbox.set_margin_bottom(margin=12)
        vbox.set_margin_start(margin=12)
        self.set_child(child=vbox)

        image = Gtk.Image.new_from_file(filename=CUSTOM_IMAGE)
        image.add_css_class(css_class='lowres-icon')

        button = Gtk.Button.new()
        button.set_child(child=image)
        vbox.append(child=button)


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.Image().

It is suitable for loading icons.

The size is calculated automatically by GTK.

If you want to load an image, use `Gtk.Picture()`.
"""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent
CUSTOM_IMAGE = str(
    BASE_DIR.parent.parent.parent.joinpath(
        'data', 'icons', 'br.com.justcode.PyGObject.png',
    )
)


@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    image = Gtk.Template.Child('image')

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.image.set_from_file(filename=CUSTOM_IMAGE)


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject Gtk.Image</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar" id="header_bar">
        <child type="end">
          <object class="GtkMenuButton">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
    <child>
      <object class="GtkBox">
        <property name="orientation">1</property>
        <property name="homogeneous">true</property>
        <property name="margin-top">12</property>
        <property name="margin-end">12</property>
        <property name="margin-bottom">12</property>
        <property name="margin-start">12</property>
        <property name="spacing">12</property>
        <child>
          <object class="GtkButton">
            <property name="label">Button 02</property>
            <property name="child">
              <object class="GtkImage" id="image">
                <style>
                  <class name="lowres-icon"/>
                </style>
              </object>
            </property>
          </object>
        </child>
      </object>
    </child>
  </template>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
    </section>
  </menu>
</interface>
using Gtk 4.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject Gtk.Image';
  default-width: 683;
  default-height: 384;

  [titlebar]
  Gtk.HeaderBar header_bar {
    [end]
    Gtk.MenuButton {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }

  Gtk.Box {
    orientation: vertical;
    homogeneous: true;
    margin-top: 12;
    margin-end: 12;
    margin-bottom: 12;
    margin-start: 12;
    spacing: 12;

    Gtk.Button {
      label: 'Button 02';
      child: 
        Gtk.Image image {
          styles [
            'lowres-icon',
          ]
        }
      ;
    }
  }
}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
  }
}

Gtk.ListBox#

Gtk.ListBox

Gtk.ListBox#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.ListBox"""



import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()


class ExampleWindow(Gtk.ApplicationWindow):
    # Dados que serão inseridos nas linhas do list_box_02.
    itens = ['Item 01', 'Item 02', 'Item 03']

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.set_title(title='Python and GTK: PyGObject Gtk.ListBox')
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append(
            label='Preferences',
            detailed_action='app.preferences',
        )

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        vbox = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=12)
        vbox.set_homogeneous(homogeneous=True)
        vbox.set_margin_top(margin=12)
        vbox.set_margin_end(margin=12)
        vbox.set_margin_bottom(margin=12)
        vbox.set_margin_start(margin=12)
        self.set_child(child=vbox)

        list_box_01 = Gtk.ListBox.new()
        list_box_01.set_selection_mode(mode=Gtk.SelectionMode.NONE)
        vbox.append(child=list_box_01)

        # Loop para criar os widgets.
        for n in range(1, 4):
            list_box_row = Gtk.ListBoxRow.new()
            list_box_row.set_selectable(selectable=False)

            hbox = Gtk.Box.new(
                orientation=Gtk.Orientation.HORIZONTAL, spacing=0)
            # Adicionando container na linha
            list_box_row.set_child(child=hbox)

            label = Gtk.Label.new(str=f'Line 0{n}')
            label.set_margin_top(margin=6)
            label.set_margin_end(margin=6)
            label.set_margin_bottom(margin=6)
            label.set_margin_start(margin=6)
            label.set_xalign(xalign=0)
            label.set_hexpand(expand=True)
            hbox.append(child=label)

            switch = Gtk.Switch.new()
            switch.set_margin_top(margin=6)
            switch.set_margin_end(margin=6)
            switch.set_margin_bottom(margin=6)
            switch.set_margin_start(margin=6)
            hbox.append(child=switch)

            list_box_01.append(child=list_box_row)

        # Criando um segundo ListBox
        list_box_02 = Gtk.ListBox.new()
        list_box_02.connect('row-activated', self.on_row_clicked)
        vbox.append(child=list_box_02)

        # Loop para criar as linhas.
        for item in self.itens:
            label = Gtk.Label.new(str=item)
            label.set_margin_top(6)
            label.set_margin_bottom(6)
            list_box_02.append(child=label)

    def on_row_clicked(self, listbox, listboxrow):
        print(f'Clicou no {self.itens[listboxrow.get_index()]}')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.ListBox."""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent


@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    itens = ['Item 01', 'Item 02', 'Item 03']

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    @Gtk.Template.Callback()
    def on_row_clicked(self, listbox, listboxrow):
        print(f'Clicou no {self.itens[listboxrow.get_index()]}')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject Gtk.ListBox.</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar" id="header_bar">
        <child type="end">
          <object class="GtkMenuButton">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
    <child>
      <object class="GtkBox">
        <property name="orientation">1</property>
        <property name="homogeneous">true</property>
        <property name="margin-top">12</property>
        <property name="margin-end">12</property>
        <property name="margin-bottom">12</property>
        <property name="margin-start">12</property>
        <property name="spacing">12</property>
        <child>
          <object class="GtkListBox">
            <property name="selection-mode">0</property>
            <style>
              <class name="boxed-list"/>
            </style>
            <child>
              <object class="GtkListBoxRow">
                <property name="selectable">false</property>
                <child>
                  <object class="GtkBox">
                    <property name="orientation">0</property>
                    <child>
                      <object class="GtkLabel">
                        <property name="label">Line 01</property>
                        <property name="hexpand">true</property>
                        <property name="xalign">0</property>
                        <property name="margin-top">6</property>
                        <property name="margin-end">6</property>
                        <property name="margin-bottom">6</property>
                        <property name="margin-start">6</property>
                      </object>
                    </child>
                    <child>
                      <object class="GtkSwitch">
                        <property name="margin-top">6</property>
                        <property name="margin-end">6</property>
                        <property name="margin-bottom">6</property>
                        <property name="margin-start">6</property>
                      </object>
                    </child>
                  </object>
                </child>
              </object>
            </child>
            <child>
              <object class="GtkListBoxRow">
                <property name="selectable">false</property>
                <child>
                  <object class="GtkBox">
                    <property name="orientation">0</property>
                    <child>
                      <object class="GtkLabel">
                        <property name="label">Line 02</property>
                        <property name="hexpand">true</property>
                        <property name="xalign">0</property>
                        <property name="margin-top">6</property>
                        <property name="margin-end">6</property>
                        <property name="margin-bottom">6</property>
                        <property name="margin-start">6</property>
                      </object>
                    </child>
                    <child>
                      <object class="GtkSwitch">
                        <property name="margin-top">6</property>
                        <property name="margin-end">6</property>
                        <property name="margin-bottom">6</property>
                        <property name="margin-start">6</property>
                      </object>
                    </child>
                  </object>
                </child>
              </object>
            </child>
            <child>
              <object class="GtkListBoxRow">
                <property name="selectable">false</property>
                <child>
                  <object class="GtkBox">
                    <property name="orientation">0</property>
                    <child>
                      <object class="GtkLabel">
                        <property name="label">Line 03</property>
                        <property name="hexpand">true</property>
                        <property name="xalign">0</property>
                        <property name="margin-top">6</property>
                        <property name="margin-end">6</property>
                        <property name="margin-bottom">6</property>
                        <property name="margin-start">6</property>
                      </object>
                    </child>
                    <child>
                      <object class="GtkSwitch">
                        <property name="margin-top">6</property>
                        <property name="margin-end">6</property>
                        <property name="margin-bottom">6</property>
                        <property name="margin-start">6</property>
                      </object>
                    </child>
                  </object>
                </child>
              </object>
            </child>
          </object>
        </child>
        <child>
          <object class="GtkListBox">
            <property name="selection-mode">1</property>
            <property name="show-separators">true</property>
            <property name="vexpand">true</property>
            <signal name="row-activated" handler="on_row_clicked"/>
            <style>
              <class name="boxed-list"/>
            </style>
            <child>
              <object class="GtkListBoxRow">
                <child>
                  <object class="GtkLabel">
                    <property name="label">Line 01</property>
                  </object>
                </child>
              </object>
            </child>
            <child>
              <object class="GtkListBoxRow">
                <child>
                  <object class="GtkLabel">
                    <property name="label">Line 02</property>
                  </object>
                </child>
              </object>
            </child>
            <child>
              <object class="GtkListBoxRow">
                <child>
                  <object class="GtkLabel">
                    <property name="label">Line 03</property>
                  </object>
                </child>
              </object>
            </child>
          </object>
        </child>
      </object>
    </child>
  </template>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
    </section>
  </menu>
</interface>
using Gtk 4.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject Gtk.ListBox.';
  default-width: 683;
  default-height: 384;

  [titlebar]
  Gtk.HeaderBar header_bar {
    [end]
    Gtk.MenuButton {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }

  Gtk.Box {
    orientation: vertical;
    homogeneous: true;
    margin-top: 12;
    margin-end: 12;
    margin-bottom: 12;
    margin-start: 12;
    spacing: 12;

    Gtk.ListBox {
      selection-mode: none;
        styles [
          'boxed-list',
        ]
      Gtk.ListBoxRow{
        selectable: false;
        Gtk.Box {
          orientation: horizontal;
          Gtk.Label {
            label: 'Line 01';
            hexpand: true;
            xalign: 0;
            margin-top: 6;
            margin-end: 6;
            margin-bottom: 6;
            margin-start: 6;
          }
          Gtk.Switch{
            margin-top: 6;
            margin-end: 6;
            margin-bottom: 6;
            margin-start: 6;
          }
        }
      }
      Gtk.ListBoxRow{
        selectable: false;
        Gtk.Box {
          orientation: horizontal;
          Gtk.Label {
            label: 'Line 02';
            hexpand: true;
            xalign: 0;
            margin-top: 6;
            margin-end: 6;
            margin-bottom: 6;
            margin-start: 6;
          }
          Gtk.Switch{
            margin-top: 6;
            margin-end: 6;
            margin-bottom: 6;
            margin-start: 6;
          }
        }
      }
      Gtk.ListBoxRow{
        selectable: false;
        Gtk.Box {
          orientation: horizontal;
          Gtk.Label {
            label: 'Line 03';
            hexpand: true;
            xalign: 0;
            margin-top: 6;
            margin-end: 6;
            margin-bottom: 6;
            margin-start: 6;
          }
          Gtk.Switch{
            margin-top: 6;
            margin-end: 6;
            margin-bottom: 6;
            margin-start: 6;
          }
        }
      }
    }

    Gtk.ListBox {
      selection-mode: single;
      show-separators: true;
      vexpand: true;
      row-activated => $on_row_clicked();
      styles [
        'boxed-list',
      ]
      Gtk.ListBoxRow {
        Gtk.Label {
          label: 'Line 01';
        }
      }
      Gtk.ListBoxRow {
        Gtk.Label {
          label: 'Line 02';
        }
      }
      Gtk.ListBoxRow {
        Gtk.Label {
          label: 'Line 03';
        }
      }
    }
  }
}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
  }
}

Gtk.ListView#

Aviso

Criar código em Python.

Gtk.ListView

Gtk.ListView#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.ListView."""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent


@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    @Gtk.Template.Callback()
    def on_list_view_row_activate(self, list_view, index):
        single_selection = list_view.get_model()
        string_object = single_selection.get_selected_item()
        print(index)
        print(single_selection.get_selected())
        print(string_object.get_string())


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject Gtk.ListView</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar" id="header_bar">
        <child type="end">
          <object class="GtkMenuButton">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
    <child>
      <object class="GtkBox">
        <property name="orientation">1</property>
        <property name="margin-top">12</property>
        <property name="margin-end">12</property>
        <property name="margin-bottom">12</property>
        <property name="margin-start">12</property>
        <property name="spacing">12</property>
        <child>
          <object class="GtkListView">
            <signal name="activate" handler="on_list_view_row_activate"/>
            <property name="factory">
              <object class="GtkBuilderListItemFactory">
                <property name="bytes"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <template class="GtkListItem">
    <property name="child">
      <object class="GtkLabel">
        <binding name="label">
          <lookup name="string" type="GtkStringObject">
            <lookup name="item" type="GtkListItem">
              <constant>GtkListItem</constant>
            </lookup>
          </lookup>
        </binding>
      </object>
    </property>
  </template>
</interface>]]></property>
              </object>
            </property>
            <property name="model">
              <object class="GtkSingleSelection">
                <property name="model">
                  <object class="GtkStringList">
                    <items>
                      <item>Item 01</item>
                      <item>Item 02</item>
                      <item>Item 03</item>
                    </items>
                  </object>
                </property>
              </object>
            </property>
          </object>
        </child>
      </object>
    </child>
  </template>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
    </section>
  </menu>
</interface>
using Gtk 4.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject Gtk.ListView';
  default-width: 683;
  default-height: 384;

  [titlebar]
  Gtk.HeaderBar header_bar {
    [end]
    Gtk.MenuButton {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }

  Gtk.Box {
    orientation: vertical;
    margin-top: 12;
    margin-end: 12;
    margin-bottom: 12;
    margin-start: 12;
    spacing: 12;

    Gtk.ListView {
      activate => $on_list_view_row_activate();
      factory: Gtk.BuilderListItemFactory {
        template Gtk.ListItem {
          child: Gtk.Label {
            label: bind template.item as <StringObject>.string;
          };
        }
      };
      model: Gtk.SingleSelection {
        model: Gtk.StringList {
          strings [ 'Item 01', 'Item 02', 'Item 03' ]
        };
      };
    }
  }
}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
  }
}

Gtk.MenuButton#

Gtk.MenuButton

Gtk.MenuButton#

Erro:

_gtk_css_corner_value_get_y: assertion 'corner->class == &GTK_CSS_VALUE_CORNER' failed
# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.MenuButton"""



import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()


class ExampleWindow(Gtk.ApplicationWindow):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.set_title(title='Python and GTK: PyGObject Gtk.MenuButton')
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_model = Gio.Menu()
        menu_model.append(label='Preferences', detailed_action='app.preferences')

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_model)
        header_bar.pack_end(child=menu_button)

        popover = menu_button.get_popover()
        popover.set_offset(x_offset=-50, y_offset=0)

        vbox = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=12)
        vbox.set_homogeneous(homogeneous=True)
        vbox.set_margin_top(margin=12)
        vbox.set_margin_end(margin=12)
        vbox.set_margin_bottom(margin=12)
        vbox.set_margin_start(margin=12)
        self.set_child(child=vbox)

        # Criando uma seção.
        section = Gio.Menu.new()
        section.append(label='Item 01', detailed_action='win.item1')
        section.append(label='Item 02', detailed_action='win.item2')
        menu_model.append_section(label='Section title', section=section)
        self.create_win_action(
            name='item1', callback=self.on_menu_item_clicked)
        self.create_win_action(
            name='item2', callback=self.on_menu_item_clicked)

        # Criando um submenu.
        submenu = Gio.Menu.new()
        submenu.append(label='Item 03', detailed_action=f'win.item3')
        submenu.append(label='Item 04', detailed_action=f'win.item4')
        menu_model.append_submenu(label='Sub-menu title', submenu=submenu)
        self.create_win_action(
            name='item3', callback=self.on_menu_item_clicked)
        self.create_win_action(
            name='item4', callback=self.on_menu_item_clicked)

    def on_menu_item_clicked(self, action, param):
        print(action.get_name())

    def create_win_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'win.{name}',
                accels=shortcuts,
            )


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.MenuButton."""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent


@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    menu_button = Gtk.Template.Child(name='menu_button')

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        popover = self.menu_button.get_popover()
        popover.set_offset(x_offset=-50, y_offset=0)

        self.create_win_action(
            name='item1', callback=self.on_menu_item_clicked)
        self.create_win_action(
            name='item2', callback=self.on_menu_item_clicked)
        self.create_win_action(
            name='item3', callback=self.on_menu_item_clicked)
        self.create_win_action(
            name='item4', callback=self.on_menu_item_clicked)

    def on_menu_item_clicked(self, action, param):
        print(action.get_name())

    def create_win_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'win.{name}',
                accels=shortcuts,
            )


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject Gtk.MenuButton</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar" id="header_bar">
        <child type="end">
          <object class="GtkMenuButton" id="menu_button">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
  </template>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
    </section>
    <section>
      <attribute name="label" translatable="true">Section title</attribute>
      <item>
        <attribute name="label">Item 01</attribute>
        <attribute name="action">win.item1</attribute>
      </item>
      <item>
        <attribute name="label">Item 02</attribute>
        <attribute name="action">win.item2</attribute>
      </item>
    </section>
    <submenu>
      <attribute name="label" translatable="true">Sub-menu title</attribute>
      <item>
        <attribute name="label" translatable="true">Item 03</attribute>
        <attribute name="action">win.item3</attribute>
      </item>
      <item>
        <attribute name="label">Item 04</attribute>
        <attribute name="action">win.item4</attribute>
      </item>
    </submenu>
  </menu>
</interface>
using Gtk 4.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject Gtk.MenuButton';
  default-width: 683;
  default-height: 384;

  [titlebar]
  Gtk.HeaderBar header_bar {
    [end]
    Gtk.MenuButton menu_button {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }
}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
  }
  section {
    label: _('Section title');
    // Shorthand (forma abreviada).
    item ('Item 01', 'win.item1')
    item ('Item 02', 'win.item2')

  }
  submenu {
    label: _('Sub-menu title');
    item {
      label: _('Item 03');
      action: 'win.item3';
    }
    item ('Item 04', 'win.item4')
  }
}

Gtk.Overlay#

Gtk.Overlay

Gtk.Overlay#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.Overlay"""



import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()


class ExampleWindow(Gtk.ApplicationWindow):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.set_title(title='Python and GTK: PyGObject Gtk.Overlay')
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append(
            label='Preferences',
            detailed_action='app.preferences',
        )

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        overlay = Gtk.Overlay.new()
        self.set_child(child=overlay)

        vbox = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=12)
        vbox.set_homogeneous(homogeneous=True)
        vbox.set_margin_top(margin=12)
        vbox.set_margin_end(margin=12)
        vbox.set_margin_bottom(margin=12)
        vbox.set_margin_start(margin=12)
        overlay.set_child(child=vbox)

        button = Gtk.Button.new_with_label(
            label='This Button is below the others',
        )
        vbox.append(child=button)

        button_go_previous = Gtk.Button.new_from_icon_name(
            icon_name='go-previous',
        )
        button_go_previous.set_halign(align=Gtk.Align.START)
        button_go_previous.set_valign(align=Gtk.Align.CENTER)
        overlay.add_overlay(widget=button_go_previous)

        button_go_next = Gtk.Button.new_from_icon_name(
            icon_name='go-next',
        )
        button_go_next.set_halign(align=Gtk.Align.END)
        button_go_next.set_valign(align=Gtk.Align.CENTER)
        overlay.add_overlay(widget=button_go_next)


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.Overlay."""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent


@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject Gtk.Overlay.</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar" id="header_bar">
        <child type="end">
          <object class="GtkMenuButton">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
    <child>
      <object class="GtkOverlay" id="overlay">
        <child type="overlay">
          <object class="GtkBox">
            <property name="orientation">1</property>
            <property name="homogeneous">true</property>
            <property name="margin-top">12</property>
            <property name="margin-end">12</property>
            <property name="margin-bottom">12</property>
            <property name="margin-start">12</property>
            <property name="spacing">12</property>
            <child>
              <object class="GtkButton">
                <property name="label">This Button is below the others</property>
              </object>
            </child>
          </object>
        </child>
        <child type="overlay">
          <object class="GtkButton">
            <property name="icon-name">go-previous</property>
            <property name="halign">1</property>
            <property name="valign">3</property>
          </object>
        </child>
        <child type="overlay">
          <object class="GtkButton">
            <property name="icon-name">go-next</property>
            <property name="halign">2</property>
            <property name="valign">3</property>
          </object>
        </child>
      </object>
    </child>
  </template>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
    </section>
  </menu>
</interface>
using Gtk 4.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject Gtk.Overlay.';
  default-width: 683;
  default-height: 384;

  [titlebar]
  Gtk.HeaderBar header_bar {
    [end]
    Gtk.MenuButton {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }

  Gtk.Overlay overlay {
    [overlay]
    Gtk.Box {
      orientation: vertical;
      homogeneous: true;
      margin-top: 12;
      margin-end: 12;
      margin-bottom: 12;
      margin-start: 12;
      spacing: 12;
    
      Gtk.Button {
        label: 'This Button is below the others';
      }
    }
    
    [overlay]
    Gtk.Button {
      icon-name: 'go-previous';
      halign: start;
      valign: center;
    }

    [overlay]
    Gtk.Button {
      icon-name: 'go-next';
      halign: end;
      valign: center;
    }
  }
}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
  }
}

Pango tags#

Pango tags

Pango tags#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Pango."""

import pathlib



import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()


SRC_DIR = BASE_DIR.parent.parent
TEMPLATE = SRC_DIR.joinpath('data', 'pango', 'template.txt')

with open(TEMPLATE, mode='r', encoding='utf8') as f:
    text = f.read()
    f.close()


class ExampleWindow(Gtk.ApplicationWindow):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.set_title(title='Python and GTK: PyGObject Pango.')
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append(
            label='Preferences',
            detailed_action='app.preferences',
        )

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        vbox = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=12)
        vbox.set_homogeneous(homogeneous=True)
        vbox.set_margin_top(margin=12)
        vbox.set_margin_end(margin=12)
        vbox.set_margin_bottom(margin=12)
        vbox.set_margin_start(margin=12)
        self.set_child(child=vbox)

        scrolled_window = Gtk.ScrolledWindow.new()
        vbox.append(child=scrolled_window)

        text_buffer = Gtk.TextBuffer.new()
        text_buffer.insert_markup(
            iter=text_buffer.get_end_iter(),
            markup=text,
            len=-1,
        )

        text_view = Gtk.TextView.new_with_buffer(buffer=text_buffer)
        scrolled_window.set_child(child=text_view)


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject PyGObject Pango ui file."""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent
TEMPLATE = BASE_DIR.parent.parent.parent.joinpath('data', 'pango', 'template.txt')

with open(TEMPLATE, mode='r', encoding='utf8') as f:
    text = f.read()
    f.close()

@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    text_buffer = Gtk.Template.Child('text_buffer')

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.text_buffer.insert_markup(
            iter=self.text_buffer.get_end_iter(),
            markup=text,
            len=-1,
        )


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject PyGObject Pango ui file</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar" id="header_bar">
        <child type="end">
          <object class="GtkMenuButton">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
    <child>
      <object class="GtkBox">
        <property name="orientation">1</property>
        <property name="homogeneous">true</property>
        <property name="margin-top">12</property>
        <property name="margin-end">12</property>
        <property name="margin-bottom">12</property>
        <property name="margin-start">12</property>
        <property name="spacing">12</property>
        <child>
          <object class="GtkScrolledWindow">
            <child>
              <object class="GtkTextView">
                <property name="buffer">text_buffer</property>
              </object>
            </child>
          </object>
        </child>
      </object>
    </child>
  </template>
  <object class="GtkTextBuffer" id="text_buffer"></object>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
    </section>
  </menu>
</interface>
using Gtk 4.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject PyGObject Pango ui file';
  default-width: 683;
  default-height: 384;

  [titlebar]
  Gtk.HeaderBar header_bar {
    [end]
    Gtk.MenuButton {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }

  Gtk.Box {
    orientation: vertical;
    homogeneous: true;
    margin-top: 12;
    margin-end: 12;
    margin-bottom: 12;
    margin-start: 12;
    spacing: 12;

    Gtk.ScrolledWindow {
      Gtk.TextView {
        buffer: text_buffer;
      }
    }
  }
}

Gtk.TextBuffer text_buffer {}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
  }
}

Gtk.Picture#

Gtk.Picture

Gtk.Picture#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.Picture"""

import pathlib



import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()


SRC_DIR = BASE_DIR.parent.parent
PICTURE = str(SRC_DIR.joinpath('data', 'images', 'thunderstorm.jpg'))


class ExampleWindow(Gtk.ApplicationWindow):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.set_title(title='Python and GTK: PyGObject Gtk.Picture')
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append(
            label='Preferences',
            detailed_action='app.preferences',
        )

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        vbox = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=0)
        self.set_child(child=vbox)

        gio_file = Gio.File.new_for_path(PICTURE)

        picture = Gtk.Picture.new_for_file(file=gio_file)
        picture.set_content_fit(content_fit=Gtk.ContentFit.FILL)
        vbox.append(child=picture)


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.Picture."""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent
PICTURE = str(BASE_DIR.parent.parent.parent.joinpath(
    'data', 'images', 'thunderstorm.jpg',
    ),
)


@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    picture = Gtk.Template.Child('picture')

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        gio_file = Gio.File.new_for_path(PICTURE)
        self.picture.set_file(file=gio_file)


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject Gtk.Picture</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar" id="header_bar">
        <child type="end">
          <object class="GtkMenuButton">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
    <child>
      <object class="GtkBox">
        <property name="orientation">1</property>
        <child>
          <object class="GtkPicture" id="picture">
            <property name="content-fit">0</property>
          </object>
        </child>
      </object>
    </child>
  </template>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
    </section>
  </menu>
</interface>
using Gtk 4.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject Gtk.Picture';
  default-width: 683;
  default-height: 384;

  [titlebar]
  Gtk.HeaderBar header_bar {
    [end]
    Gtk.MenuButton {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }

  Gtk.Box {
    orientation: vertical;

    Gtk.Picture picture {
      content-fit: fill;
    }
  }
}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
  }
}

Gtk.PrintOperation#

Gtk.PrintOperation

Gtk.PrintOperation#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.PrintOperation"""

import pathlib



import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk, Pango, PangoCairo

Adw.init()


PDF_FILE = str(BASE_DIR.joinpath('file-name.pdf'))

TEXT = """<span size="xx-large">Lorem</span>
Lorem <b>ipsum</b> <span foreground="red">dolor</span> <big>sit</big> amet,
<i>consectetur</i> adipiscing <s>elit</s>, sed do 
<span background="green">eiusmod</span> tempor incididunt 
<small>ut</small> <tt>labore</tt> et dolore magna aliqua.\n"""


class ExampleWindow(Gtk.ApplicationWindow):
    pango_layout = None

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.set_title(title='Python and GTK: PyGObject Gtk.PrintOperation().')
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append(
            label='Preferences',
            detailed_action='app.preferences',
        )

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        vbox = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=12)
        vbox.set_margin_top(margin=12)
        vbox.set_margin_end(margin=12)
        vbox.set_margin_bottom(margin=12)
        vbox.set_margin_start(margin=12)
        self.set_child(child=vbox)

        # Auxiliary variable with paper settings.
        self.page_setup = self._page_setup()
        # self.page_setup = self.custom_page_setup()

        # Variable for the paper configuration dialog:
        self.print_settings = Gtk.PrintSettings.new()

        # Text buffer.
        self.text_buffer = Gtk.TextBuffer.new()

        # Adding rendered text to Gtk.TextView.
        text_buffer_iter = self.text_buffer.get_end_iter()
        self.text_buffer.insert_markup(
            iter=text_buffer_iter,
            markup=TEXT,
            len=-1,
        )

        text_view = Gtk.TextView.new_with_buffer(buffer=self.text_buffer)
        text_view.set_vexpand(expand=True)
        vbox.append(child=text_view)

        hbox = Gtk.Box.new(orientation=Gtk.Orientation.HORIZONTAL, spacing=12)
        hbox.set_halign(align=Gtk.Align.CENTER)
        vbox.append(child=hbox)

        button_print_dialog = Gtk.Button.new_with_label(label='Print')
        button_print_dialog.connect(
            'clicked',
            self.on_button_open_print_dialog_clicked,
        )
        hbox.append(child=button_print_dialog)

        button_open_preview = Gtk.Button.new_with_label(label='View')
        button_open_preview.connect(
            'clicked',
            self.on_button_open_preview_clicked,
        )
        hbox.append(child=button_open_preview)

        button_page_setup_dialog = Gtk.Button.new_with_label(label='Page setup')
        button_page_setup_dialog.connect(
            'clicked',
            self.on_button_open_page_setup_dialog_clicked,
        )
        hbox.append(child=button_page_setup_dialog)

        button_export_pdf = Gtk.Button.new_with_label('Export to PDF')
        button_export_pdf.connect(
            'clicked',
            self.on_button_export_to_pdf_clicked,
        )
        hbox.append(child=button_export_pdf)

    def on_begin_print(self, print_operation, print_context):
        self.pango_layout = print_context.create_pango_layout()
        self.pango_layout.set_markup(text=TEXT, length=-1)
        self.pango_layout.set_font_description(
            desc=Pango.FontDescription('Arial 12'),
        )

    def on_draw_page(self, print_operation, print_context, page_nr):
        cairo_context = print_context.get_cairo_context()
        cairo_context.set_source_rgb(0, 0, 0)
        PangoCairo.show_layout(cr=cairo_context, layout=self.pango_layout)

    def on_button_open_print_dialog_clicked(self, widget):
        print_operation = Gtk.PrintOperation.new()
        print_operation.set_n_pages(n_pages=1)
        print_operation.set_print_settings(print_settings=self.print_settings)
        print_operation.set_default_page_setup(
            default_page_setup=self.page_setup)
        print_operation.connect('begin-print', self.on_begin_print)
        print_operation.connect('draw-page', self.on_draw_page)

        response = print_operation.run(
            parent=self,
            action=Gtk.PrintOperationAction.PRINT_DIALOG,
        )
        self._check_print_dialog_response(response=response)

    def on_button_open_preview_clicked(self, widget):
        print_operation = Gtk.PrintOperation.new()
        print_operation.set_n_pages(n_pages=1)
        print_operation.set_print_settings(print_settings=self.print_settings)
        print_operation.set_default_page_setup(
            default_page_setup=self.page_setup)
        print_operation.connect('begin-print', self.on_begin_print)
        print_operation.connect('draw-page', self.on_draw_page)

        response = print_operation.run(
            action=Gtk.PrintOperationAction.PREVIEW, parent=self)
        self._check_print_dialog_response(response=response)

    def on_button_open_page_setup_dialog_clicked(self, widget):
        print(self.page_setup.get_page_width(unit=Gtk.Unit.MM))
        self.page_setup = Gtk.print_run_page_setup_dialog(
            parent=self,
            page_setup=self.page_setup,
            settings=self.print_settings,
        )
        print(self.page_setup.get_page_width(unit=Gtk.Unit.MM))

    def on_button_export_to_pdf_clicked(self, widget):
        print_operation = Gtk.PrintOperation.new()
        print_operation.set_n_pages(n_pages=1)
        print_operation.set_print_settings(print_settings=self.print_settings)
        print_operation.set_default_page_setup(
            default_page_setup=self.page_setup)
        print_operation.connect('begin-print', self.on_begin_print)
        print_operation.connect('draw-page', self.on_draw_page)
        print_operation.set_export_filename(PDF_FILE)
        response = print_operation.run(
            action=Gtk.PrintOperationAction.EXPORT, parent=self)
        if response == Gtk.PrintOperationResult.APPLY:
            print('Arquivo exportado com sucesso')

    def _page_setup(self):
        paper_size = Gtk.PaperSize.new(name=Gtk.PAPER_NAME_A4)
        page_setup = Gtk.PageSetup.new()
        page_setup.set_paper_size_and_default_margins(size=paper_size)
        return page_setup

    def _custom_page_setup(self):
        paper_size = Gtk.PaperSize.new(name=Gtk.PAPER_NAME_A4)
        custom_page_setup = Gtk.PageSetup.new()
        custom_page_setup.set_top_margin(margin=20, unit=Gtk.Unit.MM)
        custom_page_setup.set_left_margin(margin=20, unit=Gtk.Unit.MM)
        custom_page_setup.set_orientation(
            orientation=Gtk.PageOrientation.PORTRAIT,
        )
        custom_page_setup.set_paper_size(size=paper_size)
        return custom_page_setup

    def _check_print_dialog_response(self, response):
        if response == Gtk.PrintOperationResult.ERROR:
            print('ERROR')
        elif response == Gtk.PrintOperationResult.APPLY:
            print('APPLY')
        elif response == Gtk.PrintOperationResult.CANCEL:
            print('CANCEL')
        elif response == Gtk.PrintOperationResult.IN_PROGRESS:
            print('IN_PROGRESS')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject PyGObject Gtk.PrintOperation ui file."""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent
PDF_FILE = str(BASE_DIR.joinpath('file-name.pdf'))

TEXT = """<span size="xx-large">Lorem</span>
Lorem <b>ipsum</b> <span foreground="red">dolor</span> <big>sit</big> amet,
<i>consectetur</i> adipiscing <s>elit</s>, sed do 
<span background="green">eiusmod</span> tempor incididunt 
<small>ut</small> <tt>labore</tt> et dolore magna aliqua.\n"""


@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    pango_layout = None

    text_buffer = Gtk.Template.Child('text_buffer')

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        # Auxiliary variable with paper settings.
        self.page_setup = self._page_setup()
        # self.page_setup = self.custom_page_setup()

        # Variable for the paper configuration dialog:
        self.print_settings = Gtk.PrintSettings.new()

        # Adding rendered text to Gtk.TextView.
        text_buffer_iter = self.text_buffer.get_end_iter()
        self.text_buffer.insert_markup(
            iter=text_buffer_iter,
            markup=TEXT,
            len=-1,
        )

    @Gtk.Template.Callback()
    def on_begin_print(self, print_operation, print_context):
        self.pango_layout = print_context.create_pango_layout()
        self.pango_layout.set_markup(text=TEXT, length=-1)
        self.pango_layout.set_font_description(
            desc=Pango.FontDescription('Arial 12'),
        )

    @Gtk.Template.Callback()
    def on_draw_page(self, print_operation, print_context, page_nr):
        cairo_context = print_context.get_cairo_context()
        cairo_context.set_source_rgb(0, 0, 0)
        PangoCairo.show_layout(cr=cairo_context, layout=self.pango_layout)

    @Gtk.Template.Callback()
    def on_button_open_print_dialog_clicked(self, widget):
        print_operation = Gtk.PrintOperation.new()
        print_operation.set_n_pages(n_pages=1)
        print_operation.set_print_settings(print_settings=self.print_settings)
        print_operation.set_default_page_setup(
            default_page_setup=self.page_setup)
        print_operation.connect('begin-print', self.on_begin_print)
        print_operation.connect('draw-page', self.on_draw_page)

        response = print_operation.run(
            parent=self,
            action=Gtk.PrintOperationAction.PRINT_DIALOG,
        )
        self._check_print_dialog_response(response=response)

    @Gtk.Template.Callback()
    def on_button_open_preview_clicked(self, widget):
        print_operation = Gtk.PrintOperation.new()
        print_operation.set_n_pages(n_pages=1)
        print_operation.set_print_settings(print_settings=self.print_settings)
        print_operation.set_default_page_setup(
            default_page_setup=self.page_setup)
        print_operation.connect('begin-print', self.on_begin_print)
        print_operation.connect('draw-page', self.on_draw_page)

        response = print_operation.run(
            action=Gtk.PrintOperationAction.PREVIEW, parent=self)
        self._check_print_dialog_response(response=response)

    @Gtk.Template.Callback()
    def on_button_open_page_setup_dialog_clicked(self, widget):
        print(self.page_setup.get_page_width(unit=Gtk.Unit.MM))
        self.page_setup = Gtk.print_run_page_setup_dialog(
            parent=self,
            page_setup=self.page_setup,
            settings=self.print_settings,
        )
        print(self.page_setup.get_page_width(unit=Gtk.Unit.MM))

    @Gtk.Template.Callback()
    def on_button_export_to_pdf_clicked(self, widget):
        print_operation = Gtk.PrintOperation.new()
        print_operation.set_n_pages(n_pages=1)
        print_operation.set_print_settings(print_settings=self.print_settings)
        print_operation.set_default_page_setup(
            default_page_setup=self.page_setup)
        print_operation.connect('begin-print', self.on_begin_print)
        print_operation.connect('draw-page', self.on_draw_page)
        print_operation.set_export_filename(PDF_FILE)
        response = print_operation.run(
            action=Gtk.PrintOperationAction.EXPORT, parent=self)
        if response == Gtk.PrintOperationResult.APPLY:
            print('Arquivo exportado com sucesso')

    def _page_setup(self):
        paper_size = Gtk.PaperSize.new(name=Gtk.PAPER_NAME_A4)
        page_setup = Gtk.PageSetup.new()
        page_setup.set_paper_size_and_default_margins(size=paper_size)
        return page_setup

    def _custom_page_setup(self):
        paper_size = Gtk.PaperSize.new(name=Gtk.PAPER_NAME_A4)
        custom_page_setup = Gtk.PageSetup.new()
        custom_page_setup.set_top_margin(margin=20, unit=Gtk.Unit.MM)
        custom_page_setup.set_left_margin(margin=20, unit=Gtk.Unit.MM)
        custom_page_setup.set_orientation(
            orientation=Gtk.PageOrientation.PORTRAIT,
        )
        custom_page_setup.set_paper_size(size=paper_size)
        return custom_page_setup

    def _check_print_dialog_response(self, response):
        if response == Gtk.PrintOperationResult.ERROR:
            print('ERROR')
        elif response == Gtk.PrintOperationResult.APPLY:
            print('APPLY')
        elif response == Gtk.PrintOperationResult.CANCEL:
            print('CANCEL')
        elif response == Gtk.PrintOperationResult.IN_PROGRESS:
            print('IN_PROGRESS')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject PyGObject Gtk.PrintOperation</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar" id="header_bar">
        <child type="end">
          <object class="GtkMenuButton">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
    <child>
      <object class="GtkBox">
        <property name="orientation">1</property>
        <property name="margin-top">12</property>
        <property name="margin-end">12</property>
        <property name="margin-bottom">12</property>
        <property name="margin-start">12</property>
        <property name="spacing">12</property>
        <child>
          <object class="GtkTextView">
            <property name="buffer">text_buffer</property>
            <property name="vexpand">true</property>
          </object>
        </child>
        <child>
          <object class="GtkBox">
            <property name="orientation">0</property>
            <property name="halign">3</property>
            <property name="spacing">12</property>
            <child>
              <object class="GtkButton">
                <property name="label">Print</property>
                <signal name="clicked" handler="on_button_open_print_dialog_clicked"/>
              </object>
            </child>
            <child>
              <object class="GtkButton">
                <property name="label">View</property>
                <signal name="clicked" handler="on_button_open_preview_clicked"/>
              </object>
            </child>
            <child>
              <object class="GtkButton">
                <property name="label">Page setup</property>
                <signal name="clicked" handler="on_button_open_page_setup_dialog_clicked"/>
              </object>
            </child>
            <child>
              <object class="GtkButton">
                <property name="label">Export to PDF</property>
                <signal name="clicked" handler="on_button_export_to_pdf_clicked"/>
              </object>
            </child>
          </object>
        </child>
      </object>
    </child>
  </template>
  <object class="GtkTextBuffer" id="text_buffer"></object>
  <object class="GtkPrintOperation" id="print_operation">
    <signal name="begin-print" handler="on_begin_print"/>
    <signal name="draw-page" handler="on_draw_page"/>
  </object>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
    </section>
  </menu>
</interface>
using Gtk 4.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject PyGObject Gtk.PrintOperation';
  default-width: 683;
  default-height: 384;

  [titlebar]
  Gtk.HeaderBar header_bar {
    [end]
    Gtk.MenuButton {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }

  Gtk.Box {
    orientation: vertical;
    margin-top: 12;
    margin-end: 12;
    margin-bottom: 12;
    margin-start: 12;
    spacing: 12;

    Gtk.TextView {
      buffer: text_buffer;
      vexpand: true;
    }

    Gtk.Box {
      orientation: horizontal;
      halign: center;
      spacing: 12;

      Gtk.Button {
        label: 'Print';
        clicked => $on_button_open_print_dialog_clicked();
      }
      Gtk.Button {
        label: 'View';
        clicked => $on_button_open_preview_clicked();
      }
      Gtk.Button {
        label: 'Page setup';
        clicked => $on_button_open_page_setup_dialog_clicked();
      }
      Gtk.Button {
        label: 'Export to PDF';
        clicked => $on_button_export_to_pdf_clicked();
      }
    }
  }
}

Gtk.TextBuffer text_buffer {}

Gtk.PrintOperation print_operation {
  begin-print => $on_begin_print();
  draw-page => $on_draw_page();
}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
  }
}


Gtk.ShortcutsWindow#

Aviso

Criar código em Python.

Gtk.ShortcutsWindow

Gtk.ShortcutsWindow#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.ShortcutsWindow."""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent


@Gtk.Template(filename=str(BASE_DIR.joinpath('ShortcutsWindow.ui')))
class ShortcutsWindow(Gtk.ShortcutsWindow):
    __gtype_name__ = 'ShortcutsWindow'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)




@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)
        self.create_action(
            'shortcuts-window',
            self.on_shortcuts_window_action, ['<primary>1'],
        )

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def on_shortcuts_window_action(self, action, param):
        shortcuts_window = ShortcutsWindow(
            transient_for=self.get_active_window())
        shortcuts_window.present()

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject Gtk.ShortcutsWindow</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar" id="header_bar">
        <child type="end">
          <object class="GtkMenuButton">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
  </template>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
      <item>
        <attribute name="label" translatable="true">Shortcuts</attribute>
        <attribute name="action">app.shortcuts-window</attribute>
      </item>
    </section>
  </menu>
</interface>
using Gtk 4.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject Gtk.ShortcutsWindow';
  default-width: 683;
  default-height: 384;

  [titlebar]
  Gtk.HeaderBar header_bar {
    [end]
    Gtk.MenuButton {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }
}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
    item {
      label: _('Shortcuts');
      action: 'app.shortcuts-window';
    }
  }
}

Signals and slots#

Signals and slots

Signals and slots#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Signal e Slots."""



import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()


class ExampleWindow(Gtk.ApplicationWindow):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.set_title(title='Python and GTK: PyGObject Signal e Slots')
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append(
            label='Preferences',
            detailed_action='app.preferences',
        )

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        vbox = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=6)
        vbox.set_margin_top(margin=12)
        vbox.set_margin_end(margin=12)
        vbox.set_margin_bottom(margin=12)
        vbox.set_margin_start(margin=12)
        self.set_child(child=vbox)

        self.entry = Gtk.Entry.new()
        self.entry.set_placeholder_text(text='Type something.')
        vbox.append(child=self.entry)

        self.label = Gtk.Label.new(str='This text will be changed!')
        self.label.set_vexpand(expand=True)
        vbox.append(child=self.label)

        button = Gtk.Button.new_with_label(label='Click here')
        button.connect('clicked', self._on_button_clicked)
        vbox.append(child=button)

    def _on_button_clicked(self, widget):
        if self.entry.get_text().split():
            self.label.set_label(str=self.entry.get_text())
        else:
            self.label.set_label(str='Type something in the field above!')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Signal e Slots ui file."""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent


@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    entry = Gtk.Template.Child(name='entry')
    label = Gtk.Template.Child(name='label')

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    @Gtk.Template.Callback()
    def on_button_clicked(self, widget):
        if self.entry.get_text().split():
            self.label.set_label(str=self.entry.get_text())
        else:
            self.label.set_label(str='Type something in the field above!')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print(action)
        print(param)
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject Gtk.Box() vertical ui file.</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar" id="header_bar">
        <child type="end">
          <object class="GtkMenuButton">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
    <child>
      <object class="GtkBox">
        <property name="orientation">1</property>
        <property name="margin-top">12</property>
        <property name="margin-end">12</property>
        <property name="margin-bottom">12</property>
        <property name="margin-start">12</property>
        <property name="spacing">12</property>
        <child>
          <object class="GtkEntry" id="entry">
            <property name="placeholder-text">Type something.</property>
          </object>
        </child>
        <child>
          <object class="GtkLabel" id="label">
            <property name="label">This text will be changed!</property>
            <property name="vexpand">true</property>
          </object>
        </child>
        <child>
          <object class="GtkButton">
            <property name="label">Button 01</property>
            <signal name="clicked" handler="on_button_clicked"/>
          </object>
        </child>
      </object>
    </child>
  </template>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
    </section>
  </menu>
</interface>
using Gtk 4.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject Gtk.Box() vertical ui file.';
  default-width: 683;
  default-height: 384;

  [titlebar]
  Gtk.HeaderBar header_bar {
    [end]
    Gtk.MenuButton {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }

  Gtk.Box {
    orientation: vertical;
    margin-top: 12;
    margin-end: 12;
    margin-bottom: 12;
    margin-start: 12;
    spacing: 12;

    Gtk.Entry entry {
      placeholder-text: 'Type something.';
    }

    Gtk.Label label {
      label: 'This text will be changed!';
      vexpand: true;
    }

    Gtk.Button {
      label: 'Button 01';
      clicked => $on_button_clicked();
    }
  }
}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
  }
}

Gtk.StackSidebar#

Gtk.StackSidebar

Gtk.StackSidebar#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.StackSidebar"""



import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()


class ExampleWindow(Gtk.ApplicationWindow):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.set_title(title='Python and GTK: PyGObject Gtk.StackSidebar')
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append(
            label='Preferences',
            detailed_action='app.preferences',
        )

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        hbox = Gtk.Box.new(orientation=Gtk.Orientation.HORIZONTAL, spacing=12)
        hbox.set_margin_top(margin=12)
        hbox.set_margin_end(margin=12)
        hbox.set_margin_bottom(margin=12)
        hbox.set_margin_start(margin=12)
        self.set_child(child=hbox)

        page1 = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=6)
        for n in range(5):
            button = Gtk.Button.new_with_label(label=f'Button {n}')
            page1.append(child=button)

        page2 = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=6)
        for n in range(5):
            label = Gtk.Label.new(str=f'Line {n}')
            page2.append(child=label)

        stack = Gtk.Stack.new()
        stack.add_titled(child=page1, name='page1', title='Page 1')
        stack.add_titled(child=page2, name='page2', title='Page 2')
        hbox.append(child=stack)

        stack_sidebar = Gtk.StackSidebar.new()
        stack_sidebar.set_stack(stack=stack)
        hbox.prepend(child=stack_sidebar)


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.StackSidebar."""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent


@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject Gtk.StackSidebar.</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar" id="header_bar">
        <child type="end">
          <object class="GtkMenuButton">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
    <child>
      <object class="GtkBox">
        <property name="orientation">0</property>
        <property name="margin-top">12</property>
        <property name="margin-end">12</property>
        <property name="margin-bottom">12</property>
        <property name="margin-start">12</property>
        <property name="spacing">12</property>
        <child>
          <object class="GtkStackSidebar">
            <property name="stack">stack</property>
          </object>
        </child>
        <child>
          <object class="GtkStack" id="stack">
            <child>
              <object class="GtkStackPage">
                <property name="name">page1</property>
                <property name="title">Page 01</property>
                <property name="child">
                  <object class="GtkBox">
                    <property name="orientation">1</property>
                    <property name="spacing">6</property>
                    <child>
                      <object class="GtkButton">
                        <property name="label">Button 01</property>
                      </object>
                    </child>
                    <child>
                      <object class="GtkButton">
                        <property name="label">Button 02</property>
                      </object>
                    </child>
                    <child>
                      <object class="GtkButton">
                        <property name="label">Button 03</property>
                      </object>
                    </child>
                  </object>
                </property>
              </object>
            </child>
            <child>
              <object class="GtkStackPage">
                <property name="name">page2</property>
                <property name="title">Page 02</property>
                <property name="child">
                  <object class="GtkBox">
                    <property name="orientation">1</property>
                    <property name="spacing">6</property>
                    <child>
                      <object class="GtkLabel">
                        <property name="label">Line 01</property>
                      </object>
                    </child>
                    <child>
                      <object class="GtkLabel">
                        <property name="label">Line 02</property>
                      </object>
                    </child>
                    <child>
                      <object class="GtkLabel">
                        <property name="label">Line 03</property>
                      </object>
                    </child>
                  </object>
                </property>
              </object>
            </child>
          </object>
        </child>
      </object>
    </child>
  </template>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
    </section>
  </menu>
</interface>
using Gtk 4.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject Gtk.StackSidebar.';
  default-width: 683;
  default-height: 384;

  [titlebar]
  Gtk.HeaderBar header_bar {
    [end]
    Gtk.MenuButton {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }

  Gtk.Box {
    orientation: horizontal;
    margin-top: 12;
    margin-end: 12;
    margin-bottom: 12;
    margin-start: 12;
    spacing: 12;

    Gtk.StackSidebar {
      stack: stack;
    }

    Gtk.Stack stack {
      Gtk.StackPage {
        name: 'page1';
        title: 'Page 01';
        child:
          Gtk.Box {
            orientation: vertical;
            spacing: 6;
            Gtk.Button {
              label: 'Button 01';
            }
            Gtk.Button {
              label: 'Button 02';
            }
            Gtk.Button {
              label: 'Button 03';
            }
          }
        ;
      }

      Gtk.StackPage {
        name: 'page2';
        title: 'Page 02';
        child:
          Gtk.Box {
            orientation: vertical;
            spacing: 6;
            Gtk.Label {
              label: 'Line 01';
            }
            Gtk.Label {
              label: 'Line 02';
            }
            Gtk.Label {
              label: 'Line 03';
            }
          }
        ;
      }
    }    
  }
}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
  }
}

Gtk.StackSwitcher#

Gtk.StackSwitcher

Gtk.StackSwitcher#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.StackSwitcher"""



import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()


class ExampleWindow(Gtk.ApplicationWindow):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.set_title(title='Python and GTK: PyGObject Gtk.StackSwitcher')
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append(
            label='Preferences',
            detailed_action='app.preferences',
        )

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        vbox = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=12)
        vbox.set_margin_top(margin=12)
        vbox.set_margin_end(margin=12)
        vbox.set_margin_bottom(margin=12)
        vbox.set_margin_start(margin=12)
        self.set_child(child=vbox)

        stack = Gtk.Stack.new()

        page1 = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=6)
        stack.add_titled(child=page1, name='page1', title='Page 1')
        vbox.append(child=stack)

        for n in range(5):
            botao = Gtk.Button.new_with_label(label=f'Button {n}')
            page1.append(child=botao)

        page2 = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=6)
        stack.add_titled(child=page2, name='page2', title='Page 2')

        for n in range(5):
            label = Gtk.Label.new(str=f'Line {n}')
            page2.append(child=label)

        stack_switcher = Gtk.StackSwitcher.new()
        stack_switcher.set_stack(stack=stack)
        header_bar.set_title_widget(title_widget=stack_switcher)


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.StackSwitcher."""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent


@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject Gtk.GtkStackSwitcher.</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar">
        <property name="title-widget">
          <object class="GtkStackSwitcher">
            <property name="stack">stack</property>
          </object>
        </property>
        <child type="end">
          <object class="GtkMenuButton">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
    <child>
      <object class="GtkBox">
        <property name="orientation">1</property>
        <property name="homogeneous">true</property>
        <property name="margin-top">12</property>
        <property name="margin-end">12</property>
        <property name="margin-bottom">12</property>
        <property name="margin-start">12</property>
        <property name="spacing">12</property>
        <child>
          <object class="GtkStack" id="stack">
            <property name="vexpand">true</property>
            <child>
              <object class="GtkStackPage">
                <property name="name">page1</property>
                <property name="title">Page 01</property>
                <property name="child">
                  <object class="GtkBox">
                    <property name="orientation">1</property>
                    <property name="spacing">6</property>
                    <child>
                      <object class="GtkButton">
                        <property name="label">Button 01</property>
                      </object>
                    </child>
                    <child>
                      <object class="GtkButton">
                        <property name="label">Button 02</property>
                      </object>
                    </child>
                    <child>
                      <object class="GtkButton">
                        <property name="label">Button 03</property>
                      </object>
                    </child>
                  </object>
                </property>
              </object>
            </child>
            <child>
              <object class="GtkStackPage">
                <property name="name">page2</property>
                <property name="title">Page 02</property>
                <property name="child">
                  <object class="GtkBox">
                    <property name="orientation">1</property>
                    <property name="spacing">6</property>
                    <child>
                      <object class="GtkLabel">
                        <property name="label">Line 01</property>
                      </object>
                    </child>
                    <child>
                      <object class="GtkLabel">
                        <property name="label">Line 02</property>
                      </object>
                    </child>
                    <child>
                      <object class="GtkLabel">
                        <property name="label">Line 03</property>
                      </object>
                    </child>
                  </object>
                </property>
              </object>
            </child>
          </object>
        </child>
      </object>
    </child>
  </template>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
    </section>
  </menu>
</interface>
using Gtk 4.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject Gtk.GtkStackSwitcher.';
  default-width: 683;
  default-height: 384;

  [titlebar]
  Gtk.HeaderBar {
    title-widget: Gtk.StackSwitcher {
      stack: stack;
    };
  
    [end]
    Gtk.MenuButton {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }

  Gtk.Box {
    orientation: vertical;
    homogeneous: true;
    margin-top: 12;
    margin-end: 12;
    margin-bottom: 12;
    margin-start: 12;
    spacing: 12;

    Gtk.Stack stack {
      vexpand: true;

      Gtk.StackPage {
        name: 'page1';
        title: 'Page 01';
        child:
          Gtk.Box {
            orientation: vertical;
            spacing: 6;
            Gtk.Button {
              label: 'Button 01';
            }
            Gtk.Button {
              label: 'Button 02';
            }
            Gtk.Button {
              label: 'Button 03';
            }
          }
        ;
      }

      Gtk.StackPage {
        name: 'page2';
        title: 'Page 02';
        child:
          Gtk.Box {
            orientation: vertical;
            spacing: 6;
            Gtk.Label {
              label: 'Line 01';
            }
            Gtk.Label {
              label: 'Line 02';
            }
            Gtk.Label {
              label: 'Line 03';
            }
          }
        ;
      }
    }  
  }
}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
  }
}

Gtk.Switch#

Gtk.Switch

Gtk.Switch#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.Switch"""



import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()


class ExampleWindow(Gtk.ApplicationWindow):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.set_title(title='Python and GTK: PyGObject Gtk.Switch')
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append(
            label='Preferences',
            detailed_action='app.preferences',
        )

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        vbox = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=12)
        vbox.set_margin_top(margin=12)
        vbox.set_margin_end(margin=12)
        vbox.set_margin_bottom(margin=12)
        vbox.set_margin_start(margin=12)
        self.set_child(child=vbox)

        switch = Gtk.Switch.new()
        switch.set_halign(align=Gtk.Align.START)
        switch.connect('notify::active', self.on_switch_button_clicked)
        vbox.append(child=switch)

    def on_switch_button_clicked(self, switch, g_param):
        if switch.get_active():
            print('Button checked')
        else:
            print('Button unchecked')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.Switch."""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent


@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    @Gtk.Template.Callback()
    def on_switch_button_clicked(self, switch, g_param):
        if switch.get_active():
            print('Button checked')
        else:
            print('Button unchecked')


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject Gtk.Switch</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar" id="header_bar">
        <child type="end">
          <object class="GtkMenuButton">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
    <child>
      <object class="GtkBox">
        <property name="orientation">1</property>
        <property name="margin-top">12</property>
        <property name="margin-end">12</property>
        <property name="margin-bottom">12</property>
        <property name="margin-start">12</property>
        <property name="spacing">12</property>
        <child>
          <object class="GtkSwitch" id="switch">
            <property name="halign">1</property>
            <signal name="notify::active" handler="on_switch_button_clicked"/>
          </object>
        </child>
      </object>
    </child>
  </template>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
    </section>
  </menu>
</interface>
using Gtk 4.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject Gtk.Switch';
  default-width: 683;
  default-height: 384;

  [titlebar]
  Gtk.HeaderBar header_bar {
    [end]
    Gtk.MenuButton {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }

  Gtk.Box {
    orientation: vertical;
    margin-top: 12;
    margin-end: 12;
    margin-bottom: 12;
    margin-start: 12;
    spacing: 12;

    Gtk.Switch switch {
      halign: start;
      notify::active => $on_switch_button_clicked();
    }
  }
}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
  }
}

Translation (gettext)#

Aviso

Corrigir código e adicionar imagem.

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject internationalization with gettext"""

import configparser
import gettext
import pathlib



import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

APPLICATION_ID = 'br.com.justcode.PyGObject'


LOCALES_DIR = BASE_DIR.joinpath('locales')
CONFIG_FILE = BASE_DIR.joinpath('config.ini')
window_title = 'Python and GTK: Gtk.ApplicationWindow()'

# The default language of the operating system will be used.
# gettext.bindtextdomain(APPLICATION_ID, LOCALES_DIR)
# gettext.textdomain(APPLICATION_ID)
_ = gettext.gettext

config = configparser.ConfigParser()
if CONFIG_FILE.exists():
    config.read(CONFIG_FILE)
    language = config[APPLICATION_ID]['language']
    if language != 'default':
        lang = gettext.translation(APPLICATION_ID, localedir=LOCALES_DIR, languages=[language])
        lang.install()
        _ = lang.gettext


class ExampleWindow(Gtk.ApplicationWindow):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.set_title(
            _('Python and GTK: PyGObject internacionalização com gettext().'),
        )
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append(
            label='Preferences',
            detailed_action='app.preferences',
        )

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        vbox = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=0)
        vbox.set_margin_bottom(12)
        vbox.set_margin_end(12)
        vbox.set_margin_start(12)
        vbox.set_margin_top(12)
        self.set_child(child=vbox)

        label = Gtk.Label.new()
        label.set_text(_('Após trocar o idioma reinicie o aplicativo.'))
        label.set_vexpand(True)
        vbox.append(child=label)

        combobox_text = Gtk.ComboBoxText()
        combobox_text.append_text(_('Selecione um idioma.'))
        combobox_text.set_active(0)
        combobox_text.connect('changed', self.combobox_text_changed)
        vbox.append(child=combobox_text)

        langs = ['en_US', 'pt_BR']
        for lang in langs:
            combobox_text.append_text(lang)

    def combobox_text_changed(self, combobox):
        row = combobox.get_active()
        if row != 0:
            text = combobox.get_active_text()
            print(f'O idioma selecionado foi: {text}')
            if text == 'pt_BR':
                text = 'default'

            config[APPLICATION_ID] = {'language': text}
            with open(CONFIG_FILE, 'w+') as f:
                config.write(f)
                f.close()


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)

Gtk.Video#

Gtk.Video

Gtk.Video#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.Video"""

import pathlib



import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()


SRC_DIR = BASE_DIR.parent.parent
VIDEO = str(
    SRC_DIR.joinpath('data', 'videos',
                     'beautiful-sunset-view-nature-background.mp4')
)


class ExampleWindow(Gtk.ApplicationWindow):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.set_title(title='Python and GTK: PyGObject Gtk.Video')
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append(
            label='Preferences',
            detailed_action='app.preferences',
        )

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        vbox = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=12)
        vbox.set_homogeneous(homogeneous=True)
        vbox.set_margin_top(margin=12)
        vbox.set_margin_end(margin=12)
        vbox.set_margin_bottom(margin=12)
        vbox.set_margin_start(margin=12)
        self.set_child(child=vbox)

        video = Gtk.Video.new()
        video.set_filename(filename=VIDEO)
        vbox.append(video)


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.Video."""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent




VIDEO = str(
    BASE_DIR.parent.parent.parent.joinpath(
        'data', 'videos','video.mp4'
    )
)










@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    video = Gtk.Template.Child(name='video')

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.video.set_filename(filename=VIDEO)


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject Gtk.Video</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar" id="header_bar">
        <child type="end">
          <object class="GtkMenuButton">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
    <child>
      <object class="GtkBox">
        <property name="orientation">1</property>
        <property name="homogeneous">true</property>
        <property name="margin-top">12</property>
        <property name="margin-end">12</property>
        <property name="margin-bottom">12</property>
        <property name="margin-start">12</property>
        <property name="spacing">12</property>
        <child>
          <object class="GtkVideo" id="video"></object>
        </child>
      </object>
    </child>
  </template>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
    </section>
  </menu>
</interface>
using Gtk 4.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject Gtk.Video';
  default-width: 683;
  default-height: 384;

  [titlebar]
  Gtk.HeaderBar header_bar {
    [end]
    Gtk.MenuButton {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }

  Gtk.Box {
    orientation: vertical;
    homogeneous: true;
    margin-top: 12;
    margin-end: 12;
    margin-bottom: 12;
    margin-start: 12;
    spacing: 12;

    Gtk.Video video {}
  }
}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
  }
}

Gtk.Window#

Gtk.Window

Gtk.Window#

# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.Window"""



import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()


class NewWindow(Gtk.Window):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.set_title(title='Python and GTK: PyGObject Gtk.Window')
        self.set_modal(modal=True)
        self.set_default_size(width=int(1366 / 3), height=int(768 / 3))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        vbox = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=6)
        vbox.set_margin_top(margin=12)
        vbox.set_margin_end(margin=12)
        vbox.set_margin_bottom(margin=12)
        vbox.set_margin_start(margin=12)
        self.set_child(child=vbox)

        # Widgets.
        button = Gtk.Button.new_with_label('Close window')
        button.connect('clicked', self.on_button_close_clicked)
        vbox.append(child=button)

    def on_button_close_clicked(self, button):
        self.destroy()


class ExampleWindow(Gtk.ApplicationWindow):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.set_title(title='Python and GTK: PyGObject Gtk.ApplicationWindow')
        self.set_default_size(width=int(1366 / 2), height=int(768 / 2))
        self.set_size_request(width=int(1366 / 3), height=int(768 / 3))

        header_bar = Gtk.HeaderBar.new()
        self.set_titlebar(titlebar=header_bar)

        menu_button_model = Gio.Menu()
        menu_button_model.append(
            label='Preferences',
            detailed_action='app.preferences',
        )

        menu_button = Gtk.MenuButton.new()
        menu_button.set_icon_name(icon_name='open-menu-symbolic')
        menu_button.set_menu_model(menu_model=menu_button_model)
        header_bar.pack_end(child=menu_button)

        vbox = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=6)
        vbox.set_margin_top(margin=12)
        vbox.set_margin_end(margin=12)
        vbox.set_margin_bottom(margin=12)
        vbox.set_margin_start(margin=12)
        self.set_child(child=vbox)

        button = Gtk.Button.new_with_label(label='Open window')
        button.connect('clicked', self.on_button_clicked)
        vbox.append(child=button)

    def on_button_clicked(self, button):
        new_window = NewWindow(transient_for=self)
        new_window.present()


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    import sys

    app = ExampleApplication()
    app.run(sys.argv)
# -*- coding: utf-8 -*-
"""Python and GTK: PyGObject Gtk.Window."""

import pathlib
import sys

import gi

gi.require_version(namespace='Gtk', version='4.0')
gi.require_version(namespace='Adw', version='1')

from gi.repository import Adw, Gio, Gtk

Adw.init()

BASE_DIR = pathlib.Path(__file__).resolve().parent


@Gtk.Template(filename=str(BASE_DIR.joinpath('NewWindow.ui')))
class NewWindow(Gtk.Window):
    __gtype_name__ = 'NewWindow'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    @Gtk.Template.Callback()
    def on_button_close_clicked(self, button):
        self.destroy()




@Gtk.Template(filename=str(BASE_DIR.joinpath('MainWindow.ui')))
class ExampleWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'ExampleWindow'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    @Gtk.Template.Callback()
    def on_button_clicked(self, button):
        new_window = NewWindow(transient_for=self)
        new_window.present()


class ExampleApplication(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='br.com.justcode.PyGObject',
                         flags=Gio.ApplicationFlags.FLAGS_NONE)

        self.create_action('quit', self.exit_app, ['<primary>q'])
        self.create_action('preferences', self.on_preferences_action)

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = ExampleWindow(application=self)
        win.present()

    def do_startup(self):
        Gtk.Application.do_startup(self)

    def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

    def on_preferences_action(self, action, param):
        print('Action `app.preferences` was active.')

    def exit_app(self, action, param):
        self.quit()

    def create_action(self, name, callback, shortcuts=None):
        action = Gio.SimpleAction.new(name=name, parameter_type=None)
        action.connect('activate', callback)
        self.add_action(action=action)
        if shortcuts:
            self.set_accels_for_action(
                detailed_action_name=f'app.{name}',
                accels=shortcuts,
            )


if __name__ == '__main__':
    app = ExampleApplication()
    app.run(sys.argv)
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT EDIT!
This file was @generated by blueprint-compiler. Instead, edit the
corresponding .blp file and regenerate this file with blueprint-compiler.
-->
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="ExampleWindow" parent="GtkApplicationWindow">
    <property name="title">Python and GTK: PyGObject Gtk.Window</property>
    <property name="default-width">683</property>
    <property name="default-height">384</property>
    <child type="titlebar">
      <object class="GtkHeaderBar" id="header_bar">
        <child type="end">
          <object class="GtkMenuButton">
            <property name="icon-name">open-menu-symbolic</property>
            <property name="menu-model">primary_menu</property>
          </object>
        </child>
      </object>
    </child>
    <child>
      <object class="GtkBox">
        <property name="orientation">1</property>
        <property name="margin-top">12</property>
        <property name="margin-end">12</property>
        <property name="margin-bottom">12</property>
        <property name="margin-start">12</property>
        <property name="spacing">12</property>
        <child>
          <object class="GtkButton">
            <property name="label">Open window</property>
            <signal name="clicked" handler="on_button_clicked"/>
          </object>
        </child>
      </object>
    </child>
  </template>
  <menu id="primary_menu">
    <section>
      <item>
        <attribute name="label" translatable="true">Preferences</attribute>
        <attribute name="action">app.preferences</attribute>
      </item>
      <item>
        <attribute name="label" translatable="true">Atalhos</attribute>
        <attribute name="action">app.shortcuts-window</attribute>
      </item>
    </section>
  </menu>
</interface>
using Gtk 4.0;

template $ExampleWindow: Gtk.ApplicationWindow {
  title: 'Python and GTK: PyGObject Gtk.Window';
  default-width: 683;
  default-height: 384;

  [titlebar]
  Gtk.HeaderBar header_bar {
    [end]
    Gtk.MenuButton {
      icon-name: 'open-menu-symbolic';
      menu-model: primary_menu;
    }
  }

  Gtk.Box {
    orientation: vertical;
    margin-top: 12;
    margin-end: 12;
    margin-bottom: 12;
    margin-start: 12;
    spacing: 12;

    Gtk.Button {
      label: 'Open window';
     clicked => $on_button_clicked();
    }
  }
}

menu primary_menu {
  section {
    item {
      label: _('Preferences');
      action: 'app.preferences';
    }
    item {
      label: _('Atalhos');
      action: 'app.shortcuts-window';
    }
  }
}