Creating Widgets in Tkinter Using Loops in Python GUI

Posted by


Tkinter is a powerful Python library for creating graphical user interfaces (GUI). One of the most common tasks in GUI programming is creating multiple widgets at once using a loop. In this tutorial, we will learn how to create widgets in Tkinter using a loop.

To begin, you will need to have Tkinter installed on your machine. Tkinter is included in the standard Python distribution, so you likely already have it. If not, you can install it using the following command:

pip install tk

Once you have Tkinter installed, you can start creating widgets using a loop. Widgets in Tkinter are the building blocks of a GUI, such as buttons, labels, entry fields, etc. The process of creating widgets using a loop involves defining the properties of each widget and then using a loop to create multiple instances of the widget.

Let’s start by creating a simple GUI with buttons using a loop. We will create 5 buttons with different text labels.

import tkinter as tk

root = tk.Tk()

button_texts = ['Button 1', 'Button 2', 'Button 3', 'Button 4', 'Button 5']

for text in button_texts:
    button = tk.Button(root, text=text)
    button.pack()

root.mainloop()

In this example, we import the tkinter module and create an instance of the Tk class, which represents the main window of the GUI. We define a list of text labels for the buttons and then use a loop to create 5 buttons with the specified text labels. Finally, we call the mainloop() method to start the event loop and display the GUI window.

You can customize the appearance and behavior of the widgets using various properties and methods. For example, you can set the size and position of the widgets using the pack() method, change the color and font of the text using the fg and font properties, or attach event handlers to handle user interactions.

Creating widgets using a loop is a convenient way to reduce code duplication and improve the maintainability of your GUI code. You can create complex layouts and designs by combining different types of widgets and arranging them in a grid or a pack using loops.

In addition to buttons, you can create other types of widgets such as labels, entry fields, checkboxes, radio buttons, etc. using the same approach. Experiment with different types of widgets and properties to create custom GUIs for your Python applications.

Overall, creating widgets using a loop in Tkinter is a powerful technique that can help you create dynamic and interactive GUIs with ease. Experiment with different layouts, designs, and interactions to build user-friendly interfaces for your Python applications.

0 0 votes
Article Rating
50 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@aniketjain5049
3 months ago

whatt usage of line cur_label='label'+str(i) because without it the output will be same

@muhammadusman5179
3 months ago

sir love you from pakistan

@muhammadusman5179
3 months ago

thanks sir for amazing python serise

@ANANTEntercom
3 months ago

# tkinter

##import tkinter as tk

##from tkinter import *

import tkinter

r=tkinter.Tk()

##R=0

##C=0

print(r.title ('tkinter GUI'))#it prints empty string check if problrm

# tile funtions returns some vslur as empy string ''

from tkinter import ttk

q=ttk.Label (r, text='name:') #q=tkinter.Label (r, text='name: ') #.grid(row=0,column=0) #.pack()

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

##q.focus () # uselasse learn more

print(q)

q1=ttk.Label (r, text='age:')

q1.grid(row=1,column=0,sticky=tkinter.E)#W,E,N,S,

print(q1)

q2=ttk.Label(r, text='email:')

q2.grid(row=2,column=0, sticky=tkinter.E)

print (q2)

# entry box

ee=tkinter.StringVar()

e=ttk.Entry(r, width=20, textvariable= ee)

e.grid(row=0,column=1)

e.configure(foreground='blue')

print (e,ee)

ee1=tkinter.StringVar()

e1=ttk.Entry(r, width=20, textvariable= ee1)

e1.grid(row=1,column=1)

print (e1,ee1)

ee2=tkinter.StringVar()

e2=ttk.Entry(r, width=20, textvariable= ee2)

e2.grid(row=2,column=1)

print (e2,ee2)

##ee3=tkinter.StringVar()

q3=ttk.Label (r, text='gender:')

q3.grid(row=3,column=0, sticky=tkinter.E)

print (q3)

#combobox

cb1=tkinter.StringVar()

cb=ttk.Combobox (r, width=6, textvariable= cb1, state='readonly')

cb['values']=('select', 'M','F','G','S')# 'values' is cummand string remamber spaling

cb.current (0)

cb.grid(row=3,column=1)

print(cb,cb1)

#redio button

rbb1=tkinter.StringVar()

rb=ttk.Radiobutton (r, text='student', width=6, value='student', variable= rbb1)#value an vriablr not textvaviable

rb.grid(row=4,column=0, sticky=tkinter.E)

print (rb,rbb1)

##rbb2=tkinter.StringVar()

rb2=ttk.Radiobutton (r, text='teacher',width=6, value='teacher', variable= rbb1)#value

rb2.grid(row=4,column=1, sticky=tkinter.W)

print (rb2,rbb1)#,rbb2)

#check button

cbb=tkinter.IntVar ()#StringVar()#tkinter.IntVar()

cb=ttk.Checkbutton (r, text ='subcrib', variable=cbb)

cb.grid(row=5,columnspan=1, sticky=tkinter.W)

print(cb,cbb)

#opaning new file

##import os

##f=open ('C:\Users\anantnavgire\Desktop\py programs.pydata.txt','a')

#button

##i=0

#using a loop for title

##r.title('LOOP')

lb={

'father:' : tkinter.StringVar() ,

'sirname:': tkinter.StringVar() ,

'Home:': tkinter.StringVar() ,

'street:': tkinter.StringVar() ,

'vilage:': tkinter.StringVar() ,

'city:': tkinter.StringVar() ,

'state:': tkinter.StringVar() ,

'cuntry:': tkinter.StringVar() ,

'pin:': tkinter.StringVar()

}

for i in range(len(lb)):

Lb=ttk.Label(r,text= [j for j in lb.keys()] [i] ) #dict.keys()

Lb.grid(row=(6+i),column=0, sticky=tkinter.E)

Lb.configure(foreground='#9900ff')

print(Lb)

#entry box loop

I=0

for x in lb:

y=lb[x]

Le=ttk.Entry(r, width=20, textvariable= y)

Le.grid(row=6+I,column=1)

print(Le,y)

I+=1

def act():

print (ee.get (),ee1.get (),ee2.get (),cb1.get(),

rbb1.get(), cbb.get())#,rbb2.get())

a=ee.get ()

s=ee1.get ()

d=ee2.get ()

E=cb1.get()

F=rbb1.get()

g=cbb.get()#int(cbb.get())# it provides string outpoot so need to cha nge string to int

if g==0:sub='not'

else:sub='yes'

print(a,s,d,e,F,g,sub)

## return sv(a,s,d,e,f,g,sub)

##

##def sv(a,s,d,e,F,g,sub):

with open ('C:\Users\anantnavgire\Desktop\py programs.pydata.txt','a')as f:

f.write(f'n{a} ,{s} ,@{d} ,{E} {F} {g} is he subscribed?–{sub} {[(x,lb[x].get()) for x in lb]}n')

print(f)

print([(x,lb[x].get()) for x in lb])

# creat csv

from csv import DictWriter

with open ('C:\Users\anantnavgire\Desktop\py programs.pydata.csv','a')as csv:

k=DictWriter(csv,fieldnames=['name' , 'age' , 'email' ,'gender','oq','sub']+[x for x in lb])

import os

if os.stat('C:\Users\anantnavgire\Desktop\py programs.pydata.csv').st_size==0:

k.writeheader()# if file is empty

w={

'name' : a ,

'age' : s ,

'email' : d,

'gender' : E,

'oq' :F,

'sub' :g

}

w.update({(X, lb[X].get()) for X in lb})

print(w)

k.writerow(w)

## # in simple way

k.writerow(

{

'name' : a ,

'age' : s ,

'email' : d,

'gender' : E,

'oq' :F,

'sub' :g,

'father:' : lb['father:'].get() ,

'sirname:' : lb[ 'sirname:'].get() ,

'Home:' : lb['Home:'].get(),

'street:' : lb[ 'street:'].get(),

'vilage:' : lb['vilage:'].get(),

'city:' : lb['city:'].get(),

'state:' : lb[ 'state:'].get(),

'cuntry:' : lb['cuntry:'].get(),

'pin:' : lb['pin:'].get()

}#.update({(X, lb[X].get()) for X in lb}) #can't do

)

# {a}.update({(x, y) for x,y in {c}.items()}) #b.update({(x, p[x]) for x in p})

#resate values of entry booxes

e.delete(0,tkinter.END)

e1.delete(0,tkinter.END)

e2.delete(0,tkinter.END)

q.configure(foreground='#0000ff')

## cb1.delete(0,tkinter.END)

## rbb1.delete(0,tkinter.END)

## cbb.delete(0,tkinter.END)

b=ttk.Button(r, text='submite', command=act) #command is to call function

b.grid (row=100,column=1)

##b.configure(foreground='#0000ff')

print(b)

###resate values

##ee.delete(0,tkinter.END)

##ee1.delete(0,tkinter.END)

##ee2.delete(0,tkinter.END)

##cb1.delete(0,tkinter.END)

##rbb1.delete(0,tkinter.END)

##cbb.delete(0,tkinter.END)

##r.mainloop()

@ANANTEntercom
3 months ago

i used only one dict for labeling and entry box

@tipstricks8667
3 months ago

label =[]

texts = []

config = {

'width': 50,

'height': 30,

'family': 'Arial',

'size': 15

}

family ='Arial'

size = 15

entries = {

'name': {

'variable': StringVar(),

'label': 'Name',

'font': f'{family},{size}'

},

'email': {

'variable': StringVar(),

'label': 'Email',

'font': f'{family},{size}'

},

'password': {

'variable': StringVar(),

'label': 'Password',

'font': f'{family},{size}'

}

}

for values in entries.values():

label.append(Label(root, text=values['label']))

texts.append(ttk.Entry(root, textvariable= values['variable'], width=config['width'], font=f"{values['font']}"))

if values['label'] == 'Password':

texts[2].config(show='*')

label[0].place(x=10, y=10)

label[1].place(x=10, y=40)

label[2].place(x=10, y=70)

texts[0].place(x=70, y=10)

texts[1].place(x=70, y=40)

texts[2].place(x=70, y=70)

def getUser():

print(texts[0].get())

print(texts[1].get())

print(texts[2].get())

@raghu_yadav_yt
3 months ago

Nice. 👍

@pratiksatishkalaskar4640
3 months ago

thanks 4 ur efforts

@samsharma5747
3 months ago

Hi harsit how can we use sql?

@kohinoorteamyogeshchhabra8255
3 months ago

BHAI YR MJA TO A GYA LKIN EK BT SMJ NI A RHI MAI BIGNER HO YE SB YD KAISE RKHE MTLB AP YE SB KAISE KR LANE HO ITNA YD

@subhajitdutta1443
3 months ago

Thanks Harshit for such a useful video..
Can you please help me to learn how I can use loop in the Submit button part at the time of writing the data in a CSV file??

@Gotoheaven06
3 months ago

Thank you sir for your good explanation ❤️❤️

But one problem for me print double ho raha h single submit click karne me please help…

@yesican261
3 months ago

I used List instead of Dictionary
import tkinter as tk
from tkinter import ttk

win = tk.Tk()

win.title("Beta_1")

labels = ["Write your Name :","Write your Age :","Write your Gender :","Write your City :","Write your State:","Write your Country :"]

for i in range(len(labels)):

x = 'Label_Num_' + str(i)

x = tk.Label(win,text = labels[i])

x.grid(row=i, column=0,sticky=tk.W,padx=20,pady=5)

label = ["name","age","gender","city","state","country"]
zed = ["1","2","3","4","5","6"]

for i in range(len(labels)):

label[i] = tk.StringVar()

zed[i] = tk.Entry(win,width=18,textvariable=label[i])

zed[i].grid(row=i,column=1)

def action():

for i in range(len(label)):

print(label[i].get())
zed[i].delete(0,tk.END) #Delete after Submit Button is pressed

submit_btn = tk.Button(win,text="Submit",command=action)

submit_btn.grid(row=8,column=1)
win.mainloop()

@ankitrawat9726
3 months ago

Why we wrote str(i) ? Should we write only i instead of str(i) ?

@MakaroniiMisiek
3 months ago

Nice one, Can you add in future subtitles to your materials, they are really helpfully. And Question:
If I have Script with Loop in Loop, And When I submit Button , Tkinker make Operation for Loop with Other Script for example Selenium Browser, Then Tkinker is Freezing until Loop Finish, but I have Create Loop which One never End. How to Create script for Tkinker for Not Freezing Application when Loop is Working after Submit Button,when My loop is working I still need to do Other Operation on Tkinker GUI like Save,Load, Clear Data inside text Box, but This Loop is Freezing my Gui and I cant do Anythink need to Kill process.

That guide will be hellpfull 🙂

@pranavguptaa
3 months ago

5:57 , Different varibles are not created for each label,each label is assigned the same name.Can anyone help pleaseee!!

@DarshJain
3 months ago

the variables are not created in for loop, please help

@myselfriz
3 months ago

I tried to made this Program even shorter, Check here:
https://www.mediafire.com/file/s6dz6j12tzwim9h/create_widget_using_loop.py/file

@chetanbonde1427
3 months ago

How to create multiple window for every print option in below python code import time

def something():
print("a")
print("b")
print("c")
print("d")
print("e")
print("f")
print("g")
print("i")
print("j")

time.sleep(10)

while True:
something()

@ersoumyajitpan7205
3 months ago

I really love your videos…
I have one problem…
How to write in CSV file using dictionary and for loop???
I can't do this.. please help