python canvas.find_overlapping似乎具有反转的y轴

时间:2018-10-10 22:05:35

标签: python pixel turtle-graphics tkinter-canvas

我正在尝试在Python乌龟下找到画布的颜色。我使用了canvas.find_overlapping,但是只有当我否定ycor时,它才会成功,这意味着与显示的对象相比,y轴在画布对象中是倒置的。我的代码有问题还是y轴倒置了?

import turtle

wn = turtle.Screen()

maze_drawer = turtle.Turtle()
maze_drawer.color("purple")
maze_drawer.speed("fastest")
path_width = 15 

def get_pixel_color(x, y):
    c = turtle.Screen().getcanvas()
    # -y should not work??
    items = c.find_overlapping(x, -y, x, -y)
    if len(items) > 0:
        return c.itemcget(items[0], "fill") # get 0 object (canvas)

# draw simplified maze
wall_len = 0
for i in range(10): 
    maze_drawer.left(90)
    wall_len += path_width
    maze_drawer.forward(wall_len)

# navigate maze from center
maze_runner = turtle.Turtle()
maze_runner.color("green")
maze_runner.penup()
maze_runner.goto(-path_width, -path_width)
# test in y dir: maze_runner.setheading(90)

clear = True
while(clear):
    maze_runner.forward(1)
    color_at_turtle = get_pixel_color(maze_runner.xcor(), maze_runner.ycor())
    if (color_at_turtle == "purple"): 
        clear = False

wn.exitonclick()

1 个答案:

答案 0 :(得分:0)

整齐地使用乌龟内部的tkinter像素检测!如果倒置的Y坐标很麻烦,则可以从乌龟的角度翻转它:

from turtle import Screen, Turtle

screen = Screen()
width, height = screen.window_width() / 2, screen.window_height() / 2
screen.setworldcoordinates(-width, height, width, -height)  # flip Y coordinate

然后,只要您知道颠倒了,您的代码就不必考虑否定Y:

from turtle import Screen, Turtle

PATH_WIDTH = 15

def get_pixel_color(x, y):
    canvas = screen.getcanvas()
    items = canvas.find_overlapping(x, y, x, y)

    if items:
        return canvas.itemcget(items[0], "fill")  # get 0 object (canvas)

    return None

screen = Screen()
width, height = screen.window_width() / 2, screen.window_height() / 2
screen.setworldcoordinates(-width, height, width, -height)

maze_drawer = Turtle(visible=False)
maze_drawer.color("purple")
maze_drawer.speed("fastest")

# draw simplified maze
wall_len = 0

for _ in range(20):
    maze_drawer.left(90)
    wall_len += PATH_WIDTH
    maze_drawer.forward(wall_len)

# navigate maze from center
maze_runner = Turtle()
maze_runner.color("dark green", "green")
maze_runner.penup()
maze_runner.goto(-PATH_WIDTH, -PATH_WIDTH)

def run_maze():
    maze_runner.forward(1)

    x, y = maze_runner.position()
    color_at_turtle = get_pixel_color(x, y)

    if color_at_turtle == "purple":
        maze_runner.backward(PATH_WIDTH - 1)
        maze_runner.left(90)
        x, y = maze_runner.position()

    if -width < x < width and -height < y < height:
        screen.ontimer(run_maze, 10)

run_maze()

screen.exitonclick()