I am a new learner to TKinter, and I'm testing the Radio Widget. I am using this simple program to test that I can use it correctly.
import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showinfo
from tkinter import Tk, Text
# root window
root = tk.Tk()
root.geometry('300x220')
root.resizable(False, False)
root.title('Radio Button Demo')
#Display result
def display_radio():
showinfo(
title = "Result",
message = selectable_numbers.get()
)
#Selectable options
selectable_numbers = tk.StringVar()
numbers = (('1', 'One'),
('2', 'Two'),
('3', 'Three'),
('4', 'Four'))
#Label
simple_label = ttk.Label(text = "Select a number")
simple_label.pack(fill='x', padx=5, pady=5)
#Creating the radio buttons with iteration
for number in numbers:
r = ttk.Radiobutton(root,
text = number[0],
value = number[1],
variable = selectable_numbers
)
r.pack(fill='x', padx = 5, pady = 5)
#Button to display
display_button = ttk.Button(root,
text = "Display Number")
display_button.pack(fill='x', padx=5, pady=5)
display_button.bind('<Any-Button>', display_radio(), add='+')
root.mainloop()
When I run this program, the message box appears immediently with nothing in it, then the button does not work any more. I am comparing this code with an example code that does work, and as far as I can tell they are functionally identical.
import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showinfo
# root window
root = tk.Tk()
root.geometry('300x220')
root.resizable(False, False)
root.title('Radio Button Demo')
def show_selected_size():
showinfo(
title='Result',
message=selected_size.get()
)
selected_size = tk.StringVar()
sizes = (('Small', 'S'),
('Medium', 'M'),
('Large', 'L'),
('Extra Large', 'XL'),
('Extra Extra Large', 'XXL'))
# label
label = ttk.Label(text="What's your t-shirt size?")
label.pack(fill='x', padx=5, pady=5)
# radio buttons
for size in sizes:
r = ttk.Radiobutton(
root,
text=size[0],
value=size[1],
variable=selected_size
)
r.pack(fill='x', padx=5, pady=5)
# button
button = ttk.Button(
root,
text="Get Selected Size",
command=show_selected_size)
button.pack(fill='x', padx=5, pady=5)
root.mainloop()
Any reason why the button becomes functionless in my code? I have tested my code with both command binding and event binding, and they both have the same results.