Python Tkinter对象没有属性,有时有效,有时无效?
我有下面这样的代码(简化),我不能运行根控件的刷新方法,但我在不同的程序中有相同的系统,它可以工作。我在不同的文件中写了3次,有时有效,有时无效。也许我在创建这个attrPython Tkinter对象没有属性,有时有效,有时无效?,python,tkinter,Python,Tkinter,我有下面这样的代码(简化),我不能运行根控件的刷新方法,但我在不同的程序中有相同的系统,它可以工作。我在不同的文件中写了3次,有时有效,有时无效。也许我在创建这个attrself.a时做错了什么,所以请告诉我怎么做,这样它就会一直工作 错误: AttributeError:“\u tkinter.tkapp”对象没有属性“a” 从tkinter导入* 类窗口(框架): 定义初始化(自身,父级): 帧。\uuuu初始化(自,父) 标签(self,text=“some text”).pack() s
self.a
时做错了什么,所以请告诉我怎么做,这样它就会一直工作
错误:
AttributeError:“\u tkinter.tkapp”对象没有属性“a”
从tkinter导入*
类窗口(框架):
定义初始化(自身,父级):
帧。\uuuu初始化(自,父)
标签(self,text=“some text”).pack()
self.master.refresh()
类根(Tk):
定义初始化(自):
Tk.\uuuuuu初始(自我)
self.a=窗口(self)
self.a.pack()
self.mainloop()
def刷新(自我):
自我毁灭
self.a=窗口(self)
self.a.pack()
根()
您的代码可以工作,但您的结构不能。希望你能处理一个按钮
from tkinter import *
class Window(Frame):
def __init__(self, master):
Frame.__init__(self, master)
Label(self, text="some text").pack()
b = Button(self, text='refresh', command =lambda:self.master.refresh())
b.pack()
class Root(Tk):
def __init__(self):
Tk.__init__(self)
self.a = Window(self)
self.a.pack()
self.mainloop()
def refresh(self):
self.a.destroy()
self.a = Window(self)
self.a.pack()
Root()
编辑
from tkinter import *
#this is the tricky version, lambda will not show any error if a error occurs
class Root(Tk):
def __init__(self):
Tk.__init__(self)
self.a = Window(self)
self.a.pack()
self.mainloop()
def refresh(self):
self.a.destroy()
self.a = Window(self)
self.a.pack()
def function():
print('I am the executing function')
class Window(Frame):
def __init__(self, master):
Frame.__init__(self, master)
Label(self, text="some text").pack()
b = Button(self, text='refresh', command =lambda:[self.master.refresh(),self.func(), function()])
b.pack()
def func(self):
print('I am the executing func')
Root()
from tkinter import *
#this is the safer exampel, cause if a error occurs you will notice.
class Root(Tk):
def __init__(self):
Tk.__init__(self)
self.a = Window(self)
self.a.pack()
self.mainloop()
def refresh(self):
self.a.destroy()
self.a = Window(self)
self.a.pack()
class Window(Frame):
def __init__(self, master):
Frame.__init__(self, master)
Label(self, text="some text").pack()
b = Button(self, text='refresh', command =self.func)
b.pack()
def func(self):
self.master.refresh()
Root()
窗口。
正在根目录之前调用刷新()
。
已完成初始化Tk
子类实例。我能做什么?好的,谢谢,请告诉我为什么它可以作为按钮命令工作,为什么不像我写的那样,因为你的函数在创建窗口之前就破坏了它。即使是程序也需要时间来完成它们的工作。好吧,但当我使用self.master.refresh()时,我也想执行其他操作,但我无法将更多函数打包到lamda函数中。当我试图调用某个函数作为按钮命令(包含self.master.refresh)时,它会给我错误。您能将self.master.refresh()也放入该函数吗?另外,您可以向lambda添加多个函数。但是lambda在以后的调试中有点棘手,请首先考虑是否可以将该命令也放到该函数中