Home > Blockchain >  can not get the variable output in tkinter checkbutton
can not get the variable output in tkinter checkbutton

Time:11-08

I am new to tkinter and learning to use the widget "CheckButton". I have encountered a problem, whatever I select, the code prints 0.

Wanted:

  • print 1 if selected
  • print 0 if not selected

MWE

import tkinter as tk

win = tk.Tk()
win.title('My Window')
win.geometry('100x100')
 
l = tk.Label(win, width=20, text='MultipleReplace')
l.pack()

    
var_cb1 = tk.IntVar()
var_cb1.set(0)

cb1 = tk.Checkbutton(win, text='Yes',variable=var_cb1,onvalue=1,offvalue=0)
cb1.pack(side=tk.TOP)

var_cb1_val = var_cb1.get()

print('The selected value is : ', var_cb1_val)
win.mainloop()

CodePudding user response:

You're calling get on var_cb1 pretty much immediately after setting it to 0, and then printing that value. You're not waiting for the checkbutton to change states and then printing the value. Define a function that gets called when the CheckButton changes state, then get the value there

import tkinter as tk


def on_update(var):
    print('The selected value is: ', var.get())  # get the new value


win = tk.Tk()
win.title('My Window')
win.geometry('100x100')
 
l = tk.Label(win, width=20, text='MultipleReplace')
l.pack()
    
var_cb1 = tk.IntVar()
var_cb1.set(0)

cb1 = tk.Checkbutton(
    win, 
    text='Yes',
    variable=var_cb1,
    onvalue=1,
    offvalue=0,
    # call 'on_update', using a lambda to pass in the 'var_cb1' variable
    command=lambda var=var_cb1: on_update(var)
)
cb1.pack(side=tk.TOP)
win.mainloop()
  • Related