Python Tkinter添加背景图后精灵移动卡顿问题求助
Tkinter Canvas添加背景图后精灵移动卡顿问题
在Mac系统的PyCharm中使用Tkinter的Canvas组件,通过按键绑定实现精灵图像的屏幕移动。添加背景图后,移动速度大幅变慢且卡顿;移除背景图后,移动则流畅如预期。使用Tkinter已有数年,此问题为首次出现,移除背景图移动流畅,重新添加后又变得迟缓。
from tkinter import * window = Tk() # 创建画布 playground = Canvas(window, height=1500, width=1500, bg="green") playground.pack() # 移除这张背景图后,图像移动就流畅顺滑了 bgImg = PhotoImage(file="pacbg.png") bg_Img = bgImg bg = playground.create_image(0, 0, anchor = NW, image=bgImg) # 通过按键绑定移动的图像 pmanImg = PhotoImage(file="pac.png") pman_Img = pmanImg pman = playground.create_image(100, 100, image=pmanImg) # 向右移动图像 def fluidright(event): global rightLoop, leftLoop try: window.after_cancel(leftLoop) playground.move(pman, 10, 0) rightLoop = window.after(10, lambda: fluidright(event)) except NameError: playground.move(pman, 10, 0) rightLoop = window.after(10, lambda: fluidright(event)) # 停止向右移动 def stopright(event): global rightLoop window.after_cancel(rightLoop) # 向左移动图像 def fluidleft(event): global rightLoop, leftLoop try: window.after_cancel(rightLoop) playground.move(pman, -10, 0) leftLoop = window.after(10, lambda: fluidleft(event)) except NameError: playground.move(pman, -10, 0) leftLoop = window.after(10, lambda: fluidleft(event)) # 停止向左移动 def stopleft(event): global leftLoop window.after_cancel(leftLoop) # 按键绑定 playground.bind_all("<Right>", fluidright) playground.bind_all("<Left>", fluidleft) playground.bind_all("<KeyRelease - Right>", stopright) playground.bind_all("<KeyRelease - Left>", stopleft) window.mainloop()
内容的提问来源于stack exchange,提问作者Teach
相关产品推荐
相关产品推荐

