wxpython类中不能停止while循环

创建了一个wx.Frame,面板有两个按钮,点击"start"按钮后文本不断显示随机数,可是点击“stop”按钮后却不能停止循环,不知道代码哪里出问题,请各位指点,感谢!

import wx
import random
import time
n=0
b=False
class MyFrame(wx.Frame):
    def __init__(self):
        super().__init__(None,title='random',size=(300,300),pos=(100,100))
        panel=wx.Panel(parent=self)
        self.st1=wx.StaticText(parent=panel,label='0',pos=(100,50))
        self.st2=wx.StaticText(parent=panel,label='0',pos=(130,50))
        self.b1=wx.Button(parent=panel,id=1,label='start',pos=(50,100))
        self.b2=wx.Button(parent=panel,id=2,label='stop',pos=(150,100))
        #self.Bind(wx.EVT_BUTTON,self.on_click,id=1,id2=10)
        self.b1.Bind(wx.EVT_BUTTON,self.startBtn)
        self.b2.Bind(wx.EVT_BUTTON,self.stopBtn)


    def stopBtn(self,event):
        b=False
        
    def startBtn(self,event):
        b=True
        global n
        while b:
            n=random.randint(1,10)
            self.st1.SetLabelText(str(n))
            time.sleep(0.5)



if __name__=="__main__":
    app=wx.App()
    frm=MyFrame()
    frm.Show()
    app.MainLoop()
            

该回答引用ChatGPT

在你的代码中,stopBtn()方法中的变量b只是一个局部变量,并不是startBtn()中定义的全局变量b。因此,当你在stopBtn()中修改b的值时,并不会影响到startBtn()中的b变量。因此,即使你在stopBtn()中将b设置为False,startBtn()方法中的while循环仍然会继续执行。

为了解决这个问题,你可以在MyFrame类中定义一个成员变量,来保存循环是否应该继续的状态。然后,在startBtn()和stopBtn()方法中分别修改这个成员变量。具体来说,你可以将你的代码修改为如下形式:


import wx
import random
import time


class MyFrame(wx.Frame):
    def __init__(self):
        super().__init__(None, title='random', size=(300, 300), pos=(100, 100))
        self.panel = wx.Panel(parent=self)
        self.st1 = wx.StaticText(parent=self.panel, label='0', pos=(100, 50))
        self.st2 = wx.StaticText(parent=self.panel, label='0', pos=(130, 50))
        self.b1 = wx.Button(parent=self.panel, id=1, label='start', pos=(50, 100))
        self.b2 = wx.Button(parent=self.panel, id=2, label='stop', pos=(150, 100))
        self.is_running = False
        self.b1.Bind(wx.EVT_BUTTON, self.startBtn)
        self.b2.Bind(wx.EVT_BUTTON, self.stopBtn)

    def stopBtn(self, event):
        self.is_running = False

    def startBtn(self, event):
        self.is_running = True
        while self.is_running:
            n = random.randint(1, 10)
            self.st1.SetLabelText(str(n))
            time.sleep(0.5)


if __name__ == "__main__":
    app = wx.App()
    frm = MyFrame()
    frm.Show()
    app.MainLoop()

在修改后的代码中,我们在MyFrame类的__init__()方法中添加了一个成员变量self.is_running,用于表示当前循环是否应该继续。在startBtn()方法中,我们将这个成员变量设置为True,并在while循环中判断它的值。在stopBtn()方法中,我们将这个成员变量设置为False,从而停止循环。

不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^