Gather input from multiple tkinter checkboxes created by a for loop

前端 未结 1 1160
鱼传尺愫
鱼传尺愫 2021-01-29 08:50

I made an application with tkinter which creates a list of checkboxes for some data. The checkboxes are created dynamically depending on the size of the dataset. I want to know

1条回答
  •  时光说笑
    2021-01-29 09:09

    Normally you need to create an instance of IntVar or StringVar for each checkbutton. You can store those in a list or dictionary and then retrieve the values in the usual way. If you don't create these variables, they will be automatically created for you. In that case you need to save a reference to each checkbutton.

    Here's one way to save a reference:

    self.general_checkbuttons = {}
    for i in range(1, self.height):
        cb = Checkbutton(self.new_window)
        cb.grid(row=i, column=3, sticky="nsew", pady=1, padx=1)
        self.general_checkbuttons[i] = cb
    

    Then, you can iterate over the same range to get the values out. We do that by first asking the widget for the name of its associated variable, and then using tkinter's getvar method to get the value of that variable.

    for i in range(1, self.height):
        cb = self.general_checkbuttons[i]
        varname = cb.cget("variable")
        value = self.root.getvar(varname)
        print(f"{i}: {value}")
    

    0 讨论(0)
提交回复
热议问题