Create multiple buttons with "different" command function in Tkinter

TkinterServer Side ProgrammingProgramming

A Button can be initialized using the for loop in a Tkinter application. Let us suppose that we want to create multiple buttons, each with different commands or operations defined in it. We have to first initialize the Button inside a for loop. The iterator will return the object for which multiple instances of the button will be created.


In this example, we will define some buttons that will have different commands or functionalities.

#Import the required Libraries
from tkinter import *
from tkinter import ttk
#Create an instance of Tkinter frame
win = Tk()
#Set the geometry of the Tkinter frame

#Define a function to update the entry widget
def entry_update(text):

#Create an Entry Widget
entry= Entry(win, width= 30, bg= "white")

#Create Multiple Buttons with different commands
option= ["Python", "Java", "Go", "C++"]

for i in option:
   def func(x=i):
      return entry_update(x)

   button_dict[i]=ttk.Button(win, text=i, command= func)



Running the above code will display a window that contains some buttons. When we click a particular button, it will update the message in the Entry widget.

Now, click each button to see the resultant output.

Updated on 03-May-2021 08:46:56