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

2024-10-04 05:27:08 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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:\Python26\Lib\site-packages\pygame\examples\data\file.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() 

Tags: 图像imagemovecreaterootitemmethodfile
1条回答
网友
1楼 · 发布于 2024-10-04 05:27:08

解决方案是检查对象是否已离开右边缘,然后将其移回左侧:

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.

相关问题 更多 >