在方法中生成 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')
创建复选按钮的方法
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'
关于python - 如何从多个 Checkbutton Tkinter 获取值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66626627/