首页 > 解决方案 > 如何通过在 Tkinter 上单击、拖动和释放鼠标来制作线条?

问题描述

我正在尝试完成一个要求我在 Tkinter 中画线的练习,但我不知道如何让相同的内容canvas.create_line()接收来自不同函数的坐标。我有点卡在这里; 我在哪里以及如何放置create_line

from Tkinter import *


canvas = Canvas(bg="white", width=600, height=400)
canvas.pack()


def click(c):
    cx=c.x
    cy=c.y
def drag(a):
    dx=a.x
    dy=a.y
def release(l):
    rx=l.x
    ry=l.y

canvas.bind('<ButtonPress-1>', click)
canvas.bind('<ButtonRelease-1>', release)
canvas.bind("<B1-Motion>", drag) 

mainloop()

标签: pythontkinterlines

解决方案


我认为实现您想要的最简单的方法是在单击时创建一条线,然后在拖动时更改坐标并在释放时保留它。如果您只是为每次单击创建一个新行并在拖动时更新坐标,您甚至不需要释放事件:

import Tkinter as tk

root = tk.Tk()

canvas = tk.Canvas(root, bg="white", width=600, height=400)
canvas.pack()

coords = {"x":0,"y":0,"x2":0,"y2":0}
# keep a reference to all lines by keeping them in a list 
lines = []

def click(e):
    # define start point for line
    coords["x"] = e.x
    coords["y"] = e.y

    # create a line on this point and store it in the list
    lines.append(canvas.create_line(coords["x"],coords["y"],coords["x"],coords["y"]))

def drag(e):
    # update the coordinates from the event
    coords["x2"] = e.x
    coords["y2"] = e.y

    # Change the coordinates of the last created line to the new coordinates
    canvas.coords(lines[-1], coords["x"],coords["y"],coords["x2"],coords["y2"])

canvas.bind("<ButtonPress-1>", click)
canvas.bind("<B1-Motion>", drag) 

root.mainloop()

推荐阅读