How to increment number from a button click

Asked

Viewed 893 times

0

I want a button that adds ''+1 'to the label that is displayed in the tkinter, but I do not know very well how to do, and I found nothing on Google, what I understood does not return what I wanted, instead of adding ex: press the button "+" 1x it changes the value to 1, press again it changes the value to 2, again to 3(adding +1 every time clicked)And unlike with "-" decreasing that same number 3,2,1 if necessary

from tkinter import*
janela = Tk()
text = 0


def bt7_click(): #botao +
    soma =(text)
    lb4["text"] = str(text + 1)

def bt8_click():
    soma =(text)
    lb4["text"] = str(text - 1)



lb4 = Label(janela,text="0",font="Arial 50", fg= "red", bg="white")
lb4.place(x=50, y=50)


bt7 = Button(janela, width=1, text="+", command=bt7_click)
bt7.place(x=130, y=90)
bt8 = Button(janela, width=1, text="-", command=bt8_click)
bt8.place(x=150, y=90)


janela.geometry("200x200")
janela.mainloop()

1 answer

1


Good morning,

for you to be able to do this increment and decrement control you will need a accumulator

you can use the field itself as accumulator for example,

with some minor modifications to your code, you can do it as follows:

from tkinter import*
janela = Tk()

limite = 0

def bt7_click(): #botao +
    val = int(lb4["text"])
    lb4["text"] = str(val + 1)

def bt8_click():
    val = int(lb4["text"])
    if val <= limite:
        val = limite + 1
    lb4["text"] = str(val - 1)


lb4 = Label(janela,text="0",font="Arial 50", fg= "red", bg="white")
lb4.place(x=50, y=50)
bt7 = Button(janela, width=1, text="+", command=bt7_click)
bt7.place(x=130, y=90)
bt8 = Button(janela, width=1, text="-", command=bt8_click)
bt8.place(x=150, y=90)

janela.geometry("200x200")
janela.mainloop()

lb4["text"] = '0'
  • Good morning, thank you very much, I had tried something similar but this way " val = int(text)"" that was not correct, is there a way to limit it so that it does not become negative? -1, -2? Just go to 0?

  • Good morning, opa, has yes I will edit the answer, more in practice you will only need to create a variable setting the limit limite = 0 for example, there inside the decrement click you do the validation

  • edited response

Browser other questions tagged

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