python - 如何通过在 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()
解决方案
我认为实现您想要的最简单的方法是在单击时创建一条线,然后在拖动时更改坐标并在释放时保留它。如果您只是为每次单击创建一个新行并在拖动时更新坐标,您甚至不需要释放事件:
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()
推荐阅读
- python - 程序将列表中已通过while循环输入的数字的平方相加
- actionscript-3 - 1084:语法错误:在冒号之前需要右括号
- sql-server - 如何在 SQL Server 数据库项目中删除系统版本控制表
- python - discord.py 中的反应监听器
- maven - gradle 的任何替代 artifactory_contextUrl
- vue.js - 如何使用事件总线在 nuxt js 中的任何组件之间进行通信
- game-development - 通过脚本设置可见性。戈多
- c++ - 使用自定义比较器时如何在 C++ 中执行稳定排序?
- powershell - 合并脚本并更新 csv 文件
- python - 用于计算 groupby 百分比的 Pandas Window 函数