In the first and the second part of Tkinter tutorial, we discussed how to create simple GUI with basic GUI building blocks of Tkinter module. In this tutorial, we’ll go through how to build complex, yet very useful GUI features using Tkinter.
Adding Textbox widget and configuring it
We have seen how to add basic widgets to our Window. Let’s now try to configure our GUI based on user’s input. The most common way to get input from the user is textbox. The `tkinter` module supports a class named `Entry` to create a text box. Consider the below example:
import tkinter root_window = tkinter.Tk() root_window.geometry('300x200') root_window.title("Tkinter tutorial") def clicked(): res = "Hi " + txt_box.get() label_widget.configure(text=res) label_widget = tkinter.Label(root_window, text="Hi", font=("Arial Italic", 10)) label_widget.grid(column=0, row=0) txt_box = tkinter.Entry(root_window,width=10) txt_box.grid(column=1, row=0) fn_btn = tkinter.Button(root_window, text="Click", bg="grey", fg="black", font=("Arial Bold", 10), command=clicked) fn_btn.grid(column=2, row=0) root_window.mainloop()
In the above example, we have created a text box along with a few other widgets. The output is as follows:
If you enter a text on the text box and click the “Click” button, the program will display the string “Hi” concatenated along with the text got as input.
Creating a Dropdown box widget
There may occur situations where we need to get input from the user by making the user select from a list of options displayed in a dropdown/combo box. The ttk library provides a class named `Combobox` to create a dropdown/combo box widget. So, we need to import the ttk library to use this function. Let’s create a sample dropdown box widget to get the Gender from the user.
import tkinter from tkinter .ttk import * root_window = tkinter.Tk() root_window.geometry('300x200') root_window.title("Tkinter tutorial") label_widget = tkinter.Label(root_window, text="Gender", font=("Arial Italic", 10)) label_widget.grid(column=0, row=0) combo = Combobox(root_window) combo['values']= ("Male", "Female") combo.grid(column=1, row=0) root_window.mainloop()
This code creates a combo box widget as shown below.
Add a Checkbutton widget
The ttk library supports a class named `Checkbutton` to create checkbox widget. Let’s consider the below example:
from tkinter import * from tkinter.ttk import * main_window = Tk() main_window.geometry('300x200') chk_state = BooleanVar() chk_state.set(True) chk = Checkbutton(main_window, text='I agree to the terms and conditions of this site', var=chk_state) chk.grid(column=0, row=0) main_window.mainloop()
As you see, we have used `Checkbutton` class to create a check button. We can set the check box’s state by passing the check value to be enabled by default by using the `set` argument.
chk_state = BooleanVar() chk_state.set(True)
If you see, the check value is set to the checked state.
Creating Radiobutton widget
The ttk library provides `Radiobutton` class to add radio button widgets. Let’s create a basic restaurant order app that allows the user to select the size of pizza they want to order by clicking at the desired radio button.
from tkinter import * from tkinter.ttk import * main_window = Tk() main_window.geometry('600x200') label_widget = Label(main_window, text="Please select the size of pizza you like to order:", font=("Arial Italic", 10)) label_widget.grid(column=0, row=0) s1 = Spinbox(main_window, from_=0, to=100, width=5) main_window.mainloop()
Note: You must remember to set different values for each radio button.
Creating Message boxes
The reason why many users prefer the GUI interface is because it is user-friendly and makes the user know if an error/warning occurs. This is achieved through message boxes.
Tkinter module allows us to create Message Boxes, which are simple, yet widely used widgets. Message boxes can be used to display a message to the user to understand better what went wrong by either giving a warning or an error message.
Message boxes can also be used to allow the user to take a simple yes/no decision. The following example demonstrates the use of different types of message boxes.
from tkinter import messagebox main_window = Tk() main_window.geometry('600x200') def msgbox_demo(): messagebox.showinfo("Info", "This is a sample Message box") messagebox.showwarning("Warning", "Save before exiting") messagebox.showerror("Error", "File not found") okcancel = messagebox.askokcancel("Exit without saving?") print(okcancel) yesno = messagebox.askyesno("Continue?") print(yesno) b1 = Button(main_window, text='Display message boxes', command=msgbox_demo) b1.pack(fill='x') main_window.mainloop()
The above code displays the following output.
You can see the message boxes one after the other, by selecting the options displayed. The function `msgbox_demo` lets 5 message boxes pop up one after the other – each is displayed after the user interaction with the previous one. These message boxes return values based on the decisions, in sequence. We can choose the required message style according to our needs.
We can check the status of which button was clicked, by using the result variable. If the user clicks OK or yes or retry button, the function will return a True value. In case the user chooses no or cancel button, the function will return a False value.
Creating Spinbox widget
The Spinbox widget is similar to the Entry widget. The difference is that the entry widget allows the user to enter a value in any range. Whereas, the Spinbox widget provides the range of values for the user to choose from, from which, the user selects a value. It is used to give the user is a range of values to choose from. Below is a sample to create a Spinbox using Tkinter.
from tkinter import * main_window = Tk() main_window.geometry('600x200') label_widget = Label(main_window, text="Please select number of pizzas you would like to order:", font=("Arial Italic", 10)) label_widget.grid(column=0, row=0) s1 = Spinbox(main_window, from_=0, to=10, width=5) s1.grid(column=1, row=0) main_window.mainloop()
The output is as shown below.
Creating a Progress bar widget
Progress bar is a useful element of advanced GUI features. This is because the progress bar gives a clue to the user to know how long it takes to download, time taken to upload etc. by showing the progress of the task happening at the background, visually. This feature is a part of the `ttk` module. Hence, we need to import the ttk module for the feature to work. The following example shows a sample implementation of the progress bar feature using Tkinter:
from tkinter import * from tkinter.ttk import * main_window = Tk() main_window.geometry('300x200') style = Style() style.configure("black.Horizontal.TProgressbar", background='grey') pbar = Progressbar(main_window, length=200, style='black.Horizontal.TProgressbar') pbar['value'] = 40 pbar.grid(column=0, row=0) main_window.mainloop()
Here, we have created a Progressbar by first choosing the background color and then by applying the created style to the Progressbar.
Creating a Menu bar widget
Allowing the user to select an option from a menu is a common feature of graphical user interface. The Menubar widget combines at least many functional buttons (like Cut, Copy, or Paste). Creating even complicated GUIs can be done in a jiffy using Tkinter. Let’s look at the following example of creating a Menubar widget:
from tkinter import * from tkinter import Menu root = Tk() menu = Menu(root) list_option = Menu(menu) list_option.add_command(label='Cut') list_option.add_command(label='Copy') list_option.add_command(label='Paste') menu.add_cascade(label='Edit', menu=list_option) root.config(menu=menu) root.mainloop()
We have created a Menubar using `menu.add_cascade` function. We can create multiple menu items we need in the same way.
We have covered the significant aspects of Python GUI development by using Tkinter. Hope this tutorial would help you to quickly build GUIs in your Python projects.