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

如何在Python的Tkinter中绑定鼠标持续按压事件?

解决Tkinter按住鼠标持续绘图的问题

你现在用的<Button-1>绑定只会在鼠标按下的瞬间触发一次,不会持续响应按住的状态。要实现按住鼠标时持续绘图,分两种常见场景给你解决方案:

场景1:按住鼠标拖动时连续画线(最常用的绘图逻辑)

这种情况用<B1-Motion>事件配合状态标记即可,它会在按住左键拖动鼠标时持续触发。同时需要跟踪鼠标按下状态和上一次的坐标,用来连接连续的线条:

import tkinter as tk

root = tk.Tk()
root.title("简易绘图")

# 记录鼠标状态与上一次绘图坐标
is_drawing = False
last_x, last_y = 0, 0

def on_mouse_down(event):
    global is_drawing, last_x, last_y
    is_drawing = True
    # 记录按下瞬间的坐标
    last_x, last_y = event.x, event.y

def on_mouse_drag(event):
    global is_drawing, last_x, last_y
    if is_drawing:
        # 从上一坐标到当前坐标绘制直线
        my_canvas.create_line(last_x, last_y, event.x, event.y, width=2)
        # 更新坐标为当前位置,准备下一段线条
        last_x, last_y = event.x, event.y

def on_mouse_up(event):
    global is_drawing
    # 松开鼠标后停止绘图
    is_drawing = False

my_canvas = tk.Canvas(root, width=960, height=540, bg="white")
my_canvas.pack()

# 绑定三个核心事件
my_canvas.bind('<Button-1>', on_mouse_down)
my_canvas.bind('<B1-Motion>', on_mouse_drag)
my_canvas.bind('<ButtonRelease-1>', on_mouse_up)

root.mainloop()

场景2:按住鼠标即使不拖动,也持续执行绘图动作(比如持续画点)

如果需要按住鼠标不动也持续生成图形,就得用after()方法定时调用绘图函数,直到鼠标松开:

import tkinter as tk

root = tk.Tk()
root.title("持续画点")

is_pressing = False
draw_interval = 50  # 每隔50毫秒画一个点,数值越小速度越快

def draw_point(event=None):
    if is_pressing:
        # 获取鼠标在画布内的坐标
        x = my_canvas.winfo_pointerx() - my_canvas.winfo_rootx()
        y = my_canvas.winfo_pointery() - my_canvas.winfo_rooty()
        # 画一个小圆形作为点
        my_canvas.create_oval(x-2, y-2, x+2, y+2, fill="black")
        # 定时调用自身,实现持续绘图
        my_canvas.after(draw_interval, draw_point)

def on_mouse_down(event):
    global is_pressing
    is_pressing = True
    draw_point()

def on_mouse_up(event):
    global is_pressing
    is_pressing = False

my_canvas = tk.Canvas(root, width=960, height=540, bg="white")
my_canvas.pack()

my_canvas.bind('<Button-1>', on_mouse_down)
my_canvas.bind('<ButtonRelease-1>', on_mouse_up)

root.mainloop()

两种方案按需选择,第一种是绘图软件的常规逻辑,第二种适合需要持续生成图形的场景。

内容的提问来源于stack exchange,提问作者r3d570n3

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 10:30:08