使用的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