在python中使用tkinter将图像从左到右无限移动



我正在尝试制作一个GUI,其中图像从左向右移动。但它只从左向右移动了一次。我希望这个图像从左到右移动无限次。移动图像一次的代码是:

from Tkinter import *
root = Tk()
#canvas1.create_image(50, 50, image=photo1)
def next_image(event=None):
    canvas1.move(item, 10, 0)
    canvas1.after(20, next_image)# <--- Use Canvas.move method.


image1 = r"C:Python26Libsite-packagespygameexamplesdatafile.gif"
photo1 = PhotoImage(file=image1)
width1 = photo1.width()
height1 = photo1.height()
canvas1 = Canvas(width=width1, height=height1)
canvas1.pack(expand=1, fill=BOTH) # <--- Make your canvas expandable.
x = (width1)/2.0
y = (height1)/2.0
item = canvas1.create_image(x, y, image=photo1) # <--- Save the return value of the create_* method.
canvas1.bind('<Button-1>', next_image)
root.mainloop() 

解决方案是检查对象是否已移动到右侧边缘,并将其移回左侧:

def next_image(event=None):
    maxwidth = canvas1.winfo_width()
    x0,y0 = canvas1.coords(item)
    if x0 > maxwidth:
        canvas1.coords(item, (0,y0))
    else:
        canvas1.move(item, 10, 0)
    canvas1.after(20, next_image)# <--- Use Canvas.move method.

最新更新