【问题标题】:How to get value from multiple Checkbutton Tkinter如何从多个 Checkbutton Tkinter 中获取价值
【发布时间】:2023-03-14 01:05:02
【问题描述】:

在方法中生成 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

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

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

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

            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'

    【讨论】:

    • 我无法获取使用此方法@MartinWettstein 选择的值
    • 到底是什么问题?错误信息是什么?
    猜你喜欢
    • 1970-01-01
    • 2012-02-20
    • 1970-01-01
    • 1970-01-01
    • 2013-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多