That function soma
seems unnecessary to me, as you just update the contents of the button directly:
def bt_click():
lb['text'] = int(lb['text']) + 1
Since the button text is a string, I use int
to convert its contents to number, and then sum 1 and update the text of the button. So it looks like this:
from tkinter import *
root = Tk()
root.geometry('500x500')
def bt_click():
lb['text'] = int(lb['text']) + 1
lb = Label(root, text = '10')
lb.place(x = 245, y = 235)
bt = Button(root, text = '+ 1', command = bt_click)
bt.place(x = 175, y = 235)
root.mainloop()
If you want much use such a function soma
, then I could do so:
def soma(a, b):
lb['text'] = a + b
def bt_click():
soma(int(lb['text']), 1)
I deleted the global variable because apparently there is no reason to keep it (but if there is, you can use the solution of the other answer to keep it updated). Also there is no reason to throw the sum in a variable s
, only to then assign s
label. If you are not going to use s
for nothing else, delete it and play the result of the sum directly on the label.
Although the function soma
should not update the button, it should only return the result of the sum and nothing else (and whoever calls the function does what they need with the result). I mean, something like that:
def soma(a, b):
return a + b
def bt_click():
lb['text'] = soma(int(lb['text']), 1)
But I still think I exaggerate for this particular case, and I would stick with the first solution I suggested, which doesn’t use the function soma
. Of course, if you are going to do several other more complex things, then it is worth breaking into smaller functions. But for your specific case, I don’t think you need.
If one of the answers solved your problem, you can choose the one that best solved it and accept it, see here how and why to do it. It is not mandatory, but it is a good practice of the site, to indicate to future visitors that it solved the problem. Don’t forget that you can also vote in all the answers you found useful (in case you haven’t voted yet - tb is not required, but if you thought it useful, consider voting :-) )
– hkotsubo