如何在func之外使用onscreenclick(func)事件的值?

时间:2019-04-04 01:21:24

标签: python turtle-graphics

使用Turtle,我希望能够创建一个包含用户单击的屏幕位置的变量。

我发现可以使用以下代码来打印点击的位置:

import turtle

def find_click_pos(x, y):
    print('{0}, {1}'.format(x, y))

def main():
    turtle.onscreenclick(find_click_pos)

main()

turtle.mainloop()

此问题是x, y坐标仅在find_click_pos函数中定义,据我所知,不使用全局变量就无法在函数的其他位置使用它们(我想不惜一切代价避免)。

有什么方法可以将.onscreenclick()的值发送给函数吗? turtle是否还有其他功能可以满足我想要的功能?

2 个答案:

答案 0 :(得分:2)

您传递给onscreenclick的回调函数可以使用其调用的xy值来完成所需的操作。尚不清楚您要做什么,但是很难想象您找不到在函数中执行此操作的方法。

如果您担心如何在不使用全局变量的情况下传递值,则最好的方法可能是使回调成为类中的方法,以便它可以分配其他方法可以轻松读取的属性:

import turtle

class Foo:
    def __init__(self):
        self.click_x = 0  # initialize with dummy values
        self.click_y = 0
        turtle.ontimer(self.other_method, 1000)

    def click_cb(self, x, y):
        self.click_x = x
        self.click_y = y

    def other_method(self):
        print(self.click_x, self.click_y)
        turtle.ontimer(self.other_method, 1000)

foo = Foo()
turtle.onscreenclick(foo.click_cb)

turtle.mainloop()

答案 1 :(得分:0)

这似乎是错误的做法。我喜欢@Blckknght的基于对象的解决方案(+1),但是您只需将包含对象实例的全局变量替换为包含位置的全局变量。 >

如果您确实想做错事,并且避免使用全局变量,那么您也可能会以错误的方式进行操作-而且,比危险的默认值更错误的是:

import turtle

def get_click_position(x=None, y=None, stash=[0, 0]):  # dangerous default value
    if x != None != y:
        stash[0:] = (x, y)

    return turtle.Vec2D(*stash)

def print_click_position():
    x, y = get_click_position()
    print('{0}, {1}'.format(x, y))

    turtle.ontimer(print_click_position, 1000)

turtle.onscreenclick(get_click_position)
print_click_position()

turtle.mainloop()

如果您想知道最后一次点击是什么,请不带任何参数调用get_click_position()。它将一直返回该结果,直到出现新的单击为止,这时将调用get_click_position()作为带有参数的事件处理程序。

相关问题