Welcome to this tutorial on tkinter GUI widgets. In this article, I will introduce you to all the Tkinter Widgets in brief and provide you with some simple code snippets to create the widgets. Towards the end of this article, you will be able to use all the code and build a mini-service using the GUI widgets.
Creating the Main Tkinter window
This step is necessary for any Tkinter GUI widget irrespective of its characteristics.
from tkinter import * root = Tk() #optional root.configure(background='yellow') root.geometry('600x800) #place any of your code lines here #end of code root.mainloop()
The code snippet shown above is a bare-bone structure which has to be used to define the tkinter GUI box before placing any widget on the panel.
In the code snippet, the
tkinter library has been imported and the
Tk() constructor has been instantiated using the
root object. Towards the end of the code, I have called this entire program using
root.configure() is used to add additional properties to your mainframe. In this example, I have used it to add the property of
background and the
root.geometry() ensures that the main frame is of the desired size specified. These are however optional to use.
Placing Tkinter GUI Widgets
Now that we have initialized the mainframe for Tkinter, we will have a look at the different widgets.
I will be introducing the most commonly used widgets which include a label, the button, a check button, an entry, a slider (which in Tkinter is called the scale), a list box, and a radio button.
Append the code snippets given below to the code for the main window.
1. Tkinter Label Widget
For the label widget here, we will define it using the
Label constructor itself. The label is going to go in the root main window and the text will say “Hey, welcome to this my GUI”.
Then we pack the label inside the window and we have provided an argument with pady to give us a little bit more space on the y-axis.
label=Label(root,text="Hey, welcome to this my GUI") label.pack(pady=10)
2. Tkinter Button Widget
The button will be placed on the same main window and is created using the Button() constructor. The text for the button will say “press button”. Notice that the text color is green. For that, we have assigned green to the foreground.
When the button is pressed we want to activate a function and we’re going to assign that function to the command argument. The name of the function is
button_trigger(). When the button is pressed, it’s going to activate this function and print a message that says “button pressed”.
We have packed the button into the main root window. So when we press this button it’s going to activate this function and it’s going to print the message in the console.
def button_trigerr(): print("Button Pressed") button = Button(root,text="press button", foreground="green", command=button_trigger) button.pack(pady=10)
3. Tkinter Check Button Widget
For the next example, we have the check button.
When we check this box or button it’s going to turn the background white, like turning on a light. Then if we uncheck it, it’s going to turn the background black like turning a light off. Let’s try it out.
def check_button_action(): print(check_button_var.get()) if check_button_var.get()==1: root.configure(background='white') else: root.configure(background='black') check_button_var = IntVar() check_button = tk.Checkbutton(root, text="on/off", variable=check_button_var, command= button_action) check_button.pack(pady=10)
So first, create the check button using
Checkbutton(). It’s going on the root main window. The text is “on/off”.
We have associated a variable with this check button and it is an Integer. The function that will be activated by the check button and is named button_action.
The check button has two default states which are 0 and 1 and those default states will be assigned to this variable here. This variable will keep track of the state of the check button and to get the state of the check button.
We just go ahead and reference the
variable.get(). If the state of the check button is 1, that is equivalent to the box being checked and we’re going to make the background of the window white.
If it is 0, we’re going to make the background of the root window black which gives us the effect of turning the light on or off. We have then packed this into the “main” frame with a pady of 10.
4. Tkinter Entry Widget
The entry widget allows us to type in text and transfers the text from the text box or entry to the console and displays the message on the console.
To create the entry widget, we’ve gone ahead and created a frame. To create the frame, we use Frame().
The frame is going to go in the main root window with a border width of 5 with a sunken effect. We reference the framed pack and that will pack the frame into the main window.
entry_frame = Frame(root, borderwidth=5, relief = SUNKEN) entry_frame.pack() text_box=Entry(entry_frame) text_box.pack() def get_entry_text(): print(text_box.get()) label.configure(text=text_box.get()) button = Button(entry_frame, text='get entry', command=get_entry_text) button.pack(pady=10)
We have then created our entry text box and the entry is going to go into the frame. We packed the entry into the frame. So the frame will go into the main window and the entry will go into the frame.
Then we go ahead and created a button that will transfer the text from the entry to the console. Now notice that our entry message is printed to the console, and also updated our label on the mainframe. To get the text we just use the get() method.
5. Tkinter Scale Widget
Next let’s go over the slider or scale widget here. So for this widget, let’s say that you have a restaurant bill and it’s $100 and you want to see how different tip amounts will affect the total bill.
We can use the slider for the tip and the entry box for the bill and then the label will show us the total bill. The label would show us the total bill.
slider_frame = Frame(root, borderwidth=5, relief=SUNKEN) slider_frame.pack(pady=10) def calculate_total_bill(value): print(value) if bill_amount_entry.get()!=' ': tip_percent=float(value) bill=float(bill_amount_entry.get()) tip_amount=tip_percent*bill text=f'(bill+tip_amount)' bill_with_tip.configure(text=text) slider = Scale(slider_frame, from_=0.00, to=1.0,orient=HORIZONTAL, length=400, tickinterval=0.1, resolution=0.01, command=calculate_total_bill) slider.pack()
Okay, so to create the scale we use Scale() and then here we put in all of our parameters or arguments for the entry text box. We created that above.
We have packed the slider,the entry text box and the label into our frame which will go inside the main window. We created the frame like we did in the last example.
For changes made by the slider, the
calculate_total_bill() will be activated. This function will basically take the text which is the bill amount from the entry box. Then it will take the tip percentage from the slider scale, apply the tip to the bill and then give us the total bill which will be displayed in the label.
6. Tkinter ListBox Widget
Next let’s go over the list box widget. So here we have our list box with five items. In this example, we’re just going to choose one of the items. Then we’re going to press the button and we want to transfer the text from the item to a label.
listbox_frame=Frame(root,borderwidth=5, relief=SUNKEN) listbox_frame.pack(pady=10) listbox=Listbox(listbox_frame) listbox.pack() listbox.insert(END,"one") for item in ["two","three","four","five"]: listbox.insert(END, item) def list_item_selected(): selection=listbox.curselection() if selection: print(listbox.get(selection)) list_box_label.configure(text=listbox.get(selection)) list_box_button = Button(listbox_frame,text='list item button', command=list_item_selected) list_box_button.pack()
To create the list box we use
Listbox(). We’re going to put the list box inside of a frame. After we have created our list box, we can go ahead and insert items into the list box.
If you’d like to insert several items, you can do it with a for Loop. Here we have created a button, when we press the button. It’s going to activate the
To access the selection, we reference the
listbox.curselection(). To make sure that we actually have something selected, we use
if selection: and if we have an item selected, we reference the listbox item and then we get the actual item.
The reason that we have used the square brackets with the zero is that the item is typically a single digit Tuple and this will give us just the digit. Then we want to go ahead and update our label with the item that we selected.
7. Tkinter RadioButton Widget
So for the last example, let’s go over radio buttons. Now depending on the radio button selected, we’re going to get an image displayed here. So here we have mountains, boating and camping.
I have created our three radio buttons. All of the radio buttons will be placed inside the main root window. For the text, we have gone ahead and assigned “mountains, boating and camping”.
All of the radio buttons are going to have a value associated with one variable and we have created that variable.
Label(root, text="choose icon") def radio_button_func(): print(rb_icon_var.get()) if(rb_icon_var.get())==1: radio_button_icon.configure(text='\u26F0') elif rb_icon_var_get()==2: radio_button_icon.configure(text='\u26F5') elif rb_icon_var_get()==3: radio_button_icon.configure(text='\u26FA') rb_icon_var=IntVar() Radiobutton(root,text="mountains",variable=rb_icon_var, value=1, command=radio_button_func).pack() Radiobutton(root,text="boating",variable=rb_icon_var, value=2, command=radio_button_func).pack() Radiobutton(root,text="camping",variable=rb_icon_var, value=3, command=radio_button_func).pack() radio_button_icon = Label(root, text=' ', font=("Helvetica",150)) radio_button_icon.pack()
In this case, since you can only click one radio button at a time, the value associated with either of the radio buttons, which we have assigned here 1, 2, or 3, will be assigned to the variable.
When a radio button is clicked, it is going to activate or call the “radio_button_func()”.
So if this first radio button is clicked for mountains, the value of 1 will be assigned to this variable and then we will get that value and test if it’s equal to 1.
And if it is equal to 1, we are going to use the Unicode text representation for mountains.
To quickly conclude we have gone across a few commonly used widgets and the usage of them are as follows:
- Label – Display text or messages
- Button – Used in toolbars, application windows, pop-up windows, and dialogue boxes
- Check button – Used to implement on-off selections.
- Entry Widget – Used to enter or display a single line of text
- Scale widget – Used instead of an Entry widget, when you want the user to input a bounded numerical value.
- List box – Used to display a list of alternatives.
- Radio button – Used as a way to offer many possible selections to the user but lets the user choose only one of them.
Do try out these various widgets and do let us know your favorite one in the comment section below!!