Kai
Kai

Reputation: 55

How to update tkinter label with integer

I'm trying to have it so that when I press a button, the value of this label goes up, it's a score keeper. The error I get when I run my code is TypeError: unsupported operand type(s) for +: 'Label' and 'int' How can I fix this? thanks! Here is my code:

from tkinter import *

root = Tk()
root.title('Basketball Score')
root.geometry("260x600")
point1 = Label(root, text=0)
point2 = Label(root, text=0)
def addone1():
    point1 = Label(root, text="0")
    point1 = point1 + 1
def addone2():
    point2 = Label(root, text="0")
    point2 = point2 + 1

titlelabel = Label(root, text="Basketball Score Keeper")
titlelabel.grid(row=0, column=3)

button1 = Button(root, text="Add Point", command=addone1)
button1.grid(row=1, column=0)
button2 = Button(root, text="Add Point", command=addone2)
button2.grid(row=1, column=5)

point1.grid(row=2, column=0)

point2.grid(row=2, column=5)

root.mainloop()

Upvotes: 2

Views: 1069

Answers (1)

Delrius Euphoria
Delrius Euphoria

Reputation: 15098

You are adding a Label with int and hence it gives error. Instead you should add the "text of the label" with the int. Just change your function to this:

def addone1():
    text = int(point1['text'])
    point1.config(text=text+1)

Or change your button command to this one-liner:

button1 = Button(...,command=lambda: point1.config(text=int(point1['text'])+1))

Though keep in mind, PEP8 isn't very fond of these one-liners...

Upvotes: 1

Related Questions