0

I am making a login page with tkinter..

So when the user clicks on the CheckButton, I want the password to be displayed and when it is unchecked, I want it to be hidden... (star marked)

I am not able to change the state of the CheckButton...

Have viewed several answers but it did not solve my issue

My sample code below:

from tkinter import *

win = Tk()
var = IntVar()
chk = Checkbutton(win, text='See password', variable=var)
chk.grid(row=4, column=1, pady=5)

if var.get():
    print("Checked")
else:
    print("Not checked..")

win.mainloop()

When I run the code, the default is unchecked. So after I check, it does not print Checked.

wovano
  • 4,543
  • 5
  • 22
  • 49
  • You're calling `var.get()` about a millisecond after creating the widget. The user won't have even _seen_ the widget, much less have time to click on it. – Bryan Oakley Nov 03 '20 at 17:18
  • Yeah I get that....How can I change it so that when the user clicks, I can get the state changed? –  Nov 03 '20 at 17:28
  • That is covered in available documentation. You can attach a command to a checkbutton. – Bryan Oakley Nov 03 '20 at 17:34

1 Answers1

0

You can bind your IntVar() to a function, if your IntVar() changed, youor function will execute:

from tkinter import *


def callback(a, b, c):
    if var.get():
        print("Checked")
    else:
        print("Not checked..")


win = Tk()
var = IntVar()
var.trace('w', callback)
chk = Checkbutton(win, text='See password', variable=var)
chk.grid(row=4, column=1, pady=5)

win.mainloop()
CC7052
  • 563
  • 5
  • 16
  • 2
    This is the (slightly) harder way to do it. A simpler method is to use the `command` attribute of the checkbutton. – Bryan Oakley Nov 03 '20 at 17:44