Reputation: 92
I have code like below (simplified), I can not run refresh method of Root widget, but I have the same system in a different program and it works. I wrote it 3 times in different files and sometimes it works, and sometimes does not. Maybe I am doing something wrong about creating this attr self.a
, so please tell me how to do it so it would work always.
Error:
AttributeError: '_tkinter.tkapp' object has no attribute 'a'
from tkinter import *
class Window(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
Label(self, text="some text").pack()
self.master.refresh()
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()
Upvotes: 1
Views: 569
Reputation: 8042
Your code works, just your structure do not. Hope you can deal with a button.
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()
edit
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()
Upvotes: 2