Как сделать линии, щелкая, перетаскивая и отпуская мышь на Tkinter? - PullRequest
0 голосов
/ 02 мая 2018

Я пытаюсь выполнить упражнение, которое просит меня нарисовать линии в 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()

Ответы [ 2 ]

0 голосов
/ 02 мая 2018

Я думаю, что самый простой способ достичь желаемого - создать линию при нажатии, затем изменить координаты при перетаскивании и сохранить ее при отпускании. Если вы просто создаете новую строку для каждого клика и обновляете координаты при перетаскивании, вам даже не нужно событие выпуска:

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()
0 голосов
/ 02 мая 2018

Очень простое решение:

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