Tkinter Quickstart Guide
What is Tkinter?
Tkinter (which is short for Tk Interface) is a library for creating GUIs in Python. It is extremely easy to use, and it comes installed by default with Python making it very quick and painless to implement.
How to Install Tkinter
As I've said Tkinter comes with Python as one of the default standard libraries.
Download Python.
If you're on Windows or Mac, navigate to this website:
https://www.python.org/downloads/
After downloading it, you'll want to run the installer
If you're on Ubuntu (or any Linux that uses apt package manager), run the following command and it will be downloaded and installed for you.
sudo apt-get install python3
NOTE: in some versions of Ubuntu, Tkinter doesn't come with the default installation of Python, so you'll have to install it with the following command
sudo apt-get install python3-tk
And voila! By installing the latest stable version of Python, you've also installed Tkinter.
How to Use Tkinter
How to spawn a Basic GUI Window
To spawn a basic GUI window, run the following code:
from tkinter import *
root = Tk()
root.title("Hello World!")
root.geometry('300x300')
root.mainloop()
You'll have to save this code in a document and name it something.py and then run it by typing:
python something.py
How to use Buttons, Labels, and Inputs
from tkinter import *
root = Tk()
root.title("Hello World!")
root.geometry('300x300')
label = Label(root, text = "hello")
label.grid()
entry = Entry(root, width=10)
entry.grid()
def click():
value = entry.get()
label.configure(text = value)
button = Button(root, text = "Click", command=click)
button.grid(column=1, row=0)
root.mainloop()
The above code is a modification of the original window.
It will allow you to do the following:
- Enter text into an input field
- Click a button which will run the function "click" when clicked
- Display text on the GUI
Tkinter uses different widgets to get things done. For example, the Label widget will allow you to display text.
label = Label(root, text = "hello")
label.grid()
The Entry widget will allow you to have an input field
entry = Entry(root, width=10)
entry.grid()
The Button widget will allow you to have a button.
button = Button(root, text = "Click", command=click)
button.grid(column=1, row=0)
Setting the command variable equal to a function will cause the button to run that function as a command once clicked.
Setting the grid property will allow for the elements/widgets to be displayed within the GUI
So now you know how to:
- Take inputs and store them in variables
- Utilize buttons to execute functions
- Print text on the GUI in the form of a label
Resources
For additional resources on Python and Tkinter, check out the official docs.
Also, check out these fantastic tutorials on Geeks for Geeks to gain a more in-depth understanding.