从func返回2个值

时间:2016-02-13 23:17:22

标签: python tkinter

任何人都知道为什么以下代码会生成错误??

我调用func来获取鼠标坐标:

def button_click(event):
    x, y = event.x, event.y
    print('{}, {}'.format(x, y))
    return x, y

然后我想将结果分配给main中的新变量:

x_cord, y_cord = app_root.bind('<ButtonRelease-1>', button_click)

通过这样做我得到以下错误:

"x_cord, y_cord = app_root.bind('<ButtonRelease-1>', button_click)
ValueError: too many values to unpack"

任何人都知道为什么会这样?谢谢大家!

2 个答案:

答案 0 :(得分:1)

假设您使用Tkinterbind()只会将事件绑定到您的button_click回调并返回事件标识符。引自bind() docstring:

  

Bind将返回一个标识符,以允许删除绑定函数   没有内存泄漏的unbind。

您不能指望bind()返回button_click()事件处理程序返回的内容。

答案 1 :(得分:-2)

这是不好的做法,但您可以将变量范围声明为global以在其他地方访问它们:

def button_click(event):

    global x, y

    x = event.x
    y = event.y