首页 > 解决方案 > 如何用整数更新 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()

标签: pythontkinterintegerlabel

解决方案


您正在添加一个Labelwith 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 并不是很喜欢这些单行...


推荐阅读