Python Series Part 13: Starting with Tkinter

Jarret B

Well-Known Member
Staff member
Joined
May 22, 2017
Messages
390
Reaction score
467
Credits
14,550
So far, we’ve been looking at Python in a terminal running on a command-line. Now, we need to look at running as a Graphical User Interface (GUI) and making things more “screen friendly”.

The way to make the program a GUI is through the use of an add-on called ‘tkinter’.

Installing Tkinter

If you’ve been following along through the Python articles, you should already have Python installed as covered in ‘Python Series Part 1: Installing and Configuring Python 3’. Make sure you have Python installed with an Integrated Developer Environment (IDE)

Now, you should have Python and an IDE going to allow you access to an environment in which to write code, run code and test code.

Stay in the terminal for a minute to get ‘tkinter’ installed.

Use the following commands for your specific Linux distro:

Ubuntu

Code:
sudo apt install python3-tk -y

Fedora

Code:
sudo dnf install python3-tkinter -y

CentOS, Red Hat

Code:
sudo yum install tkinter tk-devel

Arch

Code:
sudo pacman -S tk

This should get you ‘tkinter’, but you can test it to make sure it works with the command:

Code:
python3 -m tkinter

The result should be like Figure 1.

Figure 1.JPG

FIGURE 1

The little box that appears is a ‘tkinter’ window. The window is GUI being run from Python. It shows the ‘tkinter’ version of ‘8.6’. We can also go into the ‘python3’ interactive environment and get the same information:

Code:
python3
import tkinter
tkinter.TkVersion
exit()

After you issue the command, ‘tkinter.TkVersion’, the output should be the same as the version number shown in the GUI. In the environment from a terminal, see three greater than symbols (>>>) before each line while you are in the Python environment. Once you issue the command ‘exit()’, you should be back at a terminal prompt.

Making a ‘tkinter’ Window

For best practice, never name your Python code ‘tkinter’. Use some variation or avoid the name ‘tkinter’ completely in the filename. Be sure not even have a file with the name ‘tkinter’ in your default save folder, even if you do not use the file. It can cause issues when using ‘tkinter’.

For the Python code, we start with the following three lines:

Code:
from tkinter import *
root = Tk()
root.mainloop()

Let’s look over the three lines of code. In the first line, we are importing all of the ‘tkinter’ module into the current Python app. The second line will then create the window and call it ‘root’. We can use any valid name, but the general practice is calling it ‘root’. The last line is a loop that implements any code or changes to the window.

You could easily create multiple windows, giving each a different name:

Code:
from tkinter import *
root = Tk()
root1 = Tk()
root.mainloop()
root1.mainloop()

You should notice that each window has a default name at the top of the window itself. The default name is ‘tk’. If you create a second window, the default name is ‘tk #2’, and so on. We’ll look into changing that soon.

Any changes you make to the window need to be implemented after you create the window and before the loop.

Changing the Window

So, let’s first look at changing the window’s name.

The command to do this is:

Code:
root.title(“Window Name”)

Figure 2 shows the GUI output.

Figure 2.JPG

FIGURE 2

Within the double-quotes, is the title at the top of the window.

NOTE: Be sure to use double-quotes, not the fancy curly double-quotes.

The rest of the window is default. This means that the window is re-sizable. You can minimize, maximize, and close it. It also has default size.

Let’s change the size first. The code would be:

Code:
root.geometry(“250x500”)

This would make the window a width of ‘250 pixels’ and a height of ‘500 pixels’. The values can be the size you require for your project.

There is a way to place the window on the screen at a specific spot as well. The top left of the screen should be ‘0,0’. The first number is the number of pixels right, while the second number is the number of pixels down. You separate these with plus signs (+). So, if we want a window with a size of ‘200x300’ and placed to the right 1000 pixels and down 400, the command is:

Code:
root.geometry(“200x300+1000+400”)

You can still maximize the window and resize it to any size you want. Once the program is closed and reopened, the defaults take effect again.

It is possible to remove the maximize button and not allow the window to be resized by the user. The code is:

Code:
root.resizable(width=False, height=False)

or

Code:
root.resizable(False, False)

Here, we remove the ability to resize the window by either height or width. We could only set it for one, neither or both.

What if we wanted to center our window on the screen? We can do that. The code is:

Code:
def center(w,h,x,y):
     screen_width = root.winfo_screenwidth()
     screen_height = root.winfo_screenheight()
     x = (screen_width/2) - (w/2)
     y = (screen_height/2) - (h/2)
     root.geometry('%dx%d+%d+%d' % (w,h,x,y))

from tkinter import *

root = Tk()
w=1000
h=500
x=0
y=0
root.title("Centered Window")
center(w,h,x,y)

root.mainloop()

I create a Function named ‘center’ where I use the window width (w), window height (h) and find the x and y placement on the screen.

We find the ‘screen_width’ using the command ‘root.winfo_screenwidth()’ and the ‘screen_height’ using the command ‘root.winfo_screenheight()’. We then use these numbers and divide them by 2 as well as dividing the window width or height by 2. We subtract these numbers to get the exact placement.

If you change the width (w) and height (h), you can see that no matter what the window size is, it should be centered on the screen.

If a window is re-sizable, we can set the minimum and maximum size of the window. This setting does not change the minimum and maximum sizes when using the minimize or maximize buttons. It works when the edge of the window is ‘grabbed’ and the user resizes the window in that manner.

So, to set the minimum and maximum size, the code is:

Code:
 window.minsize(minimum_width, minimum_height)
window.maxsize(maximum_height, maximum_height)

If you do not set one of them, the default minimum size is a single line with a height of one character. The maximum size, if not specified, is the screen size.

Another ability is to make the window transparent, opaque, or somewhere in between. The code is:

Code:
root.wait_visibility(root)
root.attributes('-alpha', 0.5)

For some Operating Systems (OS), you do not need the first line. I’ve tested this on Ubuntu and you need the first line. Here, the system waits for the ‘root’ window to become visible and then sets the transparency. The code for transparency is ‘-alpha’. The numeric value is from completely transparent (0.0) to completely opaque (1.0). You can set the value to anywhere in between 0 and 1.

Note: You can comment out the first line and try the second command alone. If it makes no change to the transparency of the window, then uncomment the first line and try again. Some commands will work on some OS, but not work the same on others.

Another good example of not working the same on every OS, this one works on Ubuntu. Most Application Title bars do not show an icon like on Windows. The icon appears on the System Title bar. The code is as follows to change it:

Code:
img = PhotoImage(file='/home/jarret/Python/JWB.gif')
root.wm_iconphoto(True, img)

In my case, a GIF file worked best. I used ImageMagick to convert an ‘ICO’ file to a ‘GIF’ file, and it worked. You need to specify the whole path unless you place the file in the same folder as the python file, then you can just specify a filename. What works is that it changes the icon in the System Bar when the Python code is running, but when you move over the icon, it says ‘Tk’. To change the title for the System Bar, use the code:

Code:
root = Tk(className="name")

Change ‘name’ to the title you want to appear on the System Bar, see Figure 3.

Figure 3.JPG

FIGURE 3

You can see that my application icon is a floppy disk. The application title bar is ‘NewIcon’. You’ll see that the System bar shows “Windows” when hovering over it. It shows the title on the top bar as well.

Conclusion

This is that basic start of installing and getting ‘tkinter’ initialized.

We also covered making a few changes to the initial window and we can get more into adding items in the next article.
 



Top