我目前正在尝试通过使用返回键绑定来更改tkinter标签小部件中的图像。按下返回键后,我希望图像更改为“ im2”,然后等待2秒钟,然后再次更改为“ im3”。到目前为止,我使用的代码是:
window = tk.Tk()
window.title("Testwindow")
window.geometry("800x800")
window.configure(background='grey')
# images
im1_path = "im1.gif"
im2_path = "im2.gif"
im3_path = "im3.gif"
im1 = ImageTk.PhotoImage(Image.open(im1_path))
im2 = ImageTk.PhotoImage(Image.open(im2_path))
im3 = ImageTk.PhotoImage(Image.open(im3_path))
panel = tk.Label(window, image = im1)
panel.pack(side = "bottom", fill = "both", expand = "yes")
def callback(e):
panel.configure(image = im2)
panel.image = im2
time.sleep(2)
panel.configure(image = im3)
panel.image = im3
window.bind("<Return>", callback)
window.mainloop()
Run Code Online (Sandbox Code Playgroud)
但是,不是两次更改图像,而是在按回车键2秒后仅将其更改为“ im3”一次,因此不显示第一个更改。有人知道为什么吗?
time.sleep()在这里不起作用,因为它停止了程序的执行,您将不得不使用after...,而且sleep在GUI编程中使用也是一种不好的做法。
root.after(time_delay, function_to_run, args_of_fun_to_run)
所以在你的情况下
def change_image():
panel.configure(image = im3)
panel.image = im3
Run Code Online (Sandbox Code Playgroud)
并在您的回调函数中
def callback(e):
panel.configure(image = im2)
panel.image = im2
#after 2 seconds it'll call the above function
window.after(2000, change_image)
Run Code Online (Sandbox Code Playgroud)