在 Turtle 中使用 screen.onclick() 和返回多个值的函数 [英] Using screen.onclick() in Turtle with a function that returns multiple values
问题描述
我试图将用户鼠标点击的坐标用作另一个函数的 x 和 y.当第二个函数运行时,它返回两个值(不是 x 和 y).
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).
但是当我运行 onclick 方法时,我得到TypeError: cannot unpack non-iterable NoneType object";在我点击任何东西之前.
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()
我是否错误地使用了海龟的 onclick 函数?或者我的龟屏设置错误?
Am I using the turtle onclick function incorrectly? Or perhaps setting up my turtle screen wrong?
否则,如果我在使用 onclick 时无法返回多个值,有什么办法可以让这两个值返回到我的主函数中?
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?
任何帮助将不胜感激!
推荐答案
此语法表明您没有正确考虑事件处理程序:
This syntax indicates you are nor thinking about event handlers correctly:
value1, value2 = screen.onclick(on_click)
screen.onclick()
函数不返回任何东西(即None
)和你的on_click()code> 函数不能返回任何东西(即
None
).此时您没有在代码中调用 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.)
您有一些选择:您可以将 (value1, value2)
放入 global 以供其他代码访问;您可以将其传递给另一个函数调用.但是你不能返回它.在结构上,您的代码可能如下所示:
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()
这篇关于在 Turtle 中使用 screen.onclick() 和返回多个值的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!