Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 946
Jim Avatar asked Mar 04 '26 18:03

Jim


1 Answers

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.

like image 61
falsetru Avatar answered Mar 07 '26 06:03

falsetru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!