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

Python Tkinter鼠标左键长按仅触发一次问题求助

解决Tkinter按钮长按持续触发函数的问题

要实现鼠标长按按钮期间持续调用Dataprint函数,你需要结合按钮的按下、释放事件以及Tkinter的after方法来实现循环调用,避免阻塞UI线程。以下是修改后的完整代码:

import tkinter as tk
from tkinter import ttk
import socket

# 全局变量跟踪按钮状态和after任务ID
is_pressing = False
after_id = None

def Dataprint():
    UDP_IP_ADDRESS_SERVER = "xxx.xxx.xx.xxx"
    UDP_PORT_SERVER = 7005
    message = "#upto"
    client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    client.sendto(message.encode('utf-8'), (UDP_IP_ADDRESS_SERVER, UDP_PORT_SERVER))
    print("sent")
    client.close()

def start_printing(event):
    global is_pressing, after_id
    is_pressing = True
    Dataprint()
    # 每隔10ms重复调用,可根据需求调整间隔
    after_id = root.after(10, repeat_printing)

def repeat_printing():
    global is_pressing, after_id
    if is_pressing:
        Dataprint()
        after_id = root.after(10, repeat_printing)

def stop_printing(event):
    global is_pressing, after_id
    is_pressing = False
    if after_id:
        root.after_cancel(after_id)
        after_id = None

# 基础窗口框架(适配原代码中的TAB2)
root = tk.Tk()
TAB2 = ttk.Frame(root)
TAB2.pack(padx=10, pady=10)

ttk.Label(TAB2, text="bos",font=("Arial",20),foreground="#fff",borderwidth=2,background="#7b7bc0",width=9).grid(column=0, row=4, padx=10, pady=10)
emptyup=ttk.Button(TAB2,text="up")
emptyup.grid(column=0, row=5, padx=10, pady=10)
# 绑定按下和释放事件
emptyup.bind("<ButtonPress-1>", start_printing)
emptyup.bind("<ButtonRelease-1>", stop_printing)

root.mainloop()

关键修改说明:

  • 移除Dataprint中的time.sleep(0.01):Tkinter是单线程模型,sleep会阻塞整个UI导致无响应,改用after实现定时调用。
  • 添加is_pressing标志:跟踪按钮是否处于长按状态,控制循环的启停。
  • 使用after和after_cancel:after安排下一次函数调用,after_cancel在按钮释放时取消未执行的任务,避免函数继续运行。
  • 绑定<ButtonPress-1>和<ButtonRelease-1>事件:分别对应长按开始和停止的触发时机。

你可以根据需求调整after方法中的时间间隔(示例为10ms),间隔越小触发频率越高。另外,每次调用Dataprint都创建新socket的做法,可优化为复用一个socket对象以减少资源消耗。

内容的提问来源于stack exchange,提问作者Seçkin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 01:15:56