如何调用在不同函数中定义的Tkinter标签?

时间:2017-02-23 16:03:53

标签: python function tkinter

我正在使用Python制作一个简单的小型点击游戏。这就是我现在所拥有的:

from tkinter import *

x = [0]
y = [1]

class Game:
    def __init__(self, master):
        master.title('Game')

        Amount = Label(master,text=x[0])
        Amount.pack()

        Butt = Button(master,text='Press!',command=self.click)
        Butt.pack()

    def click(self):
        x[0] = x[0] + y[0]
        Amount.config(root,text=x[0])
        print(x[0])

root = Tk()
root.geometry('200x50')
game = Game(root)
root.mainloop()

当我运行它时,它会告诉我' Amount'未在单击函数中定义。我知道这是因为它在不同的功能中定义。我想知道如何制作它,以便点击功能识别“数量”。

1 个答案:

答案 0 :(得分:1)

您应该将金额定义为数据成员(每个实例都有其值)或静态成员(与所有类实例相同的值)。

我会选择数据成员。

要将其用作数据成员,您应使用self.Amount

所以,这就是你需要的:

from tkinter import *

x = [0]
y = [1]

class Game:
    def __init__(self, master):
        master.title('Game')

        self.Amount = Label(master,text=x[0])
        self.Amount.pack()

        Butt = Button(master,text='Press!',command=self.click)
        Butt.pack()

    def click(self):
        x[0] = x[0] + y[0]
        self.Amount.config(text=x[0])
        print(x[0])

root = Tk()
root.geometry('200x50')
game = Game(root)
root.mainloop()

self在您的类方法中共享,因此您可以通过它访问Amount变量。