Pei Li
Pei Li

Reputation: 53

How to return value of mouse position after event

It gets your mouse position after clicks, but I can't return the X and Y value to use in other functions. Such as the codes below, it prints at the first time, but do nothing with the second print. I think x0, y0 are not returned and they are still local variables.

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)

Upvotes: 2

Views: 740

Answers (1)

furas
furas

Reputation: 143187

You can't return from function assigned to event (or used in command=, bind() or after()). You can only assign to global variable and later use in other function.

Your print() after bind() is executed before mainloop() shows window and it is NOT "other function".

I use two functions: one to get values when left mouse button is pressed, and second to use these values when right mouse button is pressed. Second function uses values from first function. It shows that value from first function are assigned to global variables.

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()

Upvotes: 2

Related Questions