Start Creating Desktop Apps in Python With the Tkinter GUI Library

Tkinter is a Graphical User Interface (GUI) toolkit you should try out if you want to explore the power of Python in creating desktop apps.

Here, we take a look at the basics of the Tkinter GUI module.

Tkinter Setup

Typically, you don’t need to install tkinter separately if you’ve installed a later version of Python, starting with Python 3. The library may not work with old Python versions, though. This is a common problem for Mac and Linux users, as these OSes usually come with older versions of Python by default.

Generally, to use the tkinter module, ensure that you download and install the latest compatible version of Python on your PC from the official python.org website.

If you’re on Mac, alternatively, you can download the latest version of ActiveTcl, a tkinter compiler from ActiveState.

How to Use Tkinter

Tkinter depends on its built-in TK class. And it wraps up all the events within the GUI in a mainloop. Thus, the mainloop wrapper makes your tkinter code executable.

To get started with tkinter:

from tkinter import Tk
Tk().mainloop()

Running the code above spins up an empty tkinter frame.

The customization features of Tkinter, however, are in its built-in widgets.

To use these widgets, you can import them from tkinter by replacing from tkinter import Tk with:

from tkinter import *
t = Tk()
t.mainloop()

You can also adjust the Window size with the geometry function and then specify a title using the title widget of tkinter:

t = Tk()
t.geometry("600x600")
t.title("Tk Tutorial")
t.mainloop()

Tkinter Label Widget

Tkinter lets you write plain texts directly to the GUI using the Label widget:

t = Tk()
Label(t, text = "MUO Tkinter tutorial").grid()
t.mainloop()

The grid() method, however, is an alternative to the pack() method. It sticks your widgets to the GUI, making them visible.

You can also specify a font for your Label text:

t = Tk()
Label(t, text = "MUO Tkinter tutorial", font=(60)).grid()
t.mainloop()

Working With the Button Widgets in Tkinter

Buttons are some of the most used widgets in tkinter. And you can add these clickable buttons to your GUI using the various built-in button widgets.

Here’s how to add a primary button to your GUI using the Button widget:

t = Tk()
Button(t, text = "Clickable", bg = "black", fg = "white").grid()
t.mainloop()

The bg and fg keywords describe the background color of the button and the color of the text within it respectively.

You can also adjust the dimension of the button by including the height and width parameters:

t = Tk()
Button(t, text = "Clickable", bg = "black", fg = "white", height="2", width="10").grid()
t.mainloop()

Here’s the output for that:

And if you want to make the button more visually appealing, you can include a relief keyword and then adjust its border width:

t = Tk()
Button(t, text="Clickable", bg="blue", fg="white",
height=2, width=10, relief=RAISED, borderwidth=6).grid()
t.mainloop()

And that looks like this:

Replace RAISED with FLAT to see how that comes through.

You can add as many buttons as you like. But you be careful to avoid content overlap.

To avoid overlap, you can specify the row and column position for each button:

t = Tk()
Button(t, text=1, bg="black", fg="white").grid(row=1, column=1)
Button(t, text=2, bg="black", fg="white").grid(row=2, column=1)
Button(t, text=3, bg="black", fg="white").grid(row=3, column=1)
Button(t, text=4, bg="black", fg="white").grid(row=4, column=1)
t.mainloop()

An optional command keyword, however, adds events to the Button widget. In essence, it anchors an optional function that handles certain events when you click a button.

The code below, for instance, multiplies the value of each button by 6 when you click it. And it’s based on a pre-defined function:

def buttonpress(r):
r = 6*r
Label(t, text=r, font=(60)).grid(row=5, column=2)
t = Tk()
Button(t, text = 1, bg = "black", fg = "white", width = 10, height = 2,
command = lambda:buttonpress(1)).grid(row=1, column = 1, pady = 6)
Button(t, text = 2, bg = "black", fg = "white", width = 10,
command = lambda:buttonpress(2)).grid(row = 2, column = 1, pady = 6)
Button(t, text = 3, bg = "black", fg = "white", width = 10,
command = lambda:buttonpress(3)).grid(row = 3, column = 1, pady = 6)
Button(t, text = 4, bg = "black", fg = "white", width = 10,
command = lambda:buttonpress(4)).grid(row = 4, column = 1, pady = 6)
t.mainloop()

In the above code, buttonpress handles the multiplication event. The Button widget then points to that event handler using an anonymous lambda function.

And if you’re worried about the pady keyword, it distinctly separates each button across the row. Replacing this with padx separates the buttons across the column. And you can use both keywords simultaneously to separate the buttons across both axes as you desire.

That said, you don’t want to reinvent the wheel for every button as you did in the previous code. This slows down execution time, plus it makes your code hard to read and narrow down.

But you can use a for loop to avoid this repetition.

So here’s a shorter and better version of the above code:

def buttonpress(r):
r = 6*r
Label(t, text = r, font = (60)).grid(row = 5, column = 2)
t = Tk()
a = [1, 4, 6, 7]
for i in a:
j = lambda y = i:buttonpress(y)
Button(t, text = i, bg = "black", fg = "white", width = 10, height = 2,
command=j).grid(row = i, column = 1, pady = 6)
t.mainloop()

Let’s further explore the power of for loop to add menu buttons to your GUI:

from tkinter import *
t = Tk()
buttons = ["Files", "Dashboard", "Menu", "Settings", "Help"]
m = 0
for i in range(len(buttons)):
# Get each text in the buttons array using a list index as m increases.
# Then let the column increase by 1 through the length of the array:

Menubutton(t, text=buttons[m], bg="blue", fg="white").grid(row=5, column=i)
m += 1
t.mainloop()

Adding check buttons to your GUI is quite easy as well:

t = Tk()
Checkbutton(t, text = "Select option").grid()
t.mainloop()

Feel free to multiply that check button using the for loop, as we did earlier.

How to Create a Dropdown Menu With Tkinter’s Menu Widget

The Menu widget lets you design clickable dropdown menus in tkinter.

As stated earlier, tkinter offers many widget options. And you’ll use some of them while designing your dropdown menu.

Here are some of the common widgets options you’ll come across while making a dropdown:

  • add_cascade: It displays a menu label and sticks it where it belongs.
  • add_separator: It demarcates submenus and groups them into upper and lower submenus.
  • add_command: This is where you give your submenu a name. Ultimately, it accepts a command argument where you can specify an event handler.

Here’s a dropdown example that uses these three options:

from tkinter import *
t = Tk()
fileOptions = ["New", "open", "Save", "Save as"]
fileOptionsAfterseparator = ["Import", "Export", "Exit"]
viewOptions = ["Transform", "Edit", "Create"]
menuBar = Menu(t)
file = Menu(menuBar, tearoff=0)
for i in fileOptions:
file.add_command(label=i, command=None)
file.add_separator()
for i in fileOptionsAfterseparator:
file.add_command(label=i, command=None)
menuBar.add_cascade(label="File", menu=file)
View = Menu(menuBar, tearoff=0)
for i in viewOptions:
View.add_command(label=i, command=None)
menuBar.add_cascade(label="View", menu=View)
t.config(menu=menuBar)
t.mainloop()

See how that looks:

Tkinter Options Menu

An Optionmenu, unlike the Menu dropdown, switches its label to a selected option.

Although you can specify a default label value for an options menu, it has no label by default.

Related: Python Project Ideas Suitable for Beginners

Here’s how to create an options menu in tkinter:

t = Tk()
Omenu = StringVar() #set the variable type of the options
Omenu.set("MUO") #specify a default value for the menu icon
OptionMenu(t, Omenu, "MUO", "Amazon", "Tutorial").grid()
t.mainloop()

Build a Reusable Desktop App With Tkinter

Tkinter offers an array of features that helps you make interactive GUI desktop apps. Although it may not have many flexible beautifying features like some other Python GUI modules, it’s still a handy tool worth exploring. And while the examples here only show some of the basics concepts, tkinter offers more advanced features that you can try out.

That said, you can build a GUI desktop calculator, make a mini text editor, or even create a GUI desktop app to manage your inventories. If you want to spread your wings and become a desktop GUI major, you can even check out other GUI modules of Python.

Author: Idowu Omisola

Source: Idowu Omisola.” Start Creating Desktop Apps in Python With the Tkinter GUI Library”. Retrieved From https://www.makeuseof.com/start-creating-desktop-apps-in-python-with-the-tkinter-gui-library/

All Rights Of This Article Reserved To MakeUseOf

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: