Reputation: 29
I have the code shown below that will iterate through the list of names in a dictionary and then create radio buttons. Prior the iteration, have set/initialized the default value. The almost same code is set in a different way and the default values is not getting set, and not sure what am I missing. Any assistance will be appreciated.
Working code
from tkinter import *
root = Tk()
root.title('Trevieew API App')
methods = [
('Monday', 1),
('Tuesday', 2),
('Wednesday', 3),
('Thursday', 4),
('Friday', 5)
]
_row = 0
v = IntVar()
v.set(1)
for method, value in methods:
b = Radiobutton(root, text=method, variable=v, value=value)
_row += 1
b.grid(row=_row, column=0, sticky=W)
root.mainloop()
NOT working copy
from tkinter import *
class App:
def __init__(self, master):
self.master = master
master.title('App Tool')
self.radiobuttons()
def radiobuttons(self):
_row = 0
methods = [
('Monday', 1),
('Tuesday', 2),
('Wednesday', 3),
('Thursday', 4),
('Friday', 5)
]
v = IntVar()
v.set(1)
for method, value in methods:
b = Radiobutton(root, text=method, variable=v, value=value)
_row += 1
b.grid(row=_row, column=0, sticky=W)
root = Tk()
my_gui = App(root)
root.mainloop()
Upvotes: 0
Views: 810
Reputation: 142641
Problem can be because v
in class is local variable which is destroyed when it ends method radiobuttons
. Use self.
to keep it.
self.v = IntVar()
self.v.set(1)
for method, value in methods:
b = Radiobutton(root, text=method, variable=self.v, value=value)
_row += 1
b.grid(row=_row, column=0, sticky=W)
Upvotes: 2