How to create Tkinter buttons in a Python for loop?

TkinterServer Side ProgrammingProgrammingPython

Tkinter Button widgets are very useful in terms of handling events and performing actions during the execution of an application. We can create Tkinter Buttons using the Button(parent, text, option..) constructor. Using the constructor, we can create multiple buttons within the loop.

Example

In this example, we will create multiple buttons in the range using a Python for loop.

#import required libraries
from tkinter import *
from tkinter import ttk

#Create an instance of Tkinter frame
win= Tk()

#Set the geometry of the window
win.geometry("750x250")

#Create a LabelFrame
labelframe= LabelFrame(win)

#Define a canvas in the window
canvas= Canvas(labelframe)
canvas.pack(side=RIGHT, fill=BOTH, expand=1)

labelframe.pack(fill= BOTH, expand= 1, padx= 30, pady=30)

#Create Button widget in Canvas
for i in range(5):
   ttk.Button(canvas, text= "Button " +str(i)).pack()

win.mainloop()

Output

Running the above code will display a window containing some buttons inside a LabelFrame object.

raja
Published on 03-May-2021 09:35:06
Advertisements