Python阻止乌龟离开画布

2024-04-19 19:19:52 发布

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

我正在用tkinter制作一个程序。我有一张帆布和一只乌龟。目前,海龟使用箭头键在屏幕上移动,但是我希望它不能离开画布的边界。这是我当前的代码

canvas = Tk.Canvas(master=self, width=300, height=300)
canvas.grid(row=2, column=2, columnspan=3, padx=50)

canvas.focus_set()

t = turtle.RawTurtle(canvas)
t.setheading(90)

left_bound = -(canvas.winfo_width() / 2)
right_bound = canvas.winfo_width() / 2
top_bound = canvas.winfo_height() / 2
bottom_bound = -(canvas.winfo_height() / 2)

tx = t.xcor()
ty = t.ycor()

if tx > right_bound or tx < left_bound:
    t.undo()
if ty > top_bound or ty < bottom_bound:
    t.undo()

def move_forward_keys(_):
   t.forward(10)

def move_left_keys(_):
   t.left(20)

def move_right_keys(_):
   t.right(20)

def move_back_keys(_):
   t.back(10)

canvas.bind("<Up>", move_forward_keys)
canvas.bind("<Left>", move_left_keys)
canvas.bind("<Right>", move_right_keys)
canvas.bind("<Down>", move_back_keys)

可能是因为我做错了什么,但这是我目前的代码。我认为它应该起作用,因为如果它离开了,它应该撤销它最后的行动。在

谢谢


Tags: rightmovebinddefbackkeyswidthleft
1条回答
网友
1楼 · 发布于 2024-04-19 19:19:52

问题是这个代码:

tx = t.xcor()
ty = t.ycor()

if tx > right_bound or tx < left_bound:
    t.undo()
if ty > top_bound or ty < bottom_bound:
    t.undo()

当它应该嵌入到move_forward_keys()move_back_keys()函数中时,它位于文件的顶层:

^{pr2}$

相关问题 更多 >