如何使用 tkinter 根据鼠标坐标绘制一条线? [英] How to draw a line following your mouse coordinates with tkinter?

查看:40
本文介绍了如何使用 tkinter 根据鼠标坐标绘制一条线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用以下代码绘制在 tkinter 中创建一条线的点:

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

可以理解,当我按d"时,程序只会绘制一个点.我尝试在 myfunction 函数中使用循环,如下所示:

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?

推荐答案

首先,您必须绑定到 "" 事件,它会在每次鼠标移动时触发.

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.

像这样:

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

这篇关于如何使用 tkinter 根据鼠标坐标绘制一条线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆