- Python Gtk tutorial
- Python Gtk simple example
- Python Gtk icon
- Python Gtk.Label
- Python Gtk.Image
- Python Gtk.Button
- Python Gtk.Fixed container
- Python Gtk.CheckButton
- Python Gtk.Entry
- Python Gtk.ComboBoxText
- Pycairo basic shapes
- Python Gtk.Application
- 2. Getting StartedВ¶
- 2.1. Simple ExampleВ¶
- 2.2. Extended ExampleВ¶
- GTK and Python
- About
- PyGObject API
- A Hello World app
- Explanation
- Contribute
- See More
- Making Matplotlib and GTK3 work on python3 windows
- 2 Answers 2
Python Gtk tutorial
last modified July 6, 2020
Python Gtk tutorial shows how to create GUI applications in Python using Gtk module.
GTK+ is a multi-platform toolkit for creating graphical user interfaces. In is created in C language. GTK+ has been designed from the ground up to support a range of languages, including Python, Ruby, and Perl.
The GTK+ library is also called the GIMP Toolkit. Originally, the library was created while developing the GIMP image manipulation program. Since then, the GTK+ became one of the most popular toolkits under Linux and BSD Unix.
Python Gtk simple example
In the first application, we display a window on the screen. Gtk.Window is a toplevel window which can contain other widgets. In other words, it is a container. Windows normally have decorations that are under the control of the windowing system and allow the user to manipulate the window.
The example shows a small window on the screen.
We import the Gtk module. The require_version() method ensures the namespace gets loaded with the given version. The gi.repository is the Python module for PyGObject . PyGObject (Python GObject introspection) contains Python bindings and support for gobject, glib, gtk and other Gnome libraries.
An empty window is created.
This line ensures that the window is closed when we click on the Close button in the title bar.
The show() window displays the window on the screen.
The main() method starts the event loop. The event loop waits for events such as mouse press, mouse move, or keyboard press events.
Figure: Python Gtk simple application
Python Gtk icon
An application icon is a small image which is usually shown in the titlebar of the application. Note that some environments might not show application icon, in some the application icons must be enabled.
The web.png is located in the current working directory.
The set_icon_from_file() sets the application icon from the image file name.
The set_default_size() sets the default size of a window.
Figure: Application icon
Python Gtk.Label
The Gtk.Label widget displays a small amount of text.
The example shows lyrics on the window.
The set_border_width() sets some margin space around the window.
Gtk.Label is created and added to the window. The Gtk.Window is a simple container.
We can show all widgets in one shot with show_all() method.
Figure: Gtk.Label
Python Gtk.Image
Gtk.Image dispalys an image. If the file is not loaded successfully, the image will contain a «broken image» icon.
The example displays a PNG image on the window.
Gtk.Image is created. The set_from_file() method sets the image from the given file name.
Python Gtk.Button
The Gtk.Button is used to trigger a callback function that is called when the button is pressed.
In the example, we have a button. When we press the button, the application terminates.
We use the Gtk.Grid manager to organize our layout. The manager lays out widgets in a table.
A Gtk.Button is created. The set_size_request() sets the minimum size of the button. The initial button size is quite small, therefore we increase its size.
When the button is clicked, it emits a clicked signal. With the connect() method we bind the signal to the on_button_clicked() callback method.
With the attach() method, we place the button into the top-left cell of the grid.
The callback method terminates the application with Gtk.main_quit() .
Figure: Quit button
Python Gtk.Fixed container
Gtk.Fixed widget is a container which puts child widgets at fixed positions and with fixed sizes, given in pixels. Gtk.Fixed performs no automatic layout management. Gtk.Fixed should be used only in specific cases.
The example shows three images at given fixed positions.
We change the background colour of the window with modify_bg() .
From three JPG images, we create three Gtk.Image widgets.
The Gtk.Fixed container is created. Its put() method places the widget at the given coordinates.
The Gtk.Fixed set to be the container for the Gtk.Window .
Figure: Fixed container
Python Gtk.CheckButton
Gtk.CheckButton a widget that has two states: on and off. The on state is visualised by a check mark.
The example displays a title in the titlebar of the window depending on the state of the Gtk.CheckButton .
The button is added to a horizontal box. Gtk.Box is a simple layout manager that arranges widgets in a row or a column.
The Gtk.CheckButton is created. Since by default the title of the window is visible, we activate the button with set_active() .
When we check or uncheck the Gtk.CheckButton , the on_clicked() method is called.
We determine the state of the Gtk.CheckButton with get_active() and set the title accordingly.
Figure: Gtk.CheckButton
Python Gtk.Entry
Gtk.Entry widget is a single line text entry widget. Many key bindings are supported by default. If the entered text is longer than the allocation of the widget, the widget will scroll so that the cursor position is visible.
In the example, we have an entry widget and a label. The text entered into the entry is displayed in the label.
We create the Gtk.Entry widget. We connect an event handler to the key-release-event .
In the on_key_release() event handler, we get the text from the entry with get_text() and set it to the label with set_text() .
Figure: Gtk.Entry
Python Gtk.ComboBoxText
Gtk.ComboBoxText is a simple variant of Gtk.ComboBox that hides the model-view complexity for simple text-only use cases.
In the example, we have a Gtk.ComboBoxText and a label. The selected item from the combo box is displayed in the label widget.
Gtk.ComboBoxText is created.
When the active item is changed, the changed signal is emitted.
We add five text items to the combo box.
In the on_changed() event handler, we get the active text with get_active_text() and set it to the label with set_label() .
Figure: Gtk.ComboBoxText
Pycairo basic shapes
Pycairo is a Python module providing bindings for the cairo graphics library. Drawing is done on a Gtk.DrawingArea widget. It is essentially a blank widget.
The example draws a few basic shapes with Pycairo.
Drawing is performed on Gtk.DrawingArea . The drawing API is called in the callback of the draw signal.
The second parameter of on_draw() is the drawing area, the third is the cairo context. The context is an object that is used to draw on all drawable objects.
The set_source_rgb() method sets a colour for the cairo context. The three parameters of the method are the colour intensity values. The values are from 0 to 1.
We paint two rectangles. The fill() method paints the interior of the rectangles in the previously set colour.
With the arc() method, we paint a full circle.
The translate() method moves the user-space origin by delta x and delta y.
If we want to draw an oval, we do some scaling first. Here the scale() method shrinks the y axis.
Figure: Pycairo basic shapes
Python Gtk.Application
Gtk.Application is a class that handles many important aspects of a GTK+ application such as initialization, application uniqueness, session management, provides some basic scriptability and desktop shell integration. It is recommended to use it together with Gtk.ApplicationWindow .
This is a simple example of a Gtk.Application . It contains a menubar.
Gtk.ApplicationWindow is a Gtk.Window subclass that offers some extra functionality for better integration with Gtk.Application features. Notably, it can handle both the application menu as well as the menubar. It has a parameter reference to the Gtk.Application .
Gtk.MenuBar creates a classic application menubar. A menubar can contain one or more Gtk.MenuItems .
A File menu item is created; it contains a single submenu, which terminates the application when selected.
The do_activate() method is called when the desktop environment launches the application. It is the application entry point. The do_startup() sets up the application when it first starts.
Figure: Gtk.Application
In this tutorial, we have created basic GUI applications with Python Gtk.
2. Getting StartedВ¶
2.1. Simple ExampleВ¶
To start with our tutorial we create the simplest program possible. This program will create an empty 200 x 200 pixel window.
We will now explain each line of the example.
In the beginning, we have to import the Gtk module to be able to access GTK+’s classes and functions. Since a user’s system can have multiple versions of GTK+ installed at the same, we want to make sure that when we import Gtk that it refers to GTK+ 3 and not any other version of the library, which is the purpose of the statement gi.require_version(‘Gtk’, ‘3.0’) .
The next line creates an empty window.
Followed by connecting to the window’s delete event to ensure that the application is terminated if we click on the x to close the window.
In the next step we display the window.
Finally, we start the GTK+ processing loop which we quit when the window is closed (see line 6).
To run the program, open a terminal, change to the directory of the file, and enter:
2.2. Extended ExampleВ¶
For something a little more useful, here’s the PyGObject version of the classic “Hello World” program.
This example differs from the simple example as we sub-class Gtk.Window to define our own MyWindow class.
In the class’s constructor we have to call the constructor of the super class. In addition, we tell it to set the value of the property title to Hello World .
The next three lines are used to create a button widget, connect to its clicked signal and add it as child to the top-level window.
Accordingly, the method on_button_clicked() will be called if you click on the button.
The last block, outside of the class, is very similar to the simple example above, but instead of creating an instance of the generic Gtk.Window class, we create an instance of MyWindow .
© Copyright GNU Free Documentation License 1.3 Revision 5b86f569 .
GTK and Python
About
PyGObject is a Python package which provides bindings for GObject based libraries such as GTK, GStreamer, WebKitGTK, GLib, GIO and many more.
It supports Linux, Windows and macOS and works with Python 2.7+, Python 3.5+, PyPy and PyPy3. PyGObject, including this documentation, is licensed under the LGPLv2.1+.
If you want to write a Python application for GNOME or a Python GUI application using GTK, then PyGObject is the way to go. For more information on specific libraries check out the Python GTK 3 Tutorial and the Python GI API Reference.
PyGObject API
You can view the API Reference for the PyGObject at http://lazka.github.io/pgi-docs/
A Hello World app
Below is an Hello World program that can be used as an example to get started with the PyGObject.
Explanation
gi python module is imported to use APIs linked with the PyGObject.
Contribute
If you are interested in contributing to the PyGObject project or want to get in touch with the original source files, you can visit the project’s git repository on Gitlab.
See More
- Gitlab Project: https://gitlab.gnome.org/GNOME/pygobject/
- PyGObject Website: https://pygobject.readthedocs.io/en/latest/
- API References: http://lazka.github.io/pgi-docs/
- PyGObject Tutorials: https://python-gtk-3-tutorial.readthedocs.io/en/latest/
GTK is hosted by GNOME.
GTK is maintained by the GTK Team.
© 1997-2021, The GTK Team. All Rights Reserved.
Making Matplotlib and GTK3 work on python3 windows
I’m trying to make GTK3 and Python3 work under windows to my project.
I have an continuum anaconda setup with a 32-bit python 3.4 and Matplotib via conda install matplotlib.
I’ve installed PyGobject(https://sourceforge.net/projects/pygobjectwin32/) and installed GTK+ / Glade via the installer.
The basic exemple from the GTK3 tutorial works well (empty screen)
I want now to embed matplotlib in gtk, I got the example from matplotlib (http://matplotlib.org/examples/user_interfaces/embedding_in_gtk3.html)
I saw then that I needed cairocffi because some incompabilities. (PyCairo has no support for a matplotlib function)
I got the windows binaries for cffi from Gohlke
And finnaly did a
And now I just get a python.exe stopped working.
Tried with GTK3agg and GTK3Cairo backends and I have the same result
Looking around I found that maybe the cairo version is outdated for the functions used by matplotlib, but I dont know how to proceed.
Cairocffi works if I try running something else.
More information (from the comment below):
I still got an unhandled win32 error. I managed to open the error and it says:
It just crashes.
2 Answers 2
I’ve had my share of problems using matplotlib in Python3 + Gtk3 . I found this cookbook page with working examples. Try to run the examples in the cookbook — particularly the simplest one:
Also, not that you need a fairly recent version of matplotlib to make things work on Python3 .
If you still have problems, please show us the complete error message.
Note: I tested this on Linux (don’t have Windows), but, from you description of problems, the issue is (was) a common one.
I have the same issue on Windows since years. The documentation of matplotlib 2.0.0 realease states that Gtk3 backend is not supported on Windows. Recently, I had an issue running the Gtk3Agg backend under Linux (Ubuntu). In both cases, it is always related to Cairo.
Thus, I wrote my own implementation of this backend, you can find it here. import the FigureCanvasGtk3Agg from my module and use it the same way as the official one. It lacks some features, but, if you just want to display a plot, it’ll do the job.
You can try the module by running it, it should display a simple colorful graph in a window. I tried it under both Linux and Windows and had no issue.
How does it works:
The trick is to avoid importing Cairo in Python3 as it usually doesn’t work (to my experience). It is done by using a GdkPixbuf .