Reputation: 33
How can I retrieve the value from multiple Checkbuttons when Checkbutton are generated in a method?
The method button which have to retrieve value checked
def __download(self, url: Entry, button: Button):
"""
download video infos video and display checkbox
:return:
"""
try:
url = url.get()
video: Video = Video()
if button['text'] != 'Download':
video.url = url
video.video = YouTube(url)
self.__display_video_title(video)
self.__display_video_thumbnail(video)
resolution = video._get_video_resolution()
# checkbox are created here
self.__display_checkbox(resolution, video)
button['text'] = 'Download'
else:
# need to get the value here
pass
except exceptions.RegexMatchError:
print('the url is not correct')
except exceptions.VideoPrivate:
print('Can\'t reach the video')
except exceptions.VideoUnavailable:
print('this video is unavailable')
the method which creates the Checkbuttons
def __display_checkbox(self, resolution: list, video: Video):
x_checkbox = 25
var = StringVar()
checkbox_title = Label(self.app, border=None, font='Terminal 15 bold', bg='#f1faee', fg='#457b9d',
text='Choose your resolution')
checkbox_title.place(x=280, y=85)
for res in resolution:
Checkbutton(self.app, text=res, bg='#f1faee', variable=var, onvalue=res, offvalue='off').place(x=x_checkbox, y=120)
x_checkbox += 100
Upvotes: 2
Views: 1781
Reputation: 2904
If you create several checkboxes, you should not use the same variable for each of them. Otherwise, you will select (or in your case deselect) all of them once you click one.
You can store multiple variables in a list to access the state of each variable from other methods:
self.states = []
for res in resolution:
cvar = StringVar()
cvar.set("off")
Checkbutton(self.app, text=res, bg='#f1faee', variable=cvar, onvalue=res, offvalue='off').place(x=x_checkbox, y=120)
self.states.append(cvar)
x_checkbox += 100
You now have a list that is an attribute of your widget: It holds all the values for checkboxes. So, you can get the values simply by:
for v in self.states:
if not v.get()=="off":
print("Resolution selected: "+v.get())
You could also have two lists, one containing all the resolutions, the other containing an integer (1=checked, 0=unchecked), so you can see for all resolutions whether it was checked or not. In your program, you only see the checked ones. The others hold an uninformative 'off'
Upvotes: 3