You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何更新tkinter Label的整数值 修复Label与int相加报错问题

错误原因

你触发报错的直接原因是:在addone1、addone2函数内部,先创建了新的局部Label对象覆盖了全局的计分Label变量,之后直接对Label对象执行整数加法运算,Python不支持Label类型和int类型做相加操作,所以抛出类型错误。
除此之外你还有逻辑错误:每次点击按钮都重新初始化Label的文本为0,就算没有类型错误,每次点击也只能得到结果1,无法实现累计计分的效果。

修复方案

修改两个计分函数的逻辑即可:

  • 不要在函数内重新创建Label实例,直接操作全局已经渲染好的point1、point2对象
  • 调用Label的cget("text")方法获取当前展示的数值,转换为整数后加1,再调用config(text=新值)方法更新Label的显示内容

完整可运行代码

from tkinter import *

root = Tk()
root.title('Basketball Score')
root.geometry("260x600")
point1 = Label(root, text=0)
point2 = Label(root, text=0)

def addone1():
    current_score = int(point1.cget("text"))
    point1.config(text=current_score + 1)

def addone2():
    current_score = int(point2.cget("text"))
    point2.config(text=current_score + 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()

内容的提问来源于stack exchange,提问作者Kai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 17:30:01