Why is there a dash in ttk radio button when made with a function?
Question:
When I make two sets of the same radio buttons there will be a dash in one of the buttons created from a function.
import tkinter as tk
from tkinter import ttk
def add_radio_buttons():
a_b = tk.StringVar()
a_button = ttk.Radiobutton(window, text="A", value="A", variable=a_b)
a_button.grid(row=1, column=1)
a_button.invoke()
b_button = ttk.Radiobutton(window, text="B", value="B", variable=a_b)
b_button.grid(row=1, column=2)
window = tk.Tk()
add_radio_buttons()
a_b_too = tk.StringVar()
a_button = ttk.Radiobutton(window, text="A", value="A", variable=a_b_too)
a_button.grid(row=2, column=1)
a_button.invoke()
b_button = ttk.Radiobutton(window, text="B", value="B", variable=a_b_too)
b_button.grid(row=2, column=2)
window.mainloop()
Is this a bug or am I forgetting something?
Answers:
You are using local variables for the StringVar
instances so the objects are being destroyed by the garbage collector. You need to use global variables or instance variables to keep a persistent copy of the variable objects.
When I make two sets of the same radio buttons there will be a dash in one of the buttons created from a function.
import tkinter as tk
from tkinter import ttk
def add_radio_buttons():
a_b = tk.StringVar()
a_button = ttk.Radiobutton(window, text="A", value="A", variable=a_b)
a_button.grid(row=1, column=1)
a_button.invoke()
b_button = ttk.Radiobutton(window, text="B", value="B", variable=a_b)
b_button.grid(row=1, column=2)
window = tk.Tk()
add_radio_buttons()
a_b_too = tk.StringVar()
a_button = ttk.Radiobutton(window, text="A", value="A", variable=a_b_too)
a_button.grid(row=2, column=1)
a_button.invoke()
b_button = ttk.Radiobutton(window, text="B", value="B", variable=a_b_too)
b_button.grid(row=2, column=2)
window.mainloop()
Is this a bug or am I forgetting something?
You are using local variables for the StringVar
instances so the objects are being destroyed by the garbage collector. You need to use global variables or instance variables to keep a persistent copy of the variable objects.