ohvonbraun
ohvonbraun

Reputation: 11

tkinter program displays the location of the mouse pointer on the canvas when the mouse is clicked

Trying to get the coordinates of the mouse pointer to display on the canvas where the mouse is. Here is the code. I can get text to display just cannot find the trick to display the coordinates of the mouse itself. Any help would be appreciated.

from tkinter import *                
width = 250
height = 250
class MainGUI:
    def __init__(self):
        window = Tk() 
        window.title("Display Cursor Position")
        self.canvas = Canvas(window, bg = "white", width = width, height = height)
        self.canvas.pack()
        self.canvas.bind("<Button-1>", self.processMouseEvent)
        self.canvas.focus_set()
        window.mainloop()
    def processMouseEvent(self, event):
        self.canvas.create_text(event.x, event.y, text = "event.x, event.y")
        #self.canvas.insert(cursorPoint)
MainGUI()

Upvotes: 1

Views: 1280

Answers (1)

Olav
Olav

Reputation: 576

In this line

self.canvas.create_text(event.x, event.y, text = "event.x, event.y")

the first two arguments tells you where the text is positioned in the canvas. As you want to insert the coordinates of the mouse, you have to convert event.x and event.y into strings (they are ints). So:

def processMouseEvent(self, event):
    mouse_coordinates= str(event.x) + ", " + str(event.y)
    self.canvas.create_text(event.x, event.y, text = mouse_coordinates)

Upvotes: 3

Related Questions