如何通过在Tkinter上单击,拖动和释放鼠标来制作线条? [英] How do I make lines by clicking, dragging and releasing the mouse on Tkinter?

查看:75
本文介绍了如何通过在Tkinter上单击,拖动和释放鼠标来制作线条?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to complete an exercise that asks me to draw lines in Tkinter but I don't know how I make the same canvas.create_line() receive the coordinates from different functions. I'm kinda stuck here; where and how do I put the 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()

推荐答案

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

I think the easiest way to achieve what you want is to create a line when you click, then change the coordinates while dragging and keep it when you release. If you simply make a new line for every click and update the coordinates on drag, you don't even need the release event:

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

这篇关于如何通过在Tkinter上单击,拖动和释放鼠标来制作线条?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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