0

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.

2
  • 2
    It would help if you reduced this code down to a minimal reproducible example. For example, if the question is about getting values from checkbuttons created in a loop then we don't need labels created in a loop, or menus, or additional frames. Also, your code has indentation errors. Commented Jul 20, 2020 at 17:52
  • 1
    @BryanOakley Thank you for your suggestion. I updated the code to be minimal as you suggested. Also, thank you for your answer below. Commented Jul 27, 2020 at 5:21

1 Answer 1

2

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}")
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the solution and for the explanations as well! It worked perfectly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.