Reputation: 29
My problem with my code is that I want to update my list during the delay and make the label appear twice with different values. I want b to appear first and then d will appear later. But it seems that only d is displayed now. Is there any ways that I can go around it? Any help is much appreciated!
import Tkinter as tk
a_list=["a","b","c"]
root=tk.Tk()
variableone=tk.StringVar()
label1=tk.Label(root,text="appear later")
label1.pack()
label=tk.Label(root, textvariable=variableone)
label.after(2000, lambda:variableone.set(a_list[1]))
label.pack()
a_list[1]="d"
label.after(5000, lambda:variableone.set(a_list[1]))
root.mainloop()
Upvotes: 0
Views: 300
Reputation: 55469
Your problem is due to your lambda
s using the current value of a_list[1]
when they're called, not the value it had when thelambda
s were created. You can get around that by giving them a default argument, since that's only evaluated at creation time.
This is a common problem when using lambda
s as callback functions. See Python Tkinter, setting up button callback functions with a loop for a similar problem using lambda
s to set up a series of Button widgets in a loop.
This code does what you want. It uses s
as the default argument to hold the value of a_list[1]
.
import Tkinter as tk
a_list=["a","b","c"]
root=tk.Tk()
variableone=tk.StringVar()
label1=tk.Label(root,text="appear later")
label1.pack()
label=tk.Label(root, textvariable=variableone)
label.after(2000, lambda s=a_list[1]:variableone.set(s))
label.pack()
a_list[1]="d"
label.after(5000, lambda s=a_list[1]:variableone.set(s))
root.mainloop()
Upvotes: 2