Welcome to the next step on this Python voyage. Today we will be creating graphical user interfaces using the powerful Tkinter library. Graphical user interfaces are referred to as GUI and can be pronounced as Gooey. GUI is a visual way of interacting with a computer using items such as windows, icons and menus. These are present in most modern operating systems and substantially improves communication between yourself and the computing device.
GUI can be created using many different external packages in Python however this guide will focus on the powerful Tkinter library. This library is pre-installed on all default Python. This means once you have utilised an import statement to your script all the functionality of this library will be ready and raring to go. The contents to this tutorial can be seen below.
- Tkinter Overview
- Check For And Get Tkinter
- Code Your First Buttons
- Addition and Subtraction Calculator
- The Next Step
- Final Note
- Download the Codes
There are several related tutorials on our website to help you become a coding virtuoso. A great place to start would be Python Rundown and Main Windows and Python and MicroPython - Compare and Access. These will also tell you locations to download the programming language Python and places to access online Python emulators. Python is a great language to utilise with Raspberry Pi Boards such as Raspberry Pi 4 Model B 8GB which are micro-processors that can easily fit on the palm of your hand!
As always if you have any questions, queries or things to add please let us know your thoughts!
Tkinter Overview
Tkinter is a lightweight toolkit and one of the simplest GUI solutions for Python. This library allows us to create windows and populate them with buttons, menu bars, text/number input sections, images, radio buttons, checkboxes, sliders, dropdown menus and labels. All these GUI objects are fully customisable. For instance the Tkinter pop-up window can be resized, minimised, maximised and closed. To create all of this from scratch it would involve lots of code and logic but thankfully because of the Tkinter library we do not need to do that. It is also a great tool to interact with databases and display graphs or charts.
Check For and Get Tkinter
First we will check if Tkinter is working and installed on your version of Python by utilising the Command Prompt. To access the Command Prompt on Windows computers press the Windows key on your keyboard then type Command Prompt to the search bar. Clicking on the application icon will open this interface. Now you can check Tkinter by typing the below line directly into your Command Prompt.
python -m tkinter
Now by pressing the enter key you will execute this line. If Tkinter has been installed correctly you will see a new pop-up window appear to your screen with the name tk in the titlebar. It will have two interactive buttons, a Click Me button and a Quit button. It will also display the version of Tkinter installed. Seen below is both the Command Prompt with the above line entered and the Tkinter pop-up window which appears when the line is executed. If this appears on your system then all is good, Tkinter is installed and is operating properly.
However, if the Command Prompt displays an error then most likely Tkinter has not been installed to your version of Python. The quickest way to fix this is to type directly into the Command Prompt the below.
pip install tk
By pressing the enter key the Command Prompt it will download and install the newest version of Tkinter. Directly below you can see the results of this line when it has been executed in the Command Prompt. Another way to do this is by going to the Official Python Website and downloading the most up-to-date software. Then when installing Python either use the default settings or when using advanced options make sure to do two things. Tick the checkbox for td/tk and IDLE and tick the checkbox for Add Python to environmental variables. Both of these options that appear during the install wizard you can see highlighted in the images further below. If you are still running into errors a tutorial with potential solutions is Installing Python Packages.
Code Your First Buttons
So with that, let us crack on and create our first GUI. We will start by creating a Tkinter pop-up window populated with buttons that perform commands when clicked. In this case one of the commands will be to print a value to the Python IDLE Console every time it is clicked. Another button will be set up to close the Tkinter pop-up window once it has been clicked. Below is the Python code to do just this. It has been extensively commented so that it can be followed through step by step. You can either type out the code in your Python Programming Window, copy and paste it there or download the code from the bottom section of this page and open it using the Python IDLE Shell.
#Using the import * means we are importing everything inside the designated library #Thus the line below imports all functionality from Tkinter library. from tkinter import * #This creates a GUI Tk() Variable. GUI = Tk() #This function gives the window a name. GUI.title('The Two Button Window') #Set the size of the GUI Window. GUI.geometry("300x220") #Creating a user-created function which will run whenever the button is clicked. def callback(): print('You have clicked!') #This defines the button, stating the button name, what window it is on #the text that fills the button, the dimensions of the button and the #command of the button (what it is that it will do ergo quit the application). #The first button references the user-created function above. button1 = Button(GUI, text = "Click Me", width=20, height = 10, command = callback) button2 = Button(GUI, text = "Quit", width=10, command = quit) #Determines location of buttons. Another method to do this is using the function pack().
#Another way to do this is using the function button1.place(x=__, y=___). #These buttons will be stacked underneath each other with 80 pixels of padding on the #x axis and 5 pixels up and down. button1.grid(row = 0, column = 1, padx=80, pady=5) button2.grid(row = 2, column = 0, columnspan = 2) #This is a way of creating an infinite loop. The application will run, wait for #events to occur and process the events so long as the window is not closed. #Another way to make an infinite loop would be creating while True infinite loop. mainloop()
Thus, when you run the above code in the Python Programming Window a Tkinter pop-up window will appear on the screen with two buttons. Below to the left you can see the two buttons we have created in the Tkinter pop-up window. Below to the right you can see the output to the Python IDLE Shell after the Click Me button has been pressed three times. When you press the Quit button it will close the Tkinter pop-up window and the Python IDLE Window.
Addition and Subtraction Calculator
This will demonstrate how to create an addition and subtraction calculator using Tkinter. This is an excellent script to put together as it highlights numerous functionalities of this library. Making practical tools like this demonstrates just a slice of the world of possibilities you can do with Tkinter. The script is seen below and has been extensively commented so you can follow through effectively. You can either type out the code in your Python Programming Window, copy and paste it there or download the code from the bottom section of this page and open it using the Python IDLE Shell.
#Using the import * means we are importing everything inside the designated library #Thus the line below imports all functionality from Tkinter library. from tkinter import * #This creates a GUI tk() Variable called calc. calc=Tk() #This function gives the window a name. calc.title('Adding and Subtracting Calculator') #Set the size of the GUI Window. calc.geometry("720x180") #Make our GUI a little more pleasing to the eye by altering the background colours. calc['bg']="powder blue" #Below is creating Labels on inside our GUI window. This is so users can #understand how to use this calculator. The Labels are given a location on the window #and also text is decided and made bold if important. FirstLabel=Label(calc, text='First Number', font=('bold')) FirstLabel.place(x=40, y=20) SecondLabel=Label(calc, text='Second Number', font=('bold')) SecondLabel.place(x=40, y=88) ThirdLabel=Label(calc, text='Or') ThirdLabel.place(x=358, y=83) FourthLabel=Label(calc, text='Result', font=('bold')) FourthLabel.place(x=556, y=52) #This creates entry locations for the user to type numbers into the calculator. Also, a place #for the result to be displayed is created. FirstNumber=Entry() FirstNumber.place(x=120, y=52) SecondNumber=Entry() SecondNumber.place(x=120, y=120) ResultNumber=Entry() ResultNumber.place(x=520, y=83) #Below is the user-created function which will run whenever the Add button is clicked. #First, we start by defining the function and giving it a name. All code of this function #will be indented. def add(): #Whenever this function is run initially we clear the result location. This is to stop #number from stacking up and thus displaying the wrong result. ResultNumber.delete(0, 'end') #Now it grabs the numbers from the first and second entry window. It also double-checks #that the data by converting the data inputted into an integer type. First = int(FirstNumber.get()) Second = int(SecondNumber.get()) #Here is the actual calculation occurring. Addition of both the numbers inputted Calculation = First Second #Now you can display the number underneath the Result label. ResultNumber.insert(END, str(Calculation)) #Same process is done below for the subtraction function. def sub(): ResultNumber.delete(0, 'end') First = int(FirstNumber.get()) Second = int(SecondNumber.get()) Calculation = First - Second ResultNumber.insert(END, str(Calculation)) #Now that the functionality has been coded, we can create buttons that reference #the above functionality. These buttons are also given a location on the window. Button1=Button(calc, text='Add', command=add) Button1.place(x=310, y=80) Button2=Button(calc, text='Subtract', command=sub) Button2.place(x=390, y=80) #This is a way of creating an infinite loop. The application will run, wait for #events to occur and process the events so long as the window is not closed. #Another way to make an infinite loop would be creating while True infinite loop. calc.mainloop()
Below shows the pop-up Tkinter window when running this code in the Python Programming Window. You can see two numbers being added together. Pretty swell!
The Next Step
And with that this will be the end of this particular Python journey. I hope you have followed along and gained from these guides. Python is truly a powerhouse programming language and if I have even helped encourage one person to experiment with some coding then I am immensely satisfied. The next step is to keep making!
Final Note
The one last thing I will leave you is The Zen of Python. Long time Pythoneer Tim Peters succinctly channels the guiding principles for Python design. I hope it will put you in good steed for your future coding adventures.
The Zen of Python
Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!
DOWNLOAD THE CODES
Below you can find all the code for the above examples. You will be able to run the codes here on your own computing device and modify the code at your leisure. Open the scripts with Python IDLE Shell and run them using the Python Programming Window.