You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在tkinter中实现鼠标绘制单条直线并添加重置功能

Tkinter 单条直线绘制与重置功能实现

完整可运行代码

import tkinter as tk

root = tk.Tk()
root.title("单条直线绘制工具")

canvas = tk.Canvas(width = 600, height = 400, bg="white")
canvas.pack(expand = tk.YES, fill = tk.BOTH)

coords = {"x":0,"y":0,"x2":0,"y2":0}
lines = []
has_drawn = False  # 标记是否已完成单条直线绘制

def click(e):
    global has_drawn
    # 已绘制完成时拦截新的创建请求
    if has_drawn:
        return
    coords["x"] = e.x
    coords["y"] = e.y
    # 创建初始直线并存入列表
    lines.append(canvas.create_line(coords["x"],coords["y"],coords["x"],coords["y"], width=5, fill='red'))

def drag(e):
    # 无直线时不执行操作,避免索引报错
    if not lines:
        return
    coords["x2"] = e.x
    coords["y2"] = e.y
    # 实时更新直线坐标
    canvas.coords(lines[-1], coords["x"],coords["y"],coords["x2"],coords["y2"])

def release(e):
    global has_drawn
    # 鼠标松开后标记绘制完成,禁止创建新直线
    if lines:
        has_drawn = True

def reset_canvas():
    global has_drawn
    canvas.delete("all")  # 清空画布所有元素
    lines.clear()  # 清空直线存储列表
    has_drawn = False  # 重置绘制状态

# 绑定鼠标事件
canvas.bind("<ButtonPress-1>", click)
canvas.bind("<B1-Motion>", drag)
canvas.bind("<ButtonRelease-1>", release)

# 添加重置按钮
reset_btn = tk.Button(root, text="重置画布", command=reset_canvas)
reset_btn.pack(pady=6)

root.mainloop()

关键修改说明

  • 新增has_drawn状态变量,鼠标松开后标记绘制完成,后续点击不会再新建直线
  • 新增重置按钮绑定reset_canvas方法,点击后清空画布、重置状态,支持重新绘制新直线
  • 修复原代码中创建直线代码行的缩进错误,补充边界判断避免空列表索引报错
  • 移除了未使用的PIL导入与无效的itemconfigure、冗余坐标打印代码

内容的提问来源于stack exchange,提问作者Henfry De Los Santos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 06:15:05