【问题标题】:How to update tkinter label with integer如何用整数更新 tkinter 标签
【发布时间】: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


【解决方案1】:

您正在添加 Labelint,因此会出错。相反,您应该使用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 并不是很喜欢这些单线...

【讨论】:

    猜你喜欢
    • 2015-12-08
    • 1970-01-01
    • 2017-04-12
    • 1970-01-01
    • 2017-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多