如何从多个Checkbutton Tkinter中获取值



在一个方法中生成Checkbutton时,如何从多个Checkbutton中检索值?

必须检索检查值的方法按钮

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')

创建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

如果创建了多个复选框,则不应为每个复选框使用相同的变量。否则,一旦单击其中一个,您将选择(或在您的情况下取消选择(所有这些选项。

您可以将多个变量存储在一个列表中,以从其他方法访问每个变量的状态:

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

现在您有了一个列表,它是小部件的一个属性:它包含复选框的所有值。因此,您可以简单地通过以下方式获取值:

for v in self.states:
if not v.get()=="off":
print("Resolution selected: "+v.get())

您还可以有两个列表,一个包含所有分辨率,另一个包含一个整数(1=选中,0=未选中(,这样您就可以查看所有分辨率是否选中。在您的程序中,您只能看到选中的那些。其他人持有无信息的'off'

最新更新