button - Dynamicaly deleting widgets in Tkinter in Python -
i have widgets in tkinter frame want remove on users click. there labels , each label, there corresponding button remove it. here code making frame.
def delfav(): win2 = tk() widgets = [] url in urls: label = label(win2, text = url) button = button(win2, text = "delete") widgets.append({"url" : url, "label" : label, "button" : button}) w in widgets: print w["url"], w["label"], w["button"] w["button"].configure(command = lambda : delete(w["url"], widgets)) w["label"].pack() w["button"].pack()
the delete function looks this:
def delete(url, widgets): w in widgets: if w["url"] == url: print w["label"] print w["button"] w["label"].pack_forget() w["button"].pack_forget() return
when want delete url press associated button, last button removed. eg, output generated clicking 2nd delete button, out of 3 buttons.
entry/13394 .44877224 .44877384 entry/13277 .44877464 .44877544 entry/8166 .44877624 .44877704 .44877624 .44877704
the first 3 lines show widgets list, , on clicking middle button, last button , label names printed delete function last 2 lines.
any button click, last label , button disappear. how correct ?
this old "late binding on functions declared in loop" problem.
w["button"].configure(command = lambda : delete(w["url"], widgets))
on line, command delete(w["url"], widgets)
assumes w
has final value w
had when loop finished, rather value had when called configure
. clicking button deletes last label.
you can compel lambda "bind earlier" passing w default argument.
w["button"].configure(command = lambda w=w: delete(w["url"], widgets))
Comments
Post a Comment