如何用tkinter在鼠标坐标后画一条线?

要沿着鼠标坐标画一条线,我们需要创建一个函数来捕获每次鼠标点击的坐标,然后在两个连续点之间画一条线。让我们举个例子,看看它是如何做到的。

步骤 -

  • 导入 tkinter 库并创建 tkinter 框架的实例。

  • 使用几何方法设置框架的大小。

  • 创建一个用户定义的方法“draw_line”来捕获每次鼠标点击的 x 和 y 坐标。然后,使用create_line()Canvas 的方法在两个连续点之间画一条线。

  • 将鼠标左键单击与draw_line方法绑定。

  • 最后,运行应用程序窗口的主循环。

示例

# Import the library
import tkinter as tk

# Create an instance of tkinter
win = tk.Tk()

# Window size
win.geometry("700x300")

# Method to draw line between two consecutive points
def draw_line(e):
   x, y = e.x, e.y
   if canvas.old_coords:
      x1, y1 = canvas.old_coords
      canvas.create_line(x, y, x1, y1, width=5)
  canvas.old_coords= x, y

canvas = tk.Canvas(win, width=700, height=300)
canvas.pack()
canvas.old_coords = None

# Bind the left button the mouse.
win.bind('<ButtonPress-1>', draw_line)

win.mainloop()
输出结果

它将跟踪鼠标的左键单击并在每两个连续点之间画一条线。