如何用整数更新 tkinter 标签

How to update tkinter label with integer

我试图让它在我按下一个按钮时,这个标签的值上升,它是一个记分员。当我 运行 我的代码时得到的错误是 TypeError: unsupported operand type(s) for +: 'Label' and 'int' 我该如何解决这个问题?谢谢! 这是我的代码:

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()

您正在添加 Labelint,因此它会出错。相反,您应该添加带有 int 的“标签文本”。只需将您的功能更改为:

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

或者将您的按钮 command 更改为此一行:

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

不过请记住,PEP8 不太喜欢这些单行...