You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tkinter音乐播放器跑马灯标签动画速度越来越快怎么解决

问题根因

每次切换歌曲调用marquee函数时,既没有终止上一次跑马灯启动的after定时任务,也没有销毁旧的Canvas实例,导致多个shift回调同时执行,每次回调都会让文字左移2像素,叠加后就会出现速度越来越快的现象。

修复方案
  • 新增全局变量存储after任务的ID,方便后续取消未执行的定时回调
  • 每次调用marquee初始化新跑马灯前,先取消上一次的定时任务,销毁旧的Canvas实例
修改后的参考代码
# 新增全局变量存储after任务id
global canvas, fps, after_id
after_id = None

def marquee(song_name,fs) :
    global canvas, fps, after_id
    # 先清理上一次的任务和旧画布
    if after_id is not None:
        canvas.after_cancel(after_id)
        after_id = None
    if 'canvas' in globals() and canvas is not None:
        canvas.destroy()
    # 原有逻辑保持不变
    fps = fs
    canvas=Canvas(Frame1)
    canvas.grid(row=1)
    text_var= song_name
    text=canvas.create_text(0,-2000,text=text_var,font=('calibri',20,'bold'),fill='black',tags=("marquee",),anchor='w')
    x1,y1,x2,y2 = canvas.bbox("marquee")
    width = x2-x1
    height = y2-y1
    canvas['width']='440'
    canvas['height']=height
    shift()

def shift():
    global canvas, fps, after_id
    x1,y1,x2,y2 = canvas.bbox("marquee")
    if(x2<0 or y1<0): 
        x1 = canvas.winfo_width()
        y1 = canvas.winfo_height()//2
        canvas.coords("marquee",x1,y1)
    else:
        canvas.move("marquee", -2, 0)
    # 存储新的after任务id
    after_id = canvas.after(1000//fps,shift)

内容的提问来源于stack exchange,提问作者user13767678

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 06:15:03