python - 如何从多个 Checkbutton Tkinter 获取值(value)

标签 python 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')

创建复选按钮的方法

    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/

相关文章:

python - 似乎无法为 python 导入 Tkinter

Python百分比计算器

python - 使用cython性能下降

python - 构建正则表达式以匹配 Python 中多个匹配项中的第一个匹配项

python - 在 matplotlib 图的交互式导航中保留缩放设置

python - 如何启动自毁的 Python/Tkinter 对话框?

python - Tkinter 实时图形 Canvas 停止更新,直到鼠标移动

python - array[::-1]的时间复杂度和空间复杂度是多少

python - 如何从图像 url (jpeg) 读取字节并在 Python 2.7 上以 base64 编码?

python - dyno falls sleep django heroku postgresql 后找不到图像