0

I am creating the checkbuttons here:

var = []
k=0
for i in results:
    var.append(IntVar())
    Checkbutton(frame, text = i[0], variable = var[k], wraplength=500).pack()
    k+=1

Here, I have obtained the variable for each check button and want to print the text of the checkbuttons that are checked:

# function is called when a button is clicked
def delHist():
    for i in range(len(var)):
        if var[i].get()==1:      # checking if the checkbutton is checked
            # want to print the text in the checkbutton here

How can I print the text of that checkbutton using only the variable?

Edit: The question here seems to be similar: How to get the text from a checkbutton in python ? (Tkinter)

I tried assigning Checkbutton(frame, text = i[0], variable = var[k], wraplength=500).pack() to a list ch[p] so as it iterates, it's assigned to a new object. When I added print ch[p].get() under the function, I get an error. I also tried print ch[p].get('text') but I get the error

TypeError: "get()" takes 1 positional argument but 2 were given

Lee Yerin
  • 37
  • 4
  • Does this answer your question? [How to get the text from a checkbutton in python ? (Tkinter)](https://stackoverflow.com/questions/33545085/how-to-get-the-text-from-a-checkbutton-in-python-tkinter) – 10 Rep Jun 17 '20 at 14:11
  • @TheMaker I've edited the question to explain why it isn't working for me. – Lee Yerin Jun 17 '20 at 14:24
  • 1
    Does this answer your question? https://stackoverflow.com/questions/48436622/how-to-get-the-text-of-checkbuttons – 10 Rep Jun 17 '20 at 14:32
  • You can use `StringVar` instead of `IntVar` and set `onvalue=i[0]` and `offvalue=''` for each checkbutton. Then if `var[i].get()` return something, then the checkbutton is checked and you can print the content. – acw1668 Jun 17 '20 at 16:30

3 Answers3

1

If you set the onvalue to the same value as the text (or whatever value you want), the variable will either contain that value or an empty string.

You would need to first switch from IntVar to StringVar, and then set the onvalue and offvalue:

var.append(StringVar())
buttons.append(Checkbutton(tk, text = i[0], variable = var[k], wraplength=500, onvalue=i[0], offvalue=""))

Next, you can modify delHist to simply print the values that are not the empty string:

def delHist():
    for variable in var:
        value = variable.get()
        if value:
            print(value)
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
0

If I understand correctly (correct me in comments), here is what you need:

from tkinter import *

tk = Tk()

var = []
buttons = []
k=0
def delHist():
    for i in range(len(var)):
        if var[i].get()==1:
            print(buttons[i]['text'])
for i in 'abcde':
    var.append(IntVar())
    buttons.append(Checkbutton(tk, text = i[0], variable = var[k], wraplength=500))
    buttons[-1].pack()
    k+=1

Button(text='delHist', command=delHist).pack()

Note that I'm appending Checkbutton(...) to list, not Checkbutton(...).pack(), and running .pack() method afterwards. The reason is that the first one returns a Checkbutton object while the second one NoneType - this is not jQuery. Hope that's helpful!

rizerphe
  • 1,340
  • 1
  • 14
  • 24
0

Tkinteris OOP, therefore the opposite takes place.
Extend the tk.Checkbutton object and forget abbout the variable=tk.IntVar().
The extended Checkbutton knows his text= and checked state.

enter image description here

import tkinter as tk


class Checkbutton(tk.Checkbutton):
    def __init__(self, parent, **kwargs):
        self._var = tk.IntVar()
        # kwargs['variable'] = self._var
        super().__init__(parent, variable=self._var, **kwargs)

    @property
    def checked(self):
        return self._var.get() == 1

    def __str__(self):
        return f"Checkbutton: {self['text']}={self.checked}"

Usage:

class App(tk.Tk):
    def __init__(self):
        super().__init__()

        self.frame = tk.Frame(self)
        self.frame.pack()
        for text in ('option 1', 'option 2', 'option 3'):
            Checkbutton(self.frame, text=text, wraplength=500).pack()

        tk.Button(self, text='Show Checkbutton state', command=self.on_button_click).pack()

    def on_button_click(self):
        for ckb in self.frame.children.values():
            print(ckb)

if __name__ == '__main__':
    App().mainloop()

Output:

Checkbutton: option 1=False
Checkbutton: option 2=True
Checkbutton: option 3=False
stovfl
  • 14,998
  • 7
  • 24
  • 51