单击时更改 txt 的 tkinter 按钮

tkinter button with changing txt when clicked

所以我知道问题出在哪里,只是不知道如何解决: self.health 被存储在变量中一次,之后不会重新读取。我试过使用:@属性。但是我昨天才知道@属性,所以要么1:我没有正确使用它,要么2:它不能在这种情况下使用。

import tkinter as tk


class button_health:
    def __init__(self):
        self.health = 5
    def hit(self, event):
        self.health -= 1
bob = button_health()

window = tk.Tk()
button = tk.Button(window, text = bob.health #I want this to update)
button.bind("<Button-1>", bob.hit)
button.pack()

window.mainloop()

我的目标是让代码在屏幕上生成一个简单的 tkinter 按钮,该按钮开始显示“5”,然后当您单击它时显示“4”,然后单击“3”等。

tk.Button 中有一个名为 command 的参数。将 button-1 绑定到函数并不是检查用户是否单击按钮的最佳方法。即使你使用了 bind,它也应该绑定到一个函数,而不是 class。 要更改按钮的文本,您可以将 button['text'] 设置为某些内容。

import tkinter as tk


def button_health():
    global health
    health -= 1
    button['text'] = str(health)

health = 5
window = tk.Tk()
button = tk.Button(window, text = health , command = button_health)
button.pack()

window.mainloop()

您也可以通过这样做来避免使用 global 语句:

import tkinter as tk

def button_health(but):
    but.health -= 1
    but['text'] = str(but.health)

window = tk.Tk()
button = tk.Button(window)
button.health = 5
button['text'] = str(button.health)
button['command'] = lambda: button_health(button)
button.pack()

window.mainloop()

这样做的另一个好处是它可以保持按钮的运行状况独立,因此如果您有多个按钮,这将使所有按钮的计数器保持不同。

使用button['text']button.config(text={text})

class button_health:
    def __init__(self):
        self.health = 5
    def hit(self, event):
        self.health -= 1
        button['text'] = str(self.health)

class button_health:
    def __init__(self):
        self.health = 5
    def hit(self, event):
        self.health -= 1
        button.config(text= str(self.health))

使用 Tkinter IntVar 变量来跟踪健康值的变化。使用 textvariable 属性将该变量连接到按钮标签。

import tkinter as tk

class button_health:
    def __init__(self, health=5):
        self.health = tk.IntVar()
        self.health.set(health)

    def hit(self, event=None):
        if self.health.get() >= 1:    # assuming that you can't have negative health
            self.health.set(self.health.get() - 1)

window = tk.Tk()
bob = button_health(8)
button = tk.Button(window, textvariable=bob.health, command=bob.hit)
#button = tk.Button(window, textvariable=bob.health)
#button.bind('<Button-1>', bob.hit)
button.pack()

window.mainloop()

另一种方法是创建自己的按钮 class 作为 Button 的子 class 并将 IntVar 作为 [=21= 的成员].这样您就可以轻松创建多个具有不同健康值的独立按钮:

import tkinter as tk

class HealthButton(tk.Button):
    def __init__(self, window, health=5, *args, **kwargs):
        self.health = tk.IntVar()
        self.health.set(health)
        super(HealthButton, self).__init__(window, *args, textvariable=self.health, command=self.hit, **kwargs)

    def hit(self):
        if self.health.get() >= 1:
            self.health.set(self.health.get() - 1)

window = tk.Tk()
buttons = [HealthButton(window, i) for i in range(10,15)]
for b in buttons:
    b.pack()

window.mainloop()