tkinter-widgets

Tkinter Widgets: Python Tkinter Tutorial-1

Tkinter Widgets

During the time of the Guess The Anime article, I had accidentally said that I will bring 3 Part Tkinter Series. And I had completely forgotten about that. But now that I remember, I shall publish Python Tkinter Tutorial 3 Part Series along with some projects. Using Python Tkinter we can create beautiful GUI Desktop Applications. Tkinter supports a wide range of widgets and we shall look at commonly used Tkinter widgets in part1.

Commonly Used Tkinter Widgets

Label

A Label is nothing but adding text on GUI. It might be a word, sentence, or even a Paragraph.

Syntax:
variable = tk.Label(text="<your-text>")

Apparently, when there is a text, it becomes necessary to change its font. Many programmers are satisfied with the default font. But many on other hand prefers new font. In that case, let’s change the font.

Syntax: 
font=(font-name,font-size,font-weight)
import tkinter as tk
root = tk.Tk()
default = tk.Label(text="I am Default")
default.pack()
text1 = tk.Label(text="I am Arial",font=("Arial",18,"bold"))
text1.pack()
text2 = tk.Label(text="I am TNR",font=("Times New Roman",16,"italic"))
text2.pack()
text3 = tk.Label(text="I am Carlito",font=("Carlito",15,"underline"))
text3.pack()
root.mainloop()

Note: pack() is one of the geometry managers which is beneficially used to display widgets on the GUI window. We shall see Geometry Functions in detail in Part-2.

Button

A Button is a widget that triggers a function. You might have seen on many websites or apps, that whenever you click on a button certain operation is triggered. In the same way, let us create a button with the name click me and iterate a counter.

import tkinter as tk

root = tk.Tk()
root.geometry("100x100")
btn = tk.Button(text="Click Me")
btn.pack()
root.mainloop()

Now just a second, this program does nothing. We might have created a button, but no use. Because we haven’t given any command for the button to operate. Inside the Button, the widget provides a parameter command with a value. This value is function. Just provide a function as a value, without any parenthesis. Now you are good to go.

import tkinter as tk

def click():
    global count
    count+=1
    text.config(text=count)

root = tk.Tk()
root.geometry("100x100")
count = 0
text = tk.Label(carried releasetext=count,font=("Arial",18,"bold"))
text.pack()
btn = tk.Button(text="Click Me",command=click,bd=5)
btn.pack()
root.mainloop()

Entrybox

Say you have visited your college for the first time, there give an application form to fill up in bringing. In this form, you are supposed to enter your name, email, and phone number. This is an example for Entry Box, where you ask your user to enter details into it. The same goes in the online form, where you freshly register for Instagram or Twitter, or any other social media. There is a space where you are supposed to enter your details that is also an example of the entry box.

Before we create Entry Box, let us learn about the Tkinter Variables which we will be dealing with. We will cover how to receive and send data through the Entry Box.

Tkinter Data Types

int_variable = tk.IntVar()
str_variable = tk.StringVar()
float_variable = tk.DoubleVar()
boo_variable = tk.BooleanVar()

int_variable.set(12)
str_variable.set("Killua")
float_variable.set(156.45)
boo_variable.set(True)

lbl_age = tk.Label(text=int_variable.get()).pack()
lbl_name = tk.Label(text=str_variable.get()).pack()
lbl_height = tk.Label(text=float_variable.get()).pack()
lbl_anime_char = tk.Label(text=boo_variable.get()).pack()
lbl_age = tk.Label(textvariable=int_variable).pack()
lbl_name = tk.Label(textvariable=str_variable).pack()
lbl_height = tk.Label(textvariable=float_variable).pack()
lbl_anime_char = tk.Label(textvariable=boo_variable).pack()

Create A Entry Box

A short reminder on when to use Entry Box is when you need to take user input in the GUI application.

name = tk.StringVar()
age = tk.IntVar()

name_lbl = tk.Label(text="Enter Name:",font=("arial",14,"bold")).place(x=5,y=53)
age_lbl = tk.Label(text="Enter Age:",font=("arial",14,"bold")).place(x=5,y=153)

name_entry = tk.Entry(textvariable=name,bd=3,font=("arial",16,"bold"))
name_entry.place(x=120, y=50)

age_entry = tk.Entry(textvariable=age,bd=3,font=("arial",16,"bold"))
age_entry.place(x=120,y=150)

sbt = tk.Button(text="Submit",font=("arial",14,"bold"),bd=3).place(x=150,y=200)

place() again is an geometry manager, and we shall discuss that in part 2.

get and set methods

get is the method that is used to receive the data, and the set is the method that is used to store the data.

import tkinter as tk
root = tk.Tk()
root.geometry("400x300")

#details is triggered on button click
#using get method, we can get the user entered details.
def details():
    #get needs no argument
    print("User Name Recived:{}".format(name_entry.get()))
    print("User Age:{}".format(age_entry.get()))
    name_entry.delete(0,"end")
    age_entry.delete(0,"end")


name = tk.StringVar()
age = tk.IntVar()
#set requires argument to add initial data
name.set("Enter Name")
age.set("Enter Age")

name_entry = tk.Entry(textvariable=name,bd=3,font=("arial",16,"bold"))
name_entry.place(x=100, y=50)
age_entry = tk.Entry(textvariable=age,bd=3,font=("arial",16,"bold"))
age_entry.place(x=100,y=150)

sbt = tk.Button(text="Submit",font=("arial",14,"bold"),bd=3,command=details).place(x=150,y=200)
root.mainloop()

In Entry Box, if you use the set method, that means your add adding some value inside the Entry Box, which users can see and modify. get method is used when you need to get the information of what the user has entered.

Frame

The frame is to add decoration design to Tkinter widgets. Now you might have used many photo editors, you see there is a Frame option in almost every photo editor app. The frame is mainly used for such purposes, to add a border to design Text, buttons, Entry Boxes, and many more.

Basically, Frame is used to add a kind of Layout to another widget, which is used to improve the UI of the application.

frame = tk.Frame(root,bg="yellow")
frame.place(x=50,y=50,width=100,height=100)

btn = tk.Button(frame,text="btn0",pady=10,bd=5).pack()
btn1 = tk.Button(frame,text="btn1",pady=10,bd=5).pack()

Listbox

ListBox is a container that stores a list of items. Every item inside ListBox has the same font and color. Just like a normal List Data structure, you can insert new elements in ListBox using Tkinter attributes.

frame = tk.Frame(bg="black")
frame.place(x=25,y=25,width=120,height=120)
list_box = tk.Listbox(frame,bg="white")
list_box.place(x=10,y=10,width=100,height=50)

ScrollBar

A ScrollBar allows you to view content that is outside of the current viewing area by sliding the Thumb to make the content visible.

frame = tk.Frame(root)
frame.place(x=50,y=50,width=200,height=200)
content = tk.Listbox(frame, height = 500, width = 500)
scroll = tk.Scrollbar(frame)
scroll.pack(side = RIGHT, fill = Y)
content.pack()

for i in range(500):
    content.insert(ANCHOR, i)

content.config(yscrollcommand = scroll.set)
scroll.config(command = content.yview)
frame = tk.Frame(root)
frame.place(x=50,y=50,width=200,height=200)

scrollbar = tk.Scrollbar(frame)
characters = tk.Listbox(frame, height = 100, width = 100)
scrollbar.pack(side="right",fill="y")
characters.pack()

mainChar = ["Luffy","Naruto","Gintoki","Eren","Gon","Goku","Tanjiro","Deku","Asta","Senku","Itadori","Hikigaya","Light","Lelouch","Ichigo","Hinata"]
mainChar.sort()
for char in mainChar:
   characters.insert("end",char)

characters.config(yscrollcommand = scrollbar.set)
scrollbar.config(command = characters.yview)

Canvas

Adding a good background to Tkinter becomes critical for your application in terms of UI. Tkinter supports the Canvas widget that is used to make your application look good and attractive. To begin with, basic usage of Canvas, add a background color for GUI application.

width = 350
height = 350
root.geometry("{}x{}".format(width,height))
canva = tk.Canvas(bg="aqua",width=width,height=height).pack()
root.mainloop()

RadioButton

Radio Button is the objective-based button, which lets the user select one button at a time. For example for choosing Gender: Male, Female, Prefer Not To Say. We will look at one such example where we shall change the background color of the GUI application based on user selection from Radio Button.

def sbm():
    lbl.configure(text="Choosen:{}".format(choice.get()))

choice = tk.StringVar(root,0)

for option in ["Male","Female","Prefer Not To Say"]:
    tk.Radiobutton(root,text="%s" %option,value=option,variable=choice).pack()

tk.Button(text="Submit",command=sbm,pady=10).pack()
lbl = tk.Label(text='')
lbl.pack()

In the above code, we have created three radio buttons whose values are stored in the list. The arguments passed inside the RadioButton are the text, value, and variable. Where both text and value point to the same data which is equal to the list. Furthermore, variable arguments point to Tkinter Variable that is used to set and get the data. Usually, we use the get method to receive the option from RadioButton.

Here is a small code on how to change the multiple background color based on user interest.

Change Background Colour Using RadioButton And Canvas

def change():
    color = choice.get()
    canva.configure(bg=color)

choice = tk.StringVar(root,0)
canva = tk.Canvas(root,bg="purple")
canva.place(x=-1,y=-1,width=400,height=400)

for option in ["Red","Black","Blue","Green"]:
    tk.Radiobutton(root,text="%s" %option,value=option,variable=choice).pack()

tk.Button(text="Change BG",command=change,bd=4).place(x=55,y=100)

The list of colors is iterated through the RadioButton values. With the use of Canva, we can modify the background color whenever the Button event is triggered.

Menu

A menu bar is a thin, horizontal bar containing the labels that are essential operations for the GUI app.

Using tk.Menu you need to first config the Menu to the root window. Then add_command under that specific Menu, by assigning tearoff attribute to 0. If tearoff is not given 0, then we get an unnecessary separator at the beginning of the Menu. Lastly, with help of add_cascade, you can display the Menu and commands under it on the GUI window.

menubar = tk.Menu(root)
root.config(menu=menubar)

fileMenu = tk.Menu(menubar,tearoff=0)
fileMenu.add_command(label="New")
fileMenu.add_command(label='Exit',command=root.destroy)
menubar.add_cascade(label="File",menu=fileMenu)

add_separator() provides a horizontal between the multiple commands.

editMenu = tk.Menu(menubar,tearoff=0)
editMenu.add_command(label="Undo")
editMenu.add_command(label="Redo")
editMenu.add_separator()

editMenu.add_command(label="Cut")
editMenu.add_command(label="Copy")
editMenu.add_command(label="Paste")

menubar.add_cascade(label="Edit",menu=editMenu)
helpMenu = tk.Menu(menubar,tearoff=0)
helpMenu.add_command(label="Welcome")
helpMenu.add_command(label="Get started")

menubar.add_cascade(label="Help",menu=helpMenu)

Simple Programs Using Python Tkinter Widgets

Adding Multiple Colours To Background In Tkinter

width = 350
height = 350
root.geometry("{}x{}".format(width,height))
canva = tk.Canvas(bg="aqua",width=width,height=height/2).pack()
canva1 = tk.Canvas(bg="violet",width=width,height=height+height/2).pack()

Add A Background Image To Tkinter App

The basic requirement for a better UI is adding a decent background image for your web application. Moreover, the background image can be resized based on the application geometry requirements.

import tkinter as tk
from PIL import Image,ImageTk

#get GUI window
root = tk.Tk()
root.geometry("455x425+425+150")
#open the image and resize it according to GUI window
img = Image.open('anyimage.png')
img = img.resize((453,430), Image.ANTIALIAS)
bg= ImageTk.PhotoImage(img)

#now create_image using Canvas to add background image to your application.
canvas= tk.Canvas(root)
canvas.pack(expand=True, fill= "both")
canvas.create_image(0,0,image=bg,anchor="nw")

root.mainloop()

Subscribe to our Newsletter to never miss out on the content: https://animevyuh.org/newsletter. Join our Newsletter now for amazing Anime RecommendationPython and Machine Learning Content, and many more kind of good stuff.

Support Us: https://www.buymeacoffee.com/trjtarunhttps://ko-fi.com/tarunrjain751
GitHub: https://github.com/lucifertrj
Twitter: https://twitter.com/TRJ_0751

1 thought on “Tkinter Widgets: Python Tkinter Tutorial-1”

  1. Pingback: Tkinter Geometry Managers -

Comments are closed.