0

everybody! I'm just learning python GUI and I can't figure out what am I doing wrong. I'm trying to draw a tree of buttons. I've created a first button in a frame then when I click it, I expect two more frames to be placed in a parent frame and two more buttons place in these new frames and so on. But when I'm clicking the button on a second iteration it adds new frames not to the button's frame but in the LAST FRAME that was created.

from Tkinter import *
class my_class():

def __init__(self,frame):
    self.frame=frame
def create_frames(self):
    Frames=[]
    p=2
    for k in range(p):

        New_frame=Frame(self.frame, highlightbackground="green", highlightcolor="green", highlightthickness=1,
                          width=100, height=100, bd=0)

        New_frame.pack(side=LEFT)
        Frames.append(New_frame)
        obj=my_class(Frames[k])
        but=Button(obj.frame, text='but', command=lambda:obj.create_frames())
        but.pack()


my_app=Tk()
obj=my_class(my_app)
but=Button(my_app,text='butt',command=lambda:obj.create_frames())
but.pack()
my_app.mainloop()

1-iteration

2-iteration (I pressed the first button)

Y. Stoian
  • 1
  • 3
  • 1
    There's something wrong with the indentation in your code. – Bryan Oakley Jul 05 '17 at 13:50
  • Probably classical [lambda-in-a-loop](https://stackoverflow.com/q/19837486/1639625) problem. `obj` is evaluated at the time the button is clicked, and then it's the instance from the last iteration. – tobias_k Jul 05 '17 at 13:52
  • Jup, exactly that. Change the command to `command=lambda obj=obj: obj. ...`, then it works. – tobias_k Jul 05 '17 at 13:55
  • @tobias_k THANK YOU SO MUCH! I was trying to fix it for a couple of days. It works now. Thanks you again! – Y. Stoian Jul 05 '17 at 14:15

0 Answers0