事件发生后如何返回鼠标位置的值



它在单击后获得鼠标位置,但是我无法返回x和y值以在其他功能中使用。例如下面的代码,它是第一次打印,但对第二印刷品无能为力。我认为X0,Y0没有返回,它们仍然是本地变量。

from tkinter import *
root = Tk()
w = Canvas(root, width=1000, height=640)
w.pack()
def getorigin(eventorigin):
    global x0, y0
    x0 = eventorigin.x
    y0 = eventorigin.y
    print(x0, y0)
    return x0, y0
w.bind("<Button 1>",getorigin)
print(x0, y0)

您无法从分配给事件的函数返回(或在command=bind()after()中使用(。您只能分配给全局变量,然后在其他功能中使用。

mainloop()显示窗口之前执行bind()后您的print(),它不是"其他函数"。

我使用两个功能:一个函数:一个在按下左鼠标按钮时获得值,第二次在按下右鼠标按钮时使用这些值。第二个功能使用第一个功能的值。它表明,第一个函数的值分配给全局变量。

from tkinter import *
# --- functions ---
def getorigin(event):
    global x0, y0 # inform function to assing to global variables instead of local variables
    x0 = event.x
    y0 = event.y
    print('getorigin:', x0, y0)
def other_function(event):
    #global x0, y0 # this function doesn't assign to variables so it doesn't need `global`
    print('other function', x0, y0)
# --- main ---
# create global variables 
x0 = 0  
y0 = 0
root = Tk()
w = Canvas(root, width=1000, height=640)
w.pack()
w.bind("<Button-1>", getorigin)
w.bind("<Button-3>", other_function)
print('before mainloop:', x0, y0) # executed before mainloop shows window
root.mainloop()

最新更新