Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
How to move a Tkinter button?
Next article icon

In this article, let’s see how we can loop through the buttons in Tkinter.

Stepwise implementation:

Step 1: Import the Tkinter package and all of its modules and create a root window (root = Tk()).

Python3
# Import package and it's modulesfromtkinterimport*# create root windowroot=Tk()# root window title and dimensionroot.title("GeekForGeeks")# Set geometry (widthxheight)root.geometry('400x400')# Execute Tkinterroot.mainloop()

Output

Step 2:Now let's add aEntry() class and will display the button name as soon as one of the buttons is clicked.

Python3
# Import package and it's modulesfromtkinterimport*# create root windowroot=Tk()# root window title and dimensionroot.title("GeekForGeeks")# Set geometry (widthxheight)root.geometry('400x400')# Entry Boxtext=Entry(root,width=30,bg='White')text.pack(pady=10)# Execute Tkinterroot.mainloop()

Output  

Step 3:Now let's create an empty dictionary (button_dict) to save all the button objects and a list consisting of names of all the buttons. Now loop over each item of the list to create anbutton object of it and store it in the dictionary. For the button command, create a function named 'action' and for each button call thetext_update() function to update the changes in the entry in Entry() object created earlier.

Python3
# Import package and it's modulesfromtkinterimport*# text_update functiondeftext_updation(language):text.delete(0,END)text.insert(0,language)# create root windowroot=Tk()# root window title and dimensionroot.title("GeekForGeeks")# Set geometry (widthxheight)root.geometry('400x400')# Entry Boxtext=Entry(root,width=30,bg='White')text.pack(pady=10)# create buttonsbutton_dict={}words=["Python","Java","R","JavaScript"]forlanginwords:# pass each button's text to a functiondefaction(x=lang):returntext_updation(x)# create the buttonsbutton_dict[lang]=Button(root,text=lang,command=action)button_dict[lang].pack(pady=10)# Execute Tkinterroot.mainloop()

Output

loop through button tkinter

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp