如何通过在Tkinter上单击,拖动和释放鼠标来制作线条?

时间:2018-05-02 03:29:15

标签: python tkinter lines

我正在尝试完成一个练习,要求我在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()

3 个答案:

答案 0 :(得分:1)

我认为实现所需内容的最简单方法是在单击时创建一条线,然后在拖动时更改坐标并在发布时保留它。 如果您只需为每次点击换一个新行并更新拖动时的坐标,那么您甚至不需要发布活动:

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

答案 1 :(得分:0)

非常简单的解决方案:

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

store = {'x':0,"y":0,"x2":0,"y2":0} #store values in a map  x,y:start   x2,y2:end  

def click(c):
    store['x'] = c.x
    store['y'] = c.y

def release(l):
    store['x2'] = l.x
    store['y2'] = l.y
    draw() # Release the mouse and draw

def draw():
    canvas.create_line(store['x'],store['y'],store['x2'],store['y2'])

canvas.bind('<ButtonPress-1>', click)
canvas.bind('<ButtonRelease-1>', release)

mainloop()

答案 2 :(得分:0)

在此解决方案中,您将能够绘制线条并获取其坐标

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}
final=[]
lines = []
def click(e):
    coords["x"] = e.x
    coords["y"] = e.y
    lines.append(canvas.create_line(coords["x"],coords["y"],coords["x"],coords["y"]))

def release(l):
    lis=[]
    lis.append(coords["x"]);lis.append(coords["y"]);lis.append(coords["x2"]);lis.append(coords["x2"])
    final.append(lis)

def drag(e):
    coords["x2"] = e.x
    coords["y2"] = e.y
    canvas.coords(lines[-1], coords["x"],coords["y"],coords["x2"],coords["y2"])

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