使用的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()
另一种方法是创建自己的按钮类为Button
一个子类,挂钩一个IntVar
作为类中的一员。通过这种方式,您可以轻松创建多个具有不同健康值的独立按钮:
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()
Thanks :)。我将不得不做一点点的学习来完全理解你的回答(我从来没有用过lambda)。但看起来不错。 我努力遵循第二个解决方案的语法。我仍然很喜欢python。 button.health = 5#我以前没有遇到过这种语法。我不明白这是什么。它是否在按钮中创建了一个名为“健康”的变量并将其分配给5? –
'button.health = 5'在'button'中创建一个名为'health'的*属性*。这样,跟踪谁的健康状况会更容易。 'button.health'的'health'对于'button'永远是唯一的。 – abccd
而在我的情况下,lambda保持'button_health(button)'在'command'被定义之后执行。 – abccd