python(GUI thinter) 利用button停止当前运行函数

问题遇到的现象和发生背景

我在写一个带界面的python(GUI)编程的过程中遇到了一个问题,例如:有两个按钮一个是“开始”一个是“停止”。点了开始之后会运行绑定好的函数,为了让这个函数一直循环的跑,我加了个while循环。在点击开始程序已经运行的过程中,我想如果当我要停止下来时,点击“停止”按钮就会终止当前运行的函数。所以我一开始的思路是,在while循环里面加了个条件(while state == True),当我点击停止时使得state = False。但是不行,我点停止的时候它会报一个“未响应”给我。有没有朋友知道该怎么写

以下是部分相关的代码

class Application(Frame):

    def createWidegt(self):
        self.btn04 = Button(self, text='开始投注', command=self.start_betting_for, state='disabled')
        self.btn04.pack(side='left')
        self.btn06 = Button(self, text='立即停止', command=self.stop_now)
        self.btn06.pack(side='left')

    def stop_now(self):
        global state
        state = False

    def start_betting_for(self):
        global cookies
        global account
        global number
        global state

        while state == True:
            for i, j, k in zip(cookies, account, number):
                txt = self.start_betting(i, k)
                if txt == '请求成功':
                    print(f'账户{j}:投注成功')
                else:
                    print(f'账户{j}:{txt}')
            time.sleep(90)
            print('--' * 20)


    def start_betting(self, cookie, number):
        # 投注请求头
        headers_betting = {
            'Host': 'd015.appapi01.com',
            'accept-language': 'zh-CN,zh;q=0.8',
            'user-agent': 'yicai/1.0.10 (Android 9; Xiaomi_MI 8) [com.tfx.yicai_1.0.10_1010]',
            'content-type': 'application/x-www-form-urlencoded; charset=utf-8',
            'content-length': '170',
            'accept-encoding': 'gzip',
            'cookie': cookie,
        }

        data_betting = {
            'oooForce': 'false',
            'text': f'[{{"code": "1972", "compress": "false", "content": "{number},-,-,-,-", "issue":"", "lottery": "hash60ssc", "method": "dw", "methodType": 1, "model": "li", "multiple": 1}}]'
        }

        # 投注接口
        url_betting = 'https://d015.appapi01.com/api/game-lottery/add-order'

        # 发起投注请求
        response_betting = requests.post(url=url_betting, headers=headers_betting, data=data_betting)
        value = json.loads(response_betting.text)  # 将响应数据格式转换
        return value['message']
相关截图

img

img

我想要达到的结果

看看有没有什么办法,先提前谢谢你们了

用定时器来写,把while循环那一段改成下面这样再试试,注意after定时器的单位是毫秒,因为你使用time.sleep暂停了90秒,所以用定时器的话就是90000

if state:
    for i, j, k in zip(cookies, account, number):
        txt = self.start_betting(i, k)
        if txt == '请求成功':
            print(f'账户{j}:投注成功')
        else:
            print(f'账户{j}:{txt}')
    print('--' * 20)
    self.after(90000,self.start_betting_for)

这是因为start_betting_for是一个消息处理函数,它里面的while循环是一个死循环(state=True),从而导致这个消息处理函数一直无法结束返回,消息队列中的其他消息无法得到处理,因此出现界面未响应。
你应该使用一个Timer定时发送timeout消息来触发执行一个函数,在这个函数里执行你需要的操作,但是不能有死循环。
点击开始按钮时,启动定时器,点击停止按钮时,停止定时器。

将state变量定义为类的成员变量呢,并赋初始值为False
当start时,state=True
当stop时,state=False