python - 如何用整数更新 tkinter 标签
问题描述
我试图让它当我按下一个按钮时,这个标签的值会上升,它是一个记分员。运行代码时出现的错误是 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()
解决方案
您正在添加一个Label
with int
,因此它会给出错误。相反,您应该使用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 并不是很喜欢这些单行...
推荐阅读
- java - 使用 OkHttp 请求时程序卡在 socketRead0 方法中
- kubernetes - Rook ceph 在 Kubernetes 上坏了?
- jquery - 更改表格中一行的位置
- c++ - qt 指向 qmap 的指针获取值
- java - 带有自定义字段绑定的 Jooq 批量插入
- node.js - 语法错误,不能在模块外使用 import 语句,即使在 package.json 中使用 "type":"module" 也会发生
- windows - 汇编中的变量到底是什么?
- regex - 仅当它们按顺序出现时才匹配一到三个组
- pycharm - Numba 矢量化在一个简单的例子中无法正常工作
- html - 禁用浏览器的黄色自动填充