如何更新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
相关产品推荐
相关产品推荐

