单击时更改txt的tkinter按钮

时间:2017-03-27 23:56:52

标签: python tkinter python-3.6

所以我知道问题是什么,我只是不知道如何修复它: self.health存储在变量中一次,之后不会重新读取。我尝试过使用:@property。但我昨天才刚刚了解了@property,所​​以要么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按钮,开始说&#34; 5&#34;然后当你点击它时,说&#34; 4&#34 ;然后点击&#34; 3&#34;等。

3 个答案:

答案 0 :(得分:1)

command中有一个名为tk.Button的参数。将按钮1绑定到功能并不是检查用户是否单击按钮的最佳方法。即使你使用了bind,它也应该绑定到一个函数,而不是一个类。 要更改按钮的文字,您可以将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()

这样做的另一个好处是它可以保持按钮的健康状态独立,所以如果你有多个按钮,这将使所有按钮的计数器保持不同。

答案 1 :(得分:1)

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

答案 2 :(得分:1)

使用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()
相关问题