Using screen.onclick() in Turtle with a function that returns multiple values

筅森魡賤 提交于 2021-01-29 07:08:24

问题


I am trying to use the coordinates from a user's mouse click as the x and y for another function. When that second function runs, it returns two values (not x and y).

But when I run the onclick method, I get "TypeError: cannot unpack non-iterable NoneType object" before I even click anything.

def on_click(x, y):
        t = turtle.Turtle()
        screen = turtle.Screen()
        t.penup()
        t.goto(x, y)

        #do stuff part 1
        #do stuff part 2

        return value1, value2

def main():
        t = turtle.Turtle()
        screen = turtle.Screen()
        value1, value2 = screen.onclick(on_click)

        #do other stuff with value1 and value2

main()

Am I using the turtle onclick function incorrectly? Or perhaps setting up my turtle screen wrong?

Else, if I can't return multiple values while using onclick, what would be a work around for getting those two values back into my main function?

Any help would be appreciated!


回答1:


This syntax indicates you are nor thinking about event handlers correctly:

value1, value2 = screen.onclick(on_click)

The screen.onclick() function doesn't return anything (i.e. None) and your on_click() function can't return anything (i.e. None). You are not calling on_click() at this point in the code, it will be called in the future if/when a click occurs, so returning values doesn't apply. (The caller can't use them.)

You've got some choices: you can put (value1, value2) into a global for some other code to access; you can pass it to another function call. But you can't return it. Structurally, your code might look like:

from turtle import Screen, Turtle

def on_click(x, y):
    screen.onclick(None)  # disable handler inside handler

    turtle.goto(x, y)

    # do stuff part 1
    # do stuff part 2

    some_other_function(value1, value2)

    screen.onclick(on_click)  # reenable handler

def some_other_function(v1, v2):
    #  do other stuff with value1 and value2
    pass

screen = Screen()

turtle = Turtle()
turtle.penup()

screen.onclick(on_click)

screen.mainloop()


来源:https://stackoverflow.com/questions/65171391/using-screen-onclick-in-turtle-with-a-function-that-returns-multiple-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!