tkinter : how to call a method of a child from another child
Try following: (See comment to see what I modified.)
class MainFrame(tk.Frame): def __init__(self,parent): tk.Frame.__init__(self,parent) self.x=my_label(self) self.up=my_update(self, self.x) # <-- pass another child to constructor self.grid()
class my_label(tk.Frame): def __init__(self,parent): tk.Frame.__init__(self,parent) self.l = tk.Label(self,text="some text") self.l.grid() self.grid() # my_update.ButtonPushed will call this method. def ButtonPushed(self): self.l['text'] = 'pushed'
class my_update(tk.Frame): def __init__(self,parent, friend): # ^^^^^^ # accept another child reference as `freind` as save it as self.friend tk.Frame.__init__(self,parent) self.friend = friend # <-- save reference to another child self.b=tk.Button(self,text="update",command=self.ButtonPushed) self.b.grid() self.grid() def ButtonPushed(self): self.friend.ButtonPushed() # <-- call another child's method freely.
For your side question: I'm not sure what else your application needs to do, so maybe there's a good reason, but it seems to me that wrapping the label and the button in an extra class that inherits from Frame
over complicates things a bit. I think I'd just do:
class MainFrame(tk.Frame): def __init__(self,parent): tk.Frame.__init__(self,parent) self.x=tk.Label(self, text="some text") self.up=tk.Button(self, text="update", command=self.ButtonPushed) self.x.grid() self.up.grid() self.grid() def ButtonPushed(self): # do something with self.x
Or if you really need the extra classes, why not have the child classes inherit from tk.Label and tk.Button. No real need to wrap them in an extra frame.