How to generate Tkinter Buttons dynamically?


In this article, we will see how to create buttons dynamically in a tkinter window. Creating buttons dynamically means customizing the buttons and their functionality by adding events to them.

First, we will import the tkinter library in the notebook, then we will create an instance using the Button function which takes parameters such as parent or root of the window, textvariable which is the value to assign in each button and command.

Syntax

Button(parent, textvariable, command)

Example

from tkinter import *
import tkinter as tk

# create an instance of tkinter
win = tk.Tk()

#Define the size of the window
win.geometry("700x200")

#Name the title of the window
win.title("www.tutorialspoint.com")

# number of buttons
n=10

#Defining the row and column
i=3

#Iterating over the numbers till n and
#creating the button
for j in range(n):
   mybutton= Button(win, text=j)
   mybutton.grid(row=i, column=j)

# Keep the window open
win.mainloop()

Output

Running the above code in tkinter notebook will generate the following output.

Updated on: 04-Mar-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements