Home > Software engineering >  Python Tkinter Getting value of CheckButton from children list
Python Tkinter Getting value of CheckButton from children list

Time:11-07

I got widget list of frame with frame.winfo_children(). Now i need to get that checkbutton's value.Children List:

[<tkinter.Label object .!toplevel2.!labelframe.!label>, <tkinter.Entry object .!toplevel2.!labelframe.!entry>, <tkinter.Entry object .!toplevel2.!labelframe.!entry2>, <tkinter.Checkbutton object .!toplevel2.!labelframe.!checkbutton>]

What i tried :

checkbuttonwidget.get() , checkbuttonwidget.cget('variable')

How can i get its value? And is there any option to use if command for split these children? For example:

for wid in frame.winfo_children():
    if wid == LABEL(option?):
        print('yes its a label')
    elif wid == CheckButton(option?):
        print('Its a CheckButton')

Thanks..

CodePudding user response:

The simplest way to check if the widget is a Checkbutton is to use isinstance, then to get the value, you can use .getvar and the widget['variable'] (or widget.cget('variable') depending on what you prefer) to get the value of the corresponding variable:

for widget in frame.winfo_children():
    if isinstance(widget, tk.Checkbutton):
        value = frame.getvar(widget['variable'])
        print(value)

Also depending on how you imported you may need to use Checkbutton instead of tk.Checkbutton

Useful:

  • isinstance docs

  • getvar(self, name='PY_VAR')
        Return value of Tcl variable NAME.
  • Related