How to Create Tkinter Progress Bar and DropDown

Posted by Marta on February 1, 2023 Viewed 6299 times

Card image cap

In this article, I will show you step by step how you can add a progress bar and a dropdown widget to your user interface developed using Tkinter. This article has two parts. First, I will explain to you how to create a window and add the dropdown. And how to add a callback, so the interface reacts if the user changes the dropdown. In the second part, I will demonstrate how to add a progress bar using Tkinter. Let’s get started.

Install Tkinter

The Tkinter module is a built-in module. Therefore you don’t need to install it. You can import the module in your python file and use it.

Create a Tkinter Window

First, I will create an empty window. Here is the code to create a window of size 200 by 200:

from tkinter import Tk

class App(Tk):
    def __init__(self):
        super().__init__()  # Create the window
        self.geometry('200x200') #Resize

app = App()
app.mainloop()

What is this code exactly doing? I have created a class that inherits from Tk. The Tk class contains all the graphical functionality to create a window. In the constructor method, __init__, I will call the constructor of the superclass. That will make the window.

Then I have resized the window to 200 by 200 using the .geometry() method.

You can paste this code into IDLE or PyCharm, run it, and you will get your window created. Let’s move on to the next step, adding a dropdown.

Add Tkinter DropDown

Now I m going to show you how to add a dropdown like the one below. The dropdown allows you to select the gender, Male or Female. You can change these options to anything and add as many options as you like.

Here is the code to add the dropdown widget. I have placed the new piece of code between ## to mark the latest code added piece.

from tkinter import Tk, OptionMenu,StringVar

class App(Tk):
    def __init__(self):
        super().__init__()
        self.geometry('200x200')

        #NEW: Adding the dropdown ##
        self.gender_selected = StringVar()
        self.gender_selected.set("Select Gender")
		self.dropdown = OptionMenu(self, self.gender_selected, *["Male", "Female"])
        self.dropdown.grid(row=0,column=1)
        ###########################

app = App()
app.mainloop()

Code Explanation

What is this code doing? First, I have created a variable that will hold the value selected in the dropdown, called gender_selected, see lines 9 and 10. If you choose a different dropdown value, it will be saved in this variable.

Next, I have created the dropdown widget using the OptionMenu class. Lines 11 and 12. Please note that you need to import this class to use it. Otherwise, you will get a syntax error when trying to run the program. The OptionMenu class takes three parameters: the window that will contain the widget, the variable that holds the widget value, and a list with the dropdown option.

Next, I have specified the window where I want to place your dropdown, using the .grid() method. Using the grid() method is a crucial step because, if not added, the widget won’t be displayed.

Update when Tkinter dropdown changes

So far, I have added the dropdown; however, It will be better if our GUI reacts when I select something. That makes it more interactive and responsive. I will add a label that will get updated, displaying the chosen gender. See below that code to achieve this, from line 15 to line 23

from tkinter import Tk, OptionMenu,StringVar,Label


class App(Tk):
    def __init__(self):
        super().__init__()
        self.geometry('200x200')

        self.gender_selected = StringVar()
        self.gender_selected.set("Select Gender")

        self.dropdown = OptionMenu(self, self.gender_selected, *["Male", "Female"])
        self.dropdown.grid(row=0,column=1)

		# NEW Add the label  ##############
        self.label = Label(self, text="No Gender selected")
        self.label.grid(row=1,column=1)

        self.gender_selected.trace("w", callback=self.update_label)

    def update_label(self, *args):
        self.label.configure(text="Selected gender is {}".format(self.gender_selected.get()))
		
        ###################################
app = App()
app.mainloop()

Code Explanation

First, in line l6 and 17, I have added a label and place it within the window. And inline 19, I have used the .trace() method to link the dropdown widget with an action. Binding the dropdown with a method means when the dropdown changes, the callback executes the bound method.

And last bit, in line 21, I have added a new method with the action that should execute when the dropdown changes. In this case, I want the label text to change to display the dropdown value selected. I can achieve using the .configure() method, passing in as parameters the new text, which will be Select gender is, and after the value saved in the dropdown variable gender_selected.

Add Tkinter Progress Bar

Perfect! So far, we have seen how you can add a dropdown to your Tkinter Graphical User Interface. Now I am going to cover how you can add the progress bar and update it.

A progress bar is handy since it gives the user feedback about the progress of a background task. It can improve the user experience since it provides the user with a sense of how quickly the program is processing something and how much work is left.

I will create a GUI like the one you can see below, containing a progress bar and three buttons to control the progress bar. One of the buttons will start the progress. Another button to stop the progress bar, and the increment button will increment the progress bar just one step. Let’s see how we can achieve all these steps.

At this point, I will create a new file and add the code to create a window. I will get the code from the above section, ‘Create a Tkinter Window.’ Then add the label and the progress bar widget. Below you can find the code to do so, lines 10 to 15:

from tkinter import Tk, Label
from tkinter.ttk import Progressbar

class App(Tk):
    def __init__(self):
        super().__init__()
        self.geometry('200x200')

        # NEW: Added a label and the progress bar ######
        label = Label(self, text="Progess Bar")
        label.grid(row=0, column=0)

        self.progress_bar = Progressbar(self, orient="horizontal", mode="determinate")
        self.progress_bar.grid(row=0, column=1)
        ###############################################

app = App()
app.mainloop()

Code Explanation

What does this code do? First, it will create a label with the text Progress Bar, lines 10 and 11. Next, I will add the progress bar, lines 13 and 14. I will pass three parameters to the progress bar constructor method: the window that will contain the progress bar. The second parameter is the orientation. The third one is the mode. I will use a determinate method, which means there is an indicator inside the bar that moves from the beginning to the end.

Adding buttons to update progress bar

Now I will add the buttons to control the progress bar indicator. I will add three buttons:

  • Start
  • Stop
  • Increment

See below the code to add the three buttons, lines 17 to 22:

from tkinter import Tk, Label, Button
from tkinter.ttk import Progressbar

class App(Tk):
    def __init__(self):
        super().__init__()
        self.geometry('200x200')

        label = Label(self, text="Progess Bar")
        label.grid(row=0, column=0)

        self.progress_bar = Progressbar(self, orient="horizontal", mode="determinate")
        self.progress_bar.grid(row=0, column=1)

        ####################################################
        # NEW : Adding the buttons to control the progress bar
        start_button = Button(self, text='Start')
        stop_button = Button(self, text='Stop')
        increment_button = Button(self, text='Increment')
        start_button.grid(row=1,column=0)
        stop_button.grid(row=1,column=1)
        increment_button.grid(row=2,column=0)
        ####################################################
        
app = App()
app.mainloop()

This code bit is quite simple. I create the button and place it inside the window. The slightly more complicated section is coming next to link the button to action, so something happens after pressing.

Add the listener to update the progress bar.

Now I will add the listeners to the buttons. See the code below:

from tkinter import Tk, Label, Button, IntVar
from tkinter.ttk import Progressbar

class App(Tk):
    def __init__(self):
        super().__init__()
        self.geometry('200x200')
		label = Label(self, text="Progess Bar")
        label.grid(row=0, column=0)

        # NEW Add to keep track of the progress bar value
        self.value = IntVar()
        self.value.set(5)
        ######

        # Modified this line to add the variable parameter
        self.progress_bar = Progressbar(self, orient="horizontal", mode="determinate", variable=self.value)
        ##########
        self.progress_bar.grid(row=0, column=1)

		# Modified to add the command parameter
        stop_button = Button(self, text='Stop', command=self.stop_progress_bar)
        start_button = Button(self, text='Start', command=self.start_progress_bar)
        increment_button = Button(self, text='Increment', command=self.increment)
        ##################
        
        start_button.grid(row=1,column=0)
        stop_button.grid(row=1,column=1)
        increment_button.grid(row=2,column=0)

    # NEW: Added these functions to update the progress bar
    def stop_progress_bar(self):
        self.progress_bar.stop()

    def start_progress_bar(self):
        self.progress_bar.start()
        self.progress_bar.step(10)

    def increment(self):
        self.value.set(self.value.get()+5)
    ##########################################

app = App()
app.mainloop()

Code Explanation

First, we need to create a variable to keep track of the progress bar indicator, lines 12 and 13. Then I will link this variable to the progress bar widget, adding the variable parameter, see line 17, which means if the value increase, the progress bar will also increase. Therefore I can control the bar using this variable, named value.

Now that we have a way to control the bar, the next step is adding actions to the buttons. First, I will pass a command parameter to each of the buttons; see lines 22, 23, and 24. This command links the widget with a function, which will be executed when the button is pressed.

Next, I need to define the functions. I will create three functions: one to start the progress bar and stops the bar indicator. And the last one that will increment the indicator just by 5. See lines from 32 to 40.

Conclusion

To summarise, we have seen how to add a progress bar and a dropdown using Tkinter and how to link these widgets to actions to interact with the graphical interface. I hope this article was useful, and thank you for reading and supporting this blog!

Happy coding!

More Interesting Articles

Project-Based Programming Introduction

Steady pace book with lots of worked examples. Starting with the basics, and moving to projects, data visualisation, and web applications

100% Recommended book for Java Beginners

Unique lay-out and teaching programming style helping new concepts stick in your memory

90 Specific Ways to Write Better Python

Great guide for those who want to improve their skills when writing python code. Easy to understand. Many practical examples

Grow Your Java skills as a developer

Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.

Write Code as a Professional Developer

Excellent read for anyone who already know how to program and want to learn Best Practices

Every Developer should read this

Perfect book for anyone transitioning into the mid/mid-senior developer level

Great preparation for interviews

Great book and probably the best way to practice for interview. Some really good information on how to perform an interview. Code Example in Java