使用 Tkinter 在 python 中移动图像 [英] Move an image in python using Tkinter
问题描述
伙计们,我正在编写需要使用 Tkinter(canvas) 在 python 中移动图像的代码这给我制造了问题.图像正在显示,但没有移动.
Guys I am working on a code which needs to move an image in python using Tkinter(canvas) This is creating problems for me. The image is being displayed but it is not moving.
from Tkinter import *
root = Tk()
root.title("Click me!")
def next_image(event):
global toggle_flag
global x, y, photo1
# display photo2, move to right, y stays same
canvas1.create_image(x+10, y, image=photo1)
canvas1.create_image(x+20, y, image=photo1)
canvas1.create_image(x+30, y, image=photo1)
canvas1.create_image(x+40, y, image=photo1)
canvas1.create_image(x+50, y, image=photo1)
canvas1.create_image(x+60, y, image=photo1)
canvas1.create_image(x+70, y, image=photo1)
canvas1.create_image(x+100, y, image=photo1)
image1 = "C:\Python26\Lib\site-packages\pygame\examples\data\ADN_animation.gif" #use some random gif
photo1 = PhotoImage(file=image1)
# make canvas the size of image1/photo1
width1 = photo1.width()
height1 = photo1.height()
canvas1 = Canvas(width=width1, height=height1)
canvas1.pack()
# display photo1, x, y is center (anchor=CENTER is default)
x = (width1)/2.0
y = (height1)/2.0
canvas1.create_image(x, y, image=photo1)
canvas1.bind('<Button-1>', next_image) # bind left mouse click
root.mainloop()
推荐答案
Canvas 提供 move
方法.参数是要移动的项目,相对于前一个位置的 x 偏移量,y 偏移量.
Canvas provides move
method. Arguments are item you want to move, relative x offset from the previous position, y offset.
您需要保存create_image
的返回值以将其传递给move
方法.
You need to save the return value of the create_image
to pass it to the move
method.
还要确保画布是可展开的(pack(expand=1, fill=BOTH)
在下面的代码中)
Also make sure the canvas is expandable (pack(expand=1, fill=BOTH)
in the following code)
from Tkinter import *
root = Tk()
def next_image(event):
canvas1.move(item, 10, 0) # <--- Use Canvas.move method.
image1 = r"C:\Python26\Lib\site-packages\pygame\examples\data\ADN_animation.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()
<小时>
根据评论更新
使用after
,您可以安排在给定时间后调用的函数.
Using after
, you can schedule the function to be called after given time.
def next_image(event=None):
canvas1.move(item, 10, 0)
canvas1.after(100, next_image) # Call this function after 100 ms.
这篇关于使用 Tkinter 在 python 中移动图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!