Getting mouse position interms of canvas unit.

Chad Netzer cnetzer at mail.arc.nasa.gov
Mon Apr 28 16:10:38 EDT 2003


On Mon, 2003-04-28 at 08:23, perl lover wrote:
> hi,
>   iam new to python and tkinter. I have created a
> canvas of size 300m * 300m (in millimeter). I bind
> mouse move method to canvas. when i move the mouse
> over the canvas the mouse position gets printed in
> pixel unit. But i want to get mouse position values
> interms of canvas unit (ie, millimeter). How can i get
> mouse position values interms of canvas unit?

Below is a demonstration of the concept, based on your original code. 
It basically finds the screen dimensions in units of pixels and
millimeters, and from that, creates a conversion factor that can be
multiplied to pixel values.


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
from __future__ import division
from Tkinter import *

if __name__ == '__main__':
    root = Tk()

    # get screen width and height in both mm and pixels
    # use values to create factor for converting pixels to mm
    #
    # Note - left as globals for easy demonstration use in callback
    mm_x = root.winfo_screenmmwidth() / root.winfo_screenwidth()
    mm_y = root.winfo_screenmmheight() / root.winfo_screenheight()

    c = Canvas(root, width="300m", height="300m", background = 'gray')
    c.pack()

    # Note - Should change this to use currying rather than globals.
    def mouse_pos_in_mm(event):
        """Report mouse position in canvas coords, units of mm."""
        print c.canvasx(event.x) * mm_x, c.canvasy(event.y) * mm_y

    c.bind('<Motion>', mouse_pos_in_mm)

    c.create_rectangle('16m','10.5m','21m','15.5m',fill='blue')

    root.mainloop()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

-- 

Chad Netzer
(any opinion expressed is my own and not NASA's or my employer's)






More information about the Python-list mailing list