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

如何为Selenium+Tkinter+多线程的Tinder自动滑赞脚本添加停止功能

解决方法

核心问题有两个:

  • code.TinderBot的实例是liker函数内的局部变量,全局无法访问,自然不能调用它的quit()方法
  • 滑赞逻辑运行在独立子线程中,即使关闭浏览器驱动,子线程的执行逻辑还会继续,容易触发报错

修改步骤

1. 新增全局变量存储实例和运行状态

在导入模块的代码下方新增两个全局变量:

import threading
from tkinter import *
import code
import time

# 新增内容开始
bot_instance = None
is_running = False
# 新增内容结束

2. 修改liker函数,关联全局变量并增加运行状态判断

把原来的局部start实例赋值给全局bot_instance,同时把长的time.sleep拆分为短循环,每次判断运行状态,避免停止命令延迟生效:

def liker():
    global bot_instance, is_running
    is_running = True
    new_canvas.itemconfig(loading, text="Loading..Please wait")
    bot_instance = code.TinderBot()
    # 把30秒等待拆成0.5秒一次的循环,随时检测停止信号
    for _ in range(60):
        if not is_running:
            return
        time.sleep(0.5)
    if not is_running:
        return
    bot_instance.log()
    # 同理拆分10秒等待
    for _ in range(20):
        if not is_running:
            return
        time.sleep(0.5)
    if not is_running:
        return
    new_canvas.itemconfig(loading, text="Starting to swipe...")
    bot_instance.swipe()

如果你的code.py里的swipe()方法是循环滑赞的逻辑,也可以给swipe()方法加is_running的判断,每滑动一次就检测一次是否要停止,停止更及时

3. 完善close_window停止函数

在函数内调用机器人的quit()方法关闭Selenium驱动,同时修改运行状态终止子线程逻辑,更新UI提示:

def close_window():
    global bot_instance, is_running
    is_running = False
    if bot_instance is not None:
        try:
            bot_instance.quit()
        except:
            pass
        bot_instance = None
    new_canvas.itemconfig(loading, text="已停止运行,可点击启动重新运行")

额外优化(可选)

可以给启动按钮加状态控制,避免重复点击启动多个子线程:
在new_process开头判断是否已经在运行:

def new_process():
    global is_running
    if is_running:
        new_canvas.itemconfig(loading, text="程序已经在运行中,请勿重复点击")
        return
    threading.Thread(target=liker).start()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 18:06:07