I would like to learn how to track the mouse movement in a tkinter app that I am designing. I have managed to put together the following code following the example of this question, the output of which is the coordinates of my mouse as it moves through the grid:
import tkinter as tk
class MyGUI(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        # define variables
        GRID = 25
        X = GRID*20
        Y = GRID*15
        wid = 15
        hei = 25
        # create canvas
        self.canvas = tk.Canvas(width=X+1, height=Y+1, background='white',
                                highlightthickness=1, highlightbackground='black')
        self.canvas.pack()
        # create grid
        for i in range(0, Y, GRID):
            self.canvas.create_line(0, i, X, i, fill='gray')
        for i in range(0, X, GRID):
            self.canvas.create_line(i, 0, i, Y, fill='gray')
        # get mouse position
        self.mouse_pos = (0, 0)
        self.bind('<Motion>', self.motion)
    def motion(self, event):
        """Get mouse position"""
        self.mouse_pos = event.x, event.y
        print('{}, {}'.format(event.x, event.y))
if __name__ == "__main__":
    app = tk.Tk()
    app.title('hi')
    MyGUI(app).pack()
    app.mainloop()
However, when I run the code and hover the mouse over the grid, I am not getting anything (no errors and no output). I have played around and managed to change the last few lines 29-39 of the code in the following manner
    # get mouse position
    def motion(event):
        """Get mouse position"""
        x, y = event.x, event.y
        print('{}, {}'.format(event.x, event.y))
    app.bind('<Motion>', motion)
which is included within the class. This seems to work, however I suspect this might be a bad practice or something, if anything it looks significantly different that the example I linked to above and I try to understand why this case works whilst my first attempt doesn't. Thanks for your help in advance.
 
     
    