How to draw a line following your mouse coordinates with tkinter?

前端 未结 2 1688
野趣味
野趣味 2021-01-14 05:54

I have tried using the following code to draw points that create a line in tkinter:

import tkinter as tk
from time import sleep

def myfunction(event):
    x         


        
2条回答
  •  失恋的感觉
    2021-01-14 06:28

    First, you have to bind to the "" event, which will fire every time the mouse moves.

    Then you need to save the previous mouse coordinates so that you have a place to draw the line from.

    Like this:

    import tkinter as tk
    
    def myfunction(event):
        x, y = event.x, event.y
        if canvas.old_coords:
            x1, y1 = canvas.old_coords
            canvas.create_line(x, y, x1, y1)
        canvas.old_coords = x, y
    
    root = tk.Tk()
    
    canvas = tk.Canvas(root, width=400, height=400)
    canvas.pack()
    canvas.old_coords = None
    
    root.bind('', myfunction)
    root.mainloop()
    

提交回复
热议问题