Python

Python GUI examples (Tkinter Tutorial)

In this tutorial, we will learn how to develop graphical user interfaces by writing some Python GUI examples using Tkinter package.

Tkinter package is shipped with Python as a standard package, so we don’t need to install anything to use it.


Tkinter package is a very powerful package. If you already have installed Python, you may use IDLE which is the integrated IDE that is shipped with Python, this IDE is written using Tkinter. Sounds Cool!!

We will use Python 3.6, so if you are using Python 2.x, it’s strongly recommended to switch to Python 3.x unless you know the language changes so you can adjust the code to run without errors.

I assume that you have a little background about Python basics to help you understand what we are doing.

We will start by creating a window then we will learn how to add widgets such as buttons, combo boxes, etc, then we will play with their properties, so let’s get started.

 

Create your first GUI application

First, we will import Tkinter package and create a window and set its title:

The result will be like this:

Python GUI examples create app

Awesome!! Our application just works.

The last line which calls mainloop function, this function calls the endless loop of the window, so the window will wait for any user interaction till we close it.

If you forget to call the mainloop function, nothing will appear to the user.

 

Create a label widget

To add a label to our previous example, we will create a label using the label class like this:

lbl = Label(window, text="Hello")

Then we will set its position on the form using the grid function and give it the location like this:

lbl.grid(column=0, row=0)

So the complete code will be like this:

And this is the result:

Python GUI examples add label

Without calling the grid function for the label, it won’t show up.

Set label font size

You can set the label font so you can make it bigger and maybe bold. You can also change the font style.

To do so, you can pass the font parameter like this:

lbl = Label(window, text="Hello", font=("Arial Bold", 50))

Python GUI examples label font

Note that the font parameter can be passed to any widget to change its font not labels only.

Great, but the window is so small, we can even see the title, what about setting the window size?

Setting window size

We can set the default window size using geometry function like this:

window.geometry('350x200')

The above line sets the window width to 350 pixels and the height to 200 pixels.

Let’s try adding more GUI widgets like buttons and see how to handle button click event.

 

Adding a button widget

Let’s start by adding the button to the window, the button is created and added to the window the same as the label:

So our window will be like this:

The result looks like this:

Python GUI examples add button

Note that we place the button on the second column of the window which is 1. If you forget and place the button on the same column which is 0, it will show the button only, since the button will be on the top of the label.

Change button foreground and background colors

You can change foreground for a button or any other widget using fg property.

Also, you can change the background color for any widget using bg property.

btn = Button(window, text="Click Me", bg="orange", fg="red")

Python GUI examples button colors

Now, if you tried to click on the button, nothing happens because the click event of the button isn’t written yet.

Handle button click event

First, we will write the function that we need to execute when the button is clicked:

Then we will wire it with the button by specifying the function like this:

btn = Button(window, text=“Click Me”, command=clicked)

Note that, we typed clicked only not clicked() with parentheses.

Now the full code will be like this:

And when we click the button, the result as expected:

Python GUI examples button click event

Cool!!

 



Get input using Entry class (Tkinter textbox)

In the previous Python GUI examples, we saw how to add simple widgets, now let’s try getting the user input using Tkinter Entry class (Tkinter textbox).

You can create a textbox using Tkinter Entry class like this:

txt = Entry(window,width=10)

Then you can add it to the window using grid function as usual

So our window will be like this:

And the result will be like this:

Python GUI examples add entry widget

Now, if you click the button, it will show the same old message, what about showing the entered text on the Entry widget?

First, you can get entry text using get function. So we can write this code to our clicked function like this:

If you click the button and there is a text on the entry widget, it will show “Welcome to” concatenated with the entered text.

And this is the complete code:

Run the above code and check the result:

Python GUI examples entry widget event

Awesome!!

Every time we run the code, we need to click on the entry widget to set focus to write the text, what about setting the focus automatically?

Set focus to entry widget

That’s super easy, all we need to do is to call focus function like this:

txt.focus()

And when you run your code, you will notice that the entry widget has the focus so you can write your text right away.

Disable entry widget

To disable entry widget, you can set the state property to disabled:

txt = Entry(window,width=10, state='disabled')

Python GUI examples disable entry widget

Now, you won’t be able to enter any text.

 

Add a combobox widget

To add a combobox widget, you can use the Combobox class from ttk library like this:

Then you can add your values to the combobox.

Python GUI examples combobox

As you can see, we add the combobox items using the tuple.

To set the selected item, you can pass the index of the desired item to the current function.

To get the select item, you can use the get function like this:

combo.get()

 

Add a Checkbutton widget (Tkinter checkbox)

To create a checkbutton widget, you can use Checkbutton class like this:

chk = Checkbutton(window, text='Choose')

Also, you can set the checked state by passing the check value to the Checkbutton like this:

Check the result:

Python GUI examples add checkbutton

Set check state of a Checkbutton

Here we create a variable of type BooleanVar which is not a standard Python variable, it’s a Tkinter variable, and then we pass it to the Checkbutton class to set the check state as the highlighted line in the above example.

You can set the Boolean value to false to make it unchecked.

Also, you can use IntVar instead of BooleanVar and set the value to 0 or 1.

These examples give the same result as the BooleanVar.

 


Add radio buttons widgets

To add radio buttons, simply you can use RadioButton class like this:

rad1 = Radiobutton(window,text='First', value=1)

Note that you should set the value for every radio button with a different value, otherwise, they won’t work.

The result of the above code looks like this:

Python GUI examples add radio button

Also, you can set the command of any of these radio buttons to a specific function, so if the user clicks on any one of them, it runs the function code.

This is an example:

Pretty simple!!

Get radio button value (selected radio button)

To get the currently selected radio button or the radio button value, you can pass the variable parameter to the radio buttons and later you can get its value.

Python GUI examples get radio button value

Every time you select a radio button, the value of the variable will be changed to the value of the selected radio button.

 

Add a ScrolledText widget (Tkinter textarea)

To add a ScrolledText widget, you can use the ScrolledText class like this:

Here we specify the width and the height of the ScrolledText widget, otherwise, it will fill the entire window.

The result as you can see:

Python GUI examples add scrolledtext

Set scrolledtext content

To set scrolledtext content, you can use the insert method like this:

txt.insert(INSERT,'You text goes here')

Delete/Clear scrolledtext content

To clear the contents of a scrolledtext widget, you can use delete method like this:

txt.delete(1.0,END)

Great!!

 


Create a MessageBox

To show a message box using Tkinter, you can use messagebox library like this:

Pretty easy!!

Let’s show a message box when the user clicks a button.

Python GUI examples show messagebox

When you click the button, an info messagebox will appear.

Show warning and error messages

You can show a warning message or error message the same way. The only thing that needs to be changed is the message function

Show askquestion dialogs

To show a yes no message box to the user, you can use one of the following messagebox functions:

You can choose the appropriate message style according to your needs. Just replace the showinfo function line from the previous line and run it.

Also, you can check what button was clicked using the result variable

If you click OK or yes or retry, it will return True value, but if you choose no or cancel, it will return False.

The only function that returns one of three values is askyesnocancel function, it returns True or False or None.

 

Add a SpinBox (numbers widget)

To create a Spinbox widget, you can use Spinbox class like this:

spin = Spinbox(window, from_=0, to=100)

Here we create a Spinbox widget and we pass the from_ and to parameters to specify the numbers range for the Spinbox.

Also, you can specify the width of the widget using the width parameter:

spin = Spinbox(window, from_=0, to=100, width=5)

Check the complete example:

Python GUI examples spinbox

You can specify the numbers for the Spinbox instead of using the whole range like this:

spin = Spinbox(window, values=(3, 8, 11), width=5)

Here the Spinbox widget only shows these 3 numbers only 3, 8 and 11.

Set default value for Spinbox

To set the Spinbox default value, you can pass the value to the textvariable parameter like this:

Now, if you run the program, it will show 36 as a default value for the Spinbox.

 

Add a Progressbar widget

To create a progress bar, you can use the progressbar class like this:

You can set the progress bar value like this:

bar['value'] = 70

You can set this value based on any process you want like downloading a file or completing a task.

Change Progressbar color

Changing Progressbar color is a bit tricky, but super easy.

First, we will create a style and set the background color and finally set the created style to the Progressbar.

Check the following example:

And the result will be like this:

Python GUI examples change progressbar color

 


Add a filedialog (file & directory chooser)

To create a file dialog (file chooser), you can use the filedialog class like this:

After you choose a file and click open, the file variable will hold that file path.

Also, you can ask for multiple files like this:

files = filedialog.askopenfilenames()

Specify file types (filter file extensions)

You can specify the file types for a file dialog using filetypes parameter, just specify the extensions in tuples.

file = filedialog.askopenfilename(filetypes = (("Text files","*.txt"),("all files","*.*")))

You can ask for a directory using askdirectory method:

dir = filedialog.askdirectory()

You can specify the initial directory for the file dialog by specifying the initialdir like this:

Easy!!

 

Add a Menu bar

To add a menu bar, you can use menu class like this:

First, we create a menu, then we add our first label, and finally, we assign the menu to our window.

You can add menu items under any menu by using add_cascade() function like this:

menu.add_cascade(label='File', menu=new_item)

So our code will be like this:

Python GUI examples add menu bar

Using this way, you can add many menu items as you want.

Python GUI examples menu add cascade

Here we add another menu item called Edit with a menu separator.

You may notice a dashed line at the beginning, well, if you click that line, it will show the menu items in a small separate window.

You can disable this feature by disabling the tearoff feature like this:

new_item = Menu(menu, tearoff=0)

Just replace the new_item in the above example with this one and it won’t show the dashed line anymore.

I don’t need to remind you that you can type any code that works when the user clicks on any menu item by specifying the command property.

new_item.add_command(label='New', command=clicked)

 

Add a Notebook widget (tab control)

To create a tab control, there are 3 steps to do so.

  • First, we create a tab control using Notebook class
  • Create a tab using Frame class.
  • Add that tab to the tab control.
  • Pack the tab control so it becomes visible in the window.

Python GUI examples notebook widget

You can add many tabs as you want the same way.

Add widgets to Notebooks

After creating tabs, you can put widgets inside these tabs by assigning the parent property to the desired tab.

Python GUI examples add widgets to notebooks

Add spacing for widgets (padding)

You can add padding for your controls to make it looks well organized using padx and pady properties.

Just pass padx and pady to any widget and give them a value.

lbl1 = Label(tab1, text= 'label1', padx=5, pady=5)

Just that simple!!

In this tutorial, we saw many Python GUI examples using Tkinter library and we saw how easy it’s to develop graphical interfaces using it.

This tutorial covers main aspects of Python GUI development not all of them. There is no tutorial or a book can cover everything.

I hope you find these examples useful. Keep coming back.

Thank you.

Mokhtar Ebrahim
I'm working as a Linux system administrator since 2010. I'm responsible for maintaining, securing, and troubleshooting Linux servers for multiple clients around the world. I love writing shell and Python scripts to automate my work.

37 thoughts on “Python GUI examples (Tkinter Tutorial)

      1. rad1 = Radiobutton(window,text=’First’, value=1, command=clicked)

        def clicked():

        # Do what you need
        this is not working properly.
        Traceback (most recent call last):
        File “C:/Users/nishumesh/Documents/Python/GUI/Ex-15.py”, line 13, in
        rad1 = Radiobutton(window,text=’First’,value=1,command=clicked)
        NameError: name ‘clicked’ is not defined

        1. Write any code on clicked() function and when you click on the radio button, it should run the clicked() function code.

        2. Hi Umesh,

          the def definition needs to be placed before you refer to it in the rad1 initialization.

          Cheers,
          Senfman

  1. Hello, nice tutorial!

    I just went through it, and well, pretty much mixed all the bits in one window!

    So a problem showed up when wanting to use the Notebook widget, and it’s that I had a label at the very top acting as a “title” (the very first example you show), and wanted to add the tabs underneath the title, and it wouldn’t let me, it seems like the moment you use Notebook you need to put things inside (_tkinter.TclError: cannot use geometry manager grid inside . which already has slaves managed by pack).

    Something else that I tried is, animate the Progressbar with a for steps_ in range(100) and changing the value in every step after sleeping for like 0.5 sec, but that didn’t work either, it just “counted” and then filled it all in one go. Also I though of adding a progress bar in a messagebox, as in “Processing” and when it finishes loading, close the message box, but a quick query proved that to be trickier than I though.

    Well, thanks for the effort, and now I just gotta keep diggin! 🙂

      1. Sorry I was out and about, I put up a quick example using your code, since I was using silly variable names and stuff, but it boils down to this:

        My idea was to have the first label as a Title, much like an h1/h2 in web, in the inside the app window, and then below it having the tabs.

        I assume this won’t work because it’s not the way to do it, I guess I’m missing come kind of container widget, where I could potentially add the tabs in it.

        1. Your error happens because you mix pack and grid in the same window.
          So if you use grid, don’t use pack on another component.
          And regarding your positioning, try to use another row for the components under your label.
          I mean use row 0 for your label and row 1 for others. Since you use row 0 for everything and that will put them on the same line.

        2. Traceback (most recent call last):
          File “C:/Users/tab.py”, line 32, in
          tab_control.pack(expand=1, fill=’both’)
          File “C:\Users\lib\tkinter\__init__.py”, line 2140, in pack_configure
          + self._options(cnf, kw))
          _tkinter.TclError: cannot use geometry manager pack inside . which already has slaves managed by grid

          1. I think you are using both grid and pack on the same window for different controls which is not correct.

  2. Hi Max… do you know of any “DataGrid” component to use in python…

    here is a demo link I quick google of the .net dataGrid “https://youtu.be/Sm5mxkytfWk”

  3. hi,
    it was nice tutorial, but i want to know more, for example how to save your contents or values, data in a file txt, and also i want to know how to create a button that each time i click on it create’s a new button :/

    1. Hey,
      The above examples shows all examples you mentioned if you understand them well.
      Ex: we showed how to create a button and we showed how to program the click event.
      So you can put the button creation code in the click event to achieve what you want. So the idea is so simple.

      1. thanks for your fast respond 🙂
        yes i did understand every each one of the examples, but tell me if i created this button with a command that create another button each time i click on it every created button will have the same name,text, values and everything. i want for every button to be unique, how i can do that? i tried loops but didn’t work for me 🙁

        1. Well,
          If you are using Python 3.6, you can use exec function with f formatting to generate dynamic variables like this:

          from tkinter import *
          window = Tk()
          for x in range(0, 3):
          exec(f'btn_{x} = Button(window, text="Click Me")')

  4. from tkinter.ttk import *
    why is this giving me an error , using python 3.6?? plz help

    and also says that Tk is not defined in follwing exp.
    from tkinter import *

    window = Tk()

    window.title(“Welcome to LikeGeeks app”)

    window.mainloop()

        1. Save a .py in the same folder as a python script using tkinter that you know works called “tkinter” and try and run your python script that works. I guarantee it wont run because when you try to import it will use the tkinter.py that you made and obviously not contain the necessary code. It was an error I was having earlier this week and I’ve just retested and I am certain that is the problem. It may or may not be this person’s problem but it definitely breaks tkinter code if you name a file tkinter.py

  5. (radio buttons) In some cases, ‘selected = IntVar()’ will not work (ie: ‘variable=selected’ will not update the ‘selected’ var. In those cases ‘selected = IntVar(window)’ should do the trick. ( ‘window’ being the used name in ‘window = Tk()’)

  6. Is there a way to return the entry that can be used for other functions?
    For example, I ask user to enter 3 different numbers then pass these 3 numbers to another function and do the calculation.
    Thank you in advance.

    1. You can call the function normally inside the button click event. This function can carry any number of parameters.

Leave a Reply

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