Issue
This Content is from Stack Overflow. Question asked by Maior
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?
Solution
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.
This Question was asked in StackOverflow by Maior and Answered by Bryan Oakley It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.