Python 如何调用在不同函数中定义的Tkinter标签?
我正在用Python制作一个简单的小游戏。这就是我目前拥有的:Python 如何调用在不同函数中定义的Tkinter标签?,python,function,tkinter,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
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”。我知道这是因为它是在不同的函数中定义的。我想知道如何使单击函数识别“金额”。您应该将金额定义为数据成员每个实例都有其值,或者将静态成员定义为与所有类实例相同的值 我会和数据成员一起去 要将其用作数据成员,应使用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变量。我尝试了此操作,并收到以下错误:Tkinter回调中出现异常_tkinter.TclError:未知选项-class@MarkCostello,将该行修复为self.Amount.configtext=x[0],这应该可以工作。我的程序与您编辑的程序完全相同,但仍会出现“未知选项-类”错误。请将其删除!我没有注意到您从self.Amount.config参数中删除了“root”。非常感谢你!