bewop
bewop

Reputation: 11

Make an Entry When a Checkbox is Unchecked in Tkinter

I have a check button that is checked by default. If the user unchecks it, a label and an entry should appear. I tried to do so by using the key binding method; however, it has a drawback which is that if the user checks the checkbox again, the new label and entry won't disappear. How do I solve that problem?

checkButtonVar = IntVar(value = 1)
checkButtonIsChnaceDefault = Checkbutton(root, variable = checkButtonVar)
labelIsChanceDefault = Label(root, text="Make chance = 0.9?")
labelIsChanceDefault.grid(row=3, column = 0, sticky = 'w')
checkButtonIsChnaceDefault.grid(row = 3, column = 1)

def checkCheckButton(event):
    labelChance = Label(root, text = "Enter chance of winning")
    labelChance.grid( row = 3, column = 2)
    global entryChance
    entryChance = Entry(root, borderwidth = 3)
    entryChance.grid(row = 3, column = 3)

checkButtonIsChnaceDefault.bind('<Button-1>', checkCheckButton)

Here's a screenshot of the program to make things clear.

enter image description here

Upvotes: 0

Views: 677

Answers (1)

user15801675
user15801675

Reputation:

You don't need to bind the Check-button. Use command option. And setting offvalue and onvalue can control the appearance.

See the tkinter.Checkbutton

checkButtonVar = IntVar()
checkButtonIsChnaceDefault = Checkbutton(root, variable = checkButtonVar,offvvalue=0,onvalue=1,command=checkCheckButton)

...
checkButtonIsChnaceDefault.grid(row = 3, column = 1)

#==== Define the widgets here.
labelChance = Label(root, text = "Enter chance of winning")
entryChance = Entry(root, borderwidth = 3)

def checkCheckButton():
    if checkButtonVar.get()==0:
        labelChance.grid( row = 3, column = 2)
        entryChance.grid(row = 3, column = 3)
    else:
        labelChance.grid_forget()
        entryChance.grid_forget()

Upvotes: 1

Related Questions