How to get the value of a Variable associated with a Checkbutton in Tkinter? - Python

Asked

Viewed 81 times

-1

How could I get the value contained in checkBtVar having as reference ckBt?

for x in range(10):
  checkBtVar = Variable()

  ckBt = Checkbutton(root, variable=checkBtVar)
  ckBt.bind("<Button-1>",click)
  ckBt.pack()

def click(event):
  widget = event.widget
  v = widget.get()
  if v == True:
    #faça algo

There would be something like "var get.()" ?

(Note: The above code is only for Example)

1 answer

0


I don’t know anything like that "var get.()", but you can take the builtin __dict__ and take the contents of the key _tclCommands. For this example works.

from tkinter import *

root = Tk()

def click(event):
  print(event.widget.__dict__.get("_tclCommands", "Nenhum valor dentro de _tclCommands"))
  

for x in range(10):
  checkBtVar = Variable()
  ckBt = Checkbutton(root, variable=checkBtVar)
  ckBt.bind("<Button-1>",click)
  ckBt.pack()

UPDATE

Based on your post update, I think this will help you:

from tkinter import *

root = Tk()  

opt = []
ckButtons = []
ckButtons_v = []

def checkbox_clicked():
    for i, item in enumerate(ckButtons):
        opt[i]=(ckButtons_v[i].get())
    print(opt)


for x in range(10):
    ckButtons_v.append(Variable())
    off_value = False
    ckButtons.append(Checkbutton(root, onvalue=True, offvalue=off_value, variable=ckButtons_v[x], command=checkbox_clicked))
    opt.append(off_value)
    ckButtons[-1].deselect()
    ckButtons[-1].pack()

Each time a checkButton is clicked, you will have something like:

[1, 0, 0, 1, 0, 0, 0, 0, 0]

Where 1 is the marked button and 0 is unchecked.

I hope it helps.

  • Paul, how could I make a comparison using this method? I wanted the value of the variable to know if Checkbutton was selected or not. type: if widget.checkBtVar == True: >> (NOTE: I fixed the example of the code to make my doubt clearer)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.