sossexy
sossexy

Reputation: 29

Working with time delay and list in tkinter

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

Answers (1)

PM 2Ring
PM 2Ring

Reputation: 55469

Your problem is due to your lambdas using the current value of a_list[1] when they're called, not the value it had when thelambdas 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 lambdas as callback functions. See Python Tkinter, setting up button callback functions with a loop for a similar problem using lambdas 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

Related Questions