
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create Multiple Buttons with Different Command Functions in Tkinter
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.
Example
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 win.geometry("750x250") #Define a function to update the entry widget def entry_update(text): entry.delete(0,END) entry.insert(0,text) #Create an Entry Widget entry= Entry(win, width= 30, bg= "white") entry.pack(pady=10) #Create Multiple Buttons with different commands button_dict={} 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) button_dict[i].pack() win.mainloop()
Output
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.
Advertisements