【问题标题】:how to add new value to a Label , without reassign the Label to a new variabel? [duplicate]如何在不将 Label 重新分配给新变量的情况下向 Label 添加新值? [复制]
【发布时间】:2020-08-08 19:08:08
【问题描述】:

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

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

有人可以帮我吗?

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()

【问题讨论】:

    标签: python tkinter label


    【解决方案1】:

    试试这个:

    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)

    【讨论】:

    • 感谢您的帮助。它奏效了,我刚进入 tkinter 并感谢它提供的解释。
    • 太棒了!一些进一步的解释,以防将来有帮助:tkinter 标签不使用普通的 Python 变量类型。相反,他们使用 tcl 类型,例如StringVar。要获取这些变量的值,您可以调用他们的.get() 方法,该方法返回一个python 变量。现在您可以随意转换、更改和使用它了:)
    猜你喜欢
    • 2019-10-03
    • 2018-08-28
    • 2018-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-03
    • 1970-01-01
    • 2019-11-27
    相关资源
    最近更新 更多