Jim
Jim

Reputation: 73

Buttons to remove themselves in Tkinter

I'm sorry if this has been asked already, but I haven't been able to find it. I'm also just starting to learn programming so feedback is appreciated. :)

My end goal is to create an 8 by "x" grid of buttons that change their own color when pushed. I want to use this to make a grid I can upload to the POV toy I've built. This code creates a column of 8 buttons each with a callback passing itself as an argument. The idea being the callback function can do things to the button like change it's color, or delete it.

import Tkinter    
def unpack(i):
    buttons[i].pack_forget()
    print i

top = Tkinter.Tk() buttons = [] for i in range(0, 8):
    buttons.append(Tkinter.Button(top, text='Hello', command=lambda: unpack(i)))

for button in buttons:
    button.pack()

top.mainloop()

When I do this I get a windows with column of 8 buttons, and when I click on one one gets deleted. When I click on a second nothing happens. In my command prompt I get the number 7 printed no matter which button I press. I suspect the problem is in the for loop that creates the buttons, but I have no idea how to fix it.

Thanks!

Upvotes: 3

Views: 1624

Answers (1)

falsetru
falsetru

Reputation: 368944

Pass the button object to the callback function instead of the index, because the index is change after the item deletion in the list.

import Tkinter    

top = Tkinter.Tk()
for i in range(0, 8):
    btn = Tkinter.Button(top, text='Hello')
    btn['command'] = lambda b=btn: b.pack_forget()
    btn.pack()

top.mainloop()

NOTE: To prevent late binding problem, I used default parameter in the above code.

Upvotes: 4

Related Questions