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

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-01 08:23:46

问题


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, y = event.x, event.y
    x1 = (x+1)
    y1 = (y+1)
    canvas.create_line(x, y, x1, y1)
    sleep(0.5)



root = tk.Tk()

canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()

root.bind('d', myfunction)


root.mainloop()

Understandably, the program only draws a point when I press 'd'. I have tried using loops within the myfunction function like this:

def myfunction(event):
    x, y = event.x, event.y
    x1 = (x+1)
    y1 = (y+1)
    for x in range(0,5):
        canvas.create_line(x, y, x1, y1)
        sleep(0.1)

but this does not work. I have tried many other solutions but none seem to work.

Is there a solution to this problem?


回答1:


First, you have to bind to the "<Motion>" 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('<Motion>', myfunction)
root.mainloop()



回答2:


Based on Novel's answer you can further define the function to work when the left mouse button is pressed only, and further, define a function for drawing lines:

import tkinter as tk

def draw(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

def draw_line(event):

    if str(event.type) == 'ButtonPress':
        canvas.old_coords = event.x, event.y

    elif str(event.type) == 'ButtonRelease':
        x, y = event.x, event.y
        x1, y1 = canvas.old_coords
        canvas.create_line(x, y, x1, y1)

def reset_coords(event):
    canvas.old_coords = None

root = tk.Tk()

canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()
canvas.old_coords = None

root.bind('<ButtonPress-1>', draw_line)
root.bind('<ButtonRelease-1>', draw_line)

#root.bind('<B1-Motion>', draw)
#root.bind('<ButtonRelease-1>', reset_coords)

root.mainloop()


来源:https://stackoverflow.com/questions/47996285/how-to-draw-a-line-following-your-mouse-coordinates-with-tkinter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!