[英]Why does my object move in the wrong direction
我制作了一个简单的程序,旨在在画布内左右移动球。 用户将使用向左和向右键一次相应地将球移动5个像素。 如果球的x坐标小于40或大于240,则它将什么都不做。
try:
import tkinter as tk
except ImportError:
import Tkinter as Tk
window = tk.Tk()
game_area = tk.Canvas(width=270, height=400, bd=0, highlightthickness=0,
bg="white")
ball = game_area.create_oval(10, 10, 24, 24, fill="red")
game_area.move(ball, 120, 4)
coords = 120
def move_left(event):
global coords
if coords < 40:
pass
else:
coords = int(coords)- 5
game_area.move(ball, coords, 4)
game_area.update()
def move_right(event):
global coords
if coords > 240:
pass
else:
coords = int(coords)+5
game_area.move(ball, coords, 4)
game_area.update()
window.bind("<Left>", move_left)
window.bind("<Right>", move_right)
game_area.pack()
window.mainloop()
但是,尽管有if
功能,按任意一个键都可以使球向右移动(跨度超过5个像素)并离开屏幕。
根据Tkinter Canvas文档 , move
方法的第二个参数dx
是偏移量。 尝试像这样称呼它
game_area.move(ball, -5, 4)
然后,您也不需要以下行。
coords = int(coords)- 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.