Python-阻止乌龟离开画布

时间:2019-03-08 01:48:36

标签: python canvas turtle-graphics

我正在使用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)

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

谢谢

1 个答案:

答案 0 :(得分:0)

问题在于此代码:

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()函数中时,它位于文件的顶层:

CURSOR_OFFSET = 6  # cursor hotspot closer to front than back

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)

def move_forward_keys(_):
    t.forward(9)
    tx, ty = t.position()

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

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

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

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

def move_back_keys(_):
    t.back(9)
    tx, ty = t.position()

    if tx > right_bound - CURSOR_OFFSET or tx < CURSOR_OFFSET + left_bound:
        t.undo()

    if ty > top_bound - CURSOR_OFFSET or ty < CURSOR_OFFSET + bottom_bound:
        t.undo()

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