【发布时间】:2021-10-28 19:04:12
【问题描述】:
我试图让它当我按下一个按钮时,这个标签的值会上升,它是一个记分员。运行代码时出现的错误是 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()
【问题讨论】:
-
point1 = point1 + 1不正确,因为您正在使用标签本身并将其添加到数字中,有点像添加椰子和橙子。你想point1.config(text=int(point1['text'])+1)。虽然更好的方法是在外部创建一个标签,然后不断更新它。 -
@CoolCloud
point1['text']?我感觉 OP 可能会询问point未定义 -
现在,每当我点击时,什么都没有发生。该程序运行没有任何错误,但没有任何反应。我做错了什么?
-
@Kai 用我刚刚给出的代码替换你的函数。
-
@CoolCloud 你打错了:
point['text']至少在我看来,是的,你的答案也适用于你和其他人,如果他们知道如何正确实现它,也许写一个回答?
标签: python tkinter integer label