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

2024-04-29 03:30:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用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()

当我运行这个函数时,它告诉我click函数中没有定义“Amount”。我知道这是因为它是在一个不同的函数中定义的。我想知道如何使它的点击功能识别'数额'。你知道吗


Tags: 函数textfromselfmastergame定义tkinter
1条回答
网友
1楼 · 发布于 2024-04-29 03:30:56

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

我会和数据员一起去。你知道吗

为了将它用作数据成员,应该使用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变量。你知道吗

相关问题 更多 >