单击鼠标时,tkinter程序显示鼠标指针在画布上的位置

时间:2013-10-22 22:22:31

标签: python-3.x tkinter

尝试获取鼠标指针的坐标以显示在鼠标所在的画布上。这是代码。我可以得到文本显示只是找不到显示鼠标本身坐标的技巧。 任何帮助将不胜感激。

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

1 个答案:

答案 0 :(得分:2)

在这一行

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

前两个参数告诉您文本在画布中的位置。如果要插入鼠标的坐标,则必须将event.x和event.y转换为字符串(它们是整数)。所以:

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