Up to $140 off-Lowest  Prices of 2024(Nov.21-Dec.2)

My Computer Tips

Home | About | Categories | All Tips & Tutorials

Create a new window using GTK and Python in Ubuntu and Ubuntu based distributions

ID: 218

Category: Python3

Added: 19th of November 2020

Updated On: Tutorial updated and rechecked on 29th of October 2024

Views: 1,879

I have always wanted to learn how to create an application in Ubuntu or an Ubuntu based distribution. There is a lot of information out there and If I'm honest it can get quite confusing.

I also don't mind admitting that I am no expert in this field, but I wanted to put something down that I could revisit later to give me a starting point. Please note if your using Kubuntu / KDE things will be different.

In this tutorial, we create a basic window using Python3 and GTK.

First of all you need to make sure python 3 is installed, most Ubuntu and Ubuntu and Ubuntu based distributions already include this, but to check enter the following command in the terminal.

python3 --version

If you don't get any ouput from the terminal enter the following command in the terminal
sudo apt-get install python3

Once installed, it's now time to create our first window

Create a new file on your Desktop name new_window.py
Next enter the following command in the terminal to get your path to python3
which python3

Create a new file on your desktop, and save this as new_window.py, then copy and paste the code below.
#!/usr/bin/python3

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

window = Gtk.Window(title="Hello World")
window.show()
window.connect("destroy", Gtk.main_quit)
Gtk.main()

Next we need to make the script executable, so enter the following command
chmod +x new_window.py

Then enter the following in the terminal
./new_window.py

If everthing works correctly a new window should pop up.