Gather input from multiple tkinter checkboxes created by a for loop

纵然是瞬间 提交于 2021-02-05 12:16:43

问题


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 of a way to get the input of each specific checkbox.

Here is my code, which you should be able to run.

from tkinter import *

root = Tk()

height = 21
width = 5

for i in range(1, height):
    placeholder_check_gen = Checkbutton(root)
    placeholder_check_gen.grid(row=i, column=3, sticky="nsew", pady=1, padx=1)

for i in range(1, height):
    placeholder_scope = Checkbutton(root)
    placeholder_scope.grid(row=i, column=4, sticky="nsew", pady=1, padx=1)

root.mainloop()

I looked over other answers and some people got away by defining a variable inside the checkbox settings "variable=x" and then calling that variable with a "show():" function that would have "variable.get()" inside. If anyone could please point me in the right direction or how I could proceed here. Thank you and much appreciated.


回答1:


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}")


来源:https://stackoverflow.com/questions/63000455/gather-input-from-multiple-tkinter-checkboxes-created-by-a-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!