Check if Checkbox is checked

Asked

Viewed 326 times

2

In the code below I have a Checkbox named cb.

I wanted to know when it was selected/marked so that my program could run another account instead of adding.

How do I detect that the Checkbox is selected?

Code:

<code> 
from tkinter import *
from functools import partial

def calc(arg):
    if(str(ed.get()).isnumeric() and str(ed2.get()).isnumeric()):
        a = int(ed.get())
        b = int(ed2.get())
        soma = a+b
        lb1["text"] = "Soma entre os valores {}".format(soma)
        lb1["bg"] = "blue"
    else:
        lb1["text"] = "[~~ERRO~~] DIGITE APENAS NÚMEROS"
        lb1["bg"] = "red"

j = Tk()
#CHECKBOXES
cb =  Checkbutton(j)
cb.grid (row=3, column = 5)
## INPUTS 
ed = Entry(j)  #Input
ed.place(x=360, y=205)  #Input
ed2 = Entry(j)
ed2.place(x=360, y=225)

# LABELS
lbd1 = Label(j, text="Digite o 1º Número: ")
lbd2 = Label(j, text="Digite o 2º Número: ")

lbd1.place(x=200, y=200)
lbd2.place(x=200, y=220)

# BOTOES
bt1 = Button(j, width=20, height=1, bg="white", text="Ok")
bt1.place(x= 300, y= 260)
bt1["command"] = partial(calc, bt1)

#RESULTADO LABEL
lb1 = Label(j, width = 40, bg="green", text="Resultado") 
lb1.place(x=200, y=300)

# CONFIG GERAL
j.geometry("800x600+200+200")
j.mainloop()
</code>

1 answer

2


You have to make some changes to the code

First of all you need to declare a variable that will store the change of status in the case of checkbox ele só terá dois estados0ou1`

checkButtonSub = IntVar()

In the statement of CheckButton you need to say that it will receive a parameter of type variable and declare the variable checkButtonSub.

cb =  Checkbutton(j, text='subtração', variable=checkButtonSub)

finally in function calc checks whether checkbutton status change

        if checkButtonSub.get()==1:
            resultado = a-b
        else:
            resultado = a+b

Note: I changed the variable name soma for resultado

  • It worked yes, I had researched a little more and I found this same solution

Browser other questions tagged

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