获取TypeError比较Python turtle事件处理程序中的坐标

时间:2018-02-15 18:22:07

标签: python string int turtle-graphics

我无法弄清楚如何将x和y转换为来自字符串的整数

import turtle
t = turtle.Turtle()
s = turtle.Screen()
t.penup()
t.speed(0)

def draw_grid():
    count = 0
    distance = 0
    while count < 5:
        t.goto(0, distance)
        for i in range(5):
            t.dot()
            t.fd(100)
        count += 1
        distance += 100
draw_grid()


def get_mouse_click_coor(x, y):

这里发生了什么事?我不确定,并继续给我这个错误:

TypeError:'&lt;' 'int'和'str'

的实例之间不支持
    X = int(x)
    Y = int(y)
    if -20 < X < 20 and 380 > Y > 20:
        t.penup()
        if 80 > Y > 20:
            t.goto(0,0)
            t.pendown()
            t.goto(0,100)
        if 180 > Y > 120:
            t.goto(0, 100)
            t.pendown()
            t.goto(0, 200)
        if 280 > Y > 220:
            t.goto(0, 200)
            t.pendown()
            t.goto(0, 300)
        if 380 > Y > 320:
            t.goto(0, 300)
            t.pendown()
            t.goto(0, 400)

turtle.onscreenclick(get_mouse_click_coor)

s.mainloop()
s.done()

1 个答案:

答案 0 :(得分:0)

(&#34;属性错误:&#39; _Screen&#39;对象没有属性&#39;完成&#39;&#34;关闭窗口时出错)您的代码按预期工作系统(Apple OS X)无需修改。下面是我对代码的样式和效率的修改,看看它是否适合你:

from turtle import Turtle, Screen

def draw_grid():
    for distance in range(0, 500, 100):
        turtle.goto(0, distance)

        for _ in range(5):
            turtle.dot()
            turtle.fd(100)

def get_mouse_click_coor(x, y):

    if -20 < x < 20 and 20 < y < 380:

        turtle.penup()

        if 20 < y < 80:
            turtle.goto(0, 0)
            turtle.pendown()
            turtle.goto(0, 100)
        elif 120 < y < 180:
            turtle.goto(0, 100)
            turtle.pendown()
            turtle.goto(0, 200)
        elif 220 < y < 280:
            turtle.goto(0, 200)
            turtle.pendown()
            turtle.goto(0, 300)
        elif 320 < y < 380:
            turtle.goto(0, 300)
            turtle.pendown()
            turtle.goto(0, 400)

screen = Screen()

turtle = Turtle()
turtle.penup()
turtle.speed('fastest')

draw_grid()

screen.onscreenclick(get_mouse_click_coor)

screen.mainloop()

您不需要mainloop()done(),因为它们是相同的(别名。)