You could set up a callback to react to <Motion> events:
import Tkinter as tk
root = tk.Tk()
def motion(event):
x, y = event.x, event.y
print('{}, {}'.format(x, y))
root.bind('<Motion>', motion)
root.mainloop()
I'm not sure what kind of variable you want. Above, I set local variables x and y to the mouse coordinates.
If you make motion a class method, then you could set instance attributes self.x and self.y to the mouse coordinates, which could then be accessible from other class methods.
You could set up a callback to react to <Motion> events:
import Tkinter as tk
root = tk.Tk()
def motion(event):
x, y = event.x, event.y
print('{}, {}'.format(x, y))
root.bind('<Motion>', motion)
root.mainloop()
I'm not sure what kind of variable you want. Above, I set local variables x and y to the mouse coordinates.
If you make motion a class method, then you could set instance attributes self.x and self.y to the mouse coordinates, which could then be accessible from other class methods.
At any point in time you can use the method winfo_pointerx and winfo_pointery to get the x,y coordinates relative to the root window. To convert that to absolute screen coordinates you can get the winfo_pointerx or winfo_pointery, and from that subtract the respective winfo_rootx or winfo_rooty
For example:
root = tk.Tk()
...
x = root.winfo_pointerx()
y = root.winfo_pointery()
abs_coord_x = root.winfo_pointerx() - root.winfo_rootx()
abs_coord_y = root.winfo_pointery() - root.winfo_rooty()
python - How to show live mouse position on tkinter window - Stack Overflow
python - Tkinter get mouse coordinates on click and use them as variables - Stack Overflow
python - How do I get mouse position relative to the parent widget in tkinter? - Stack Overflow
How do I determine if the mouse is over canvas objects (images, rectangles, etc.)?
Videos
Hey guys
Uni assignment here. I have to write a class that gets the cursor position and I have absolutely no idea where to start. I'm tearing my hair out because every god damn google link is purple and I've gotten nowhere.
I only know how to input things through the keyboard. How on Earth can I make it take information from the mouse? Everything I've ever done has had some sort of input either through IDLE or in the .py file.
Cheers
This will only update the Label when the mouse is inside the tkinter window:
No need to use win32api, tkinter has it built in. We can bind a function to root's <Motion> key and use the given positional argument event to retrieve the coordinates of the mouse.
from tkinter import Tk, Label
root = Tk()
label = Label(root)
label.pack()
root.bind("<Motion>", lambda event: label.configure(text=f"{event.x}, {event.y}"))
root.mainloop()
You can use after() to periodically get the mouse coordinates and update the label.
Below is an example:
import tkinter as tk
import win32api
root = tk.Tk()
mousecords = tk.Label(root)
mousecords.place(x=0, y=0)
def show_mouse_pos():
x, y = win32api.GetCursorPos()
#x, y = mousecords.winfo_pointerxy() # you can also use tkinter to get the mouse coords
mousecords.config(text=f'x : {x}, y : {y}')
mousecords.after(50, show_mouse_pos) # call again 50ms later
show_mouse_pos() # start the update task
root.mainloop()
If what I said in my previous comment is what you're trying to do, since tkinter doesn't pause the program to wait for a mouse click event you will have to do this: it rebinds it every time the mouse button get clicked
from tkinter import *
from tkinter.filedialog import askopenfilename
from PIL import Image, ImageTk
import tkinter.simpledialog
root = Tk()
#setting up a tkinter canvas
w = Canvas(root, width=1000, height=1000)
w.pack()
#adding the image
File = askopenfilename(parent=root, initialdir="./",title='Select an image')
original = Image.open(File)
original = original.resize((1000,1000)) #resize image
img = ImageTk.PhotoImage(original)
w.create_image(0, 0, image=img, anchor="nw")
#ask for pressure and temperature extent
xmt = tkinter.simpledialog.askfloat("Temperature", "degrees in x-axis")
ymp = tkinter.simpledialog.askfloat("Pressure", "bars in y-axis")
#ask for real PT values at origin
xc = tkinter.simpledialog.askfloat("Temperature", "Temperature at origin")
yc = tkinter.simpledialog.askfloat("Pressure", "Pressure at origin")
#instruction on 3 point selection to define grid
tkinter.messagebox.showinfo("Instructions", "Click: \n"
"1) Origin \n"
"2) Temperature end \n"
"3) Pressure end")
# From here on I have no idea how to get it to work...
# Determine the origin by clicking
def getorigin(eventorigin):
global x0,y0
x0 = eventorigin.x
y0 = eventorigin.y
print(x0,y0)
w.bind("<Button 1>",getextentx)
#mouseclick event
w.bind("<Button 1>",getorigin)
# Determine the extent of the figure in the x direction (Temperature)
def getextentx(eventextentx):
global xe
xe = eventextentx.x
print(xe)
w.bind("<Button 1>",getextenty)
# Determine the extent of the figure in the y direction (Pressure)
def getextenty(eventextenty):
global ye
ye = eventextenty.y
print(ye)
tkinter.messagebox.showinfo("Grid", "Grid is set. You can start picking coordinates.")
w.bind("<Button 1>",printcoords)
#Coordinate transformation into Pressure-Temperature space
def printcoords(event):
xmpx = xe-x0
xm = xmt/xmpx
ympx = ye-y0
ym = -ymp/ympx
#coordinate transformation
newx = (event.x-x0)*(xm)+xc
newy = (event.y-y0)*(ym)+yc
#outputting x and y coords to console
print (newx,newy)
root.mainloop()
The easiest way is to set x, y to global, class or not doesn't matter. I didn't see your full code because I can't open zip files on my phone. So here's what I can help with your example
import tkinter as tk
def getorigin(eventorigin):
global x,y
x = eventorigin.x
y = eventorigin.y
print(x,y)
root = tk.Tk()
root.bind("<Button 1>",getorigin)
Generally speaking you should never need to "get" this information because it is given to you as part of the event object that is passed in. You probably only need this information when responding to an event, and the event gives you this information.
Put more succinctly, to get the information you simply have to retrieve it from the event object.
Here's an example:
import Tkinter
class App:
def __init__(self, root):
f = Tkinter.Frame(width=100, height=100, background="bisque")
f.pack(padx=100, pady=100)
f.bind("<1>", self.OnMouseDown)
def OnMouseDown(self, event):
print "frame coordinates: %s/%s" % (event.x, event.y)
print "root coordinates: %s/%s" % (event.x_root, event.y_root)
root=Tkinter.Tk()
app = App(root)
root.mainloop()
Get the screen coordinates of the mouse move event (x/y_root) and subtract the screen coordinates of the window (window.winfo_rootx()/y()).