[英]How to access a method variable (Tkinter) from another method in same class?
I have defined some variables in method 1 and i call method 2 from it.我在方法 1 中定义了一些变量,并从中调用方法 2。 In method 2, i have to access method 1 variable.
在方法 2 中,我必须访问方法 1 变量。
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
self.myElements()
def myElements(self):
self.master.title("1841144-SANDRINE P JOY")
self.pack(fill=BOTH , expand=1)
label1=Label(text="Starts with").place(x=10,y=0)
generateButton = Button(self,text="Generate", command=self.autogen)
generateButton.place(x=150,y=0)
label2=Label(text="--Here , your Random Name appears--").place(x=70,y=30)
def autogen(self):
randomName=pick(names)
label2.insert(INSERT,randomName) #This line is wrong
Thanks @AKX & @Cool Cloud for figuring my errors感谢 @AKX 和 @Cool Cloud 找出我的错误
Here is the corrected code这是更正后的代码
creating an instance of a method of the variable was all needed for it创建变量方法的实例是它所需要的
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
self.myElements()
def myElements(self):
self.master.title("1841144-SANDRINE P JOY")
self.pack(fill=BOTH , expand=1)
label1=Label(text="Starts with").place(x=10,y=0)
generateButton = Button(self,text="Generate", command=self.autogen)
generateButton.place(x=150,y=0)
self.result=Text(self,width=10,height=1)
self.result.place(x=70,y=30)
mstart = Label(self, text="Starting with M",bg='white',fg='black',font=("italic", 10)).place(x=20,y=50)
mtext = Text(self, width=15, height=10)
mtext.place(x=10,y=70)
pstart = Label(self, text="Starting with P",bg='white',fg='black',font=("italic", 10)).place(x=140,y=50)
ptext = Text(self, width=15, height=10)
ptext.place(x=120,y=70)
nstart = Label(self, text="Starting with N",bg='white',fg='black',font=("italic", 10)).place(x=260,y=50)
ntext = Text(self, width=15, height=10)
ntext.place(x=240,y=70)
def autogen(self):
randomName=pick(names)
self.result.insert(INSERT,randomName)
Store them as instance variables ( self.label1
etc.):将它们存储为实例变量(
self.label1
等):
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
self.myElements()
def myElements(self):
self.master.title("1841144-SANDRINE P JOY")
self.pack(fill=BOTH, expand=1)
self.label1 = Label(text="Starts with")
self.label1.place(x=10, y=0)
self.generateButton = Button(self, text="Generate", command=self.autogen)
self.generateButton.place(x=150, y=0)
self.label2 = Label(text="--Here , your Random Name appears--")
self.label2.place(x=70, y=30)
def autogen(self):
randomName = pick(names)
self.label2.insert(INSERT, randomName)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.