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

Tkinter中WebSocket客户端重连报错:Thread can only be started once

解决WebSocket客户端重连时的"Thread can only be started once"错误

错误原因

你当前的代码在初始化按钮时,只创建了一个线程实例,并把它的start方法绑定为按钮的点击命令。线程对象一旦启动过就无法再次调用start(),所以第二次点击按钮时就会触发这个错误。

修复方案

让按钮每次被点击时,新建一个线程实例并启动,而不是复用同一个线程。只需要修改按钮的command绑定逻辑:

修改后的代码

async def start_client(url, duration):
    async with websockets.connect(url) as ws:
        start_time = time.time()
        while time.time() - start_time < duration:
            message = await ws.recv()
            msg = json.loads(message)
            print(msg)

            if 'timestamp android.sensor.accelerometer' in msg:
                write_acc(msg)
            else:
                write_gyro(msg)

def on_click():
    initial_setup_files()
    asyncio.run(start_client(url, 4))
    final_csv_file_creator()
    print("Disconnected from the server")

# 修改按钮的command绑定,每次点击新建线程
btn = Button(window,
             text="Start Server ",
             fg="black",
             bg="cyan",
             font=("Times New Roman", 30, 'bold'),
             # 用lambda包装,每次点击都创建新线程并启动
             command=lambda: threading.Thread(target=on_click).start()
             )
btn.pack(padx=20,
         pady=20)

额外优化建议

为了避免用户重复点击按钮创建过多线程,可以在连接过程中禁用按钮,连接结束后再启用:

def on_click():
    # 点击后禁用按钮
    btn.config(state=DISABLED)
    initial_setup_files()
    asyncio.run(start_client(url, 4))
    final_csv_file_creator()
    print("Disconnected from the server")
    # 连接结束后恢复按钮状态
    btn.config(state=NORMAL)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 20:07:06