Tkinter如何实现PNG图片间隔数秒切换位置的动态移动效果
问题根因
- 你原有代码中两个
ventana.after(5000, ...)是同时启动计时的,不会等待前一个任务执行完成再启动下一个,同时ima2和ima3是同步立即创建的,自然会同时显示 - Canvas上绘制的图片元素不属于标准Tkinter控件,不能用
destroy()方法销毁,需要调用canvas.delete()方法删除
修复方案
我们可以先定义好图片移动的坐标序列,通过递归调用after方法按顺序切换图片位置,实现间隔移动的效果,修改后的可运行代码如下:
import tkinter as tk def texto(): link=tk.StringVar() no=tk.Label(ventana,text="Hay algo en el camino...",font=("Times",18,"bold"),anchor='n',width=24, height=3,bg="#137420", fg="#9AD51A",bd=25,relief = "ridge") no.place(x=430,y = 400,anchor ='center') caja = tk.Entry(ventana,textvariable=link,width=50,state="readonly") caja.place(x=430,y = 410,anchor ='center') lin="https://www.tumblr.com/blog/mundo000011" link.set(lin) def saliendo(): canvas.delete(ima) # 定义图片移动的坐标序列,可自行增减调整 move_points = [(247,780), (247,500)] # 间隔时间,单位毫秒 interval = 5000 current_img = None def move_step(index): nonlocal current_img # 删除上一个位置的图片 if current_img is not None: canvas.delete(current_img) # 所有坐标遍历完成后执行后续逻辑 if index >= len(move_points): texto() return # 显示当前位置的图片 x, y = move_points[index] current_img = canvas.create_image(x, y, image=myimg) # 间隔指定时间后执行下一次移动 ventana.after(interval, move_step, index + 1) # 开始第一次移动 move_step(0) def salir(): # 这里补上你原有变量trad和leta的定义即可正常运行原有判断逻辑 saliendo() ventana=tk.Tk() ventana.title("Bosque") ventana.geometry('900x800') ventana.resizable(0,0) # 补上原有代码缺失的canvas定义 canvas = tk.Canvas(ventana, width=900, height=800, bg="white") canvas.pack() myimg = tk.PhotoImage(file='circlo.png') posx=70 posy=235 ima = canvas.create_image(78,235,image=myimg) boton2 = tk.Button(text=" Ir ",font=("Verdana",16), command=salir) boton2.config(bg="#135C3F", fg="#D7D731") boton2.place(x=746,y=379) ventana.mainloop()
调整说明
- 你可以修改
move_points列表的坐标值,添加更多位置实现更长的移动路径 - 修改
interval变量的数值可以调整每次位置切换的间隔时间,单位为毫秒
内容的提问来源于stack exchange,提问作者Leandro
相关产品推荐
相关产品推荐

