如何在不将 Label 重新分配给新变量的情况下向 Label 添加新值?

how to add new value to a Label , without reassign the Label to a new variabel?

我想创建一个按钮,在您按下它的同时显示您按下了多少次。

但我不知道每次按下时如何“刷新”它。

有人可以帮我吗?

from tkinter import *


class Press():
    def __init__(self):
        self.root = Tk()
        self.scale = self.root.wm_minsize(width=500, height=300)
        self.changer = StringVar()
        self.changer.set(0)

        self.label = Label(self.root , textvariable= self.changer)

        self.button = Button(self.root, text="PRESS", command= self.amount_pressed)


        self.button.pack()
        self.label.pack()
        self.mainloop = mainloop()

    def amount_pressed(self):
        self.changer.set(+1)

test = Press()

试试这个:

from tkinter import *


class Press():
    def __init__(self):
        self.root = Tk()
        self.scale = self.root.wm_minsize(width=500, height=300)
        self.changer = StringVar()
        self.changer.set(0)

        self.label = Label(self.root , textvariable= self.changer)

        self.button = Button(self.root, text="PRESS", command= self.amount_pressed)


        self.button.pack()
        self.label.pack()
        self.mainloop = mainloop()

    def amount_pressed(self):
        self.changer.set(int(self.changer.get()) + 1)

test = Press()

解释:

通过使用 self.changer.set(+1),您将 self.changer 设置为 正数 (相对于 加一个 )。

您想做的是:

  • 获取self.changer
  • 的字符串值
  • 将其转换为整数
  • 加1

所以:

self.changer.set(int(self.changer.get()) + 1)