Tkinter Radiobutton with Dictionary
When there are more options, the program will be more complicated, so you can consider using a dictionary to store information about the option buttons, and then use the iterative dictionary to create the option buttons, see the following example.
Tkinter Radiobutton with Dictionary Example#1
Create option buttons for the city data in the dictionary, and when we select the favorite city, the Python Shell window will list the selected results.
from tkinter import *
def printSelection():
print(cities[var.get()],"Selected!!!")
root = Tk()
root.title("apidemos.com")
cities = { 0:"New York" ,1:"Houston",
2:"Washington",3:"Atlanta",
4:"New Jersey",5:"Tokyo",
}
var = IntVar() # Variables bound to option buttons
var.set(-1) # Default Options
# var.set(0) # Default Options
label = Label(root,text="Choose the city you like best",
fg="blue",bg="lightyellow",width=30)
label.pack()
for val,city in cities.items():
Radiobutton(
root,
text=city,
variable=var,value=val,
command=printSelection
).pack()
root.mainloop()
Output:
Select "New York".
When the "New York" option button is selected, you will see the following results in the Python Shell window.