我只是稍微修改了你的代码。我添加了一个线程来运行calculate方法,因此它不会阻塞主线程。在import wx
import time
import threading
class Test(wx.Frame):
def __init__(self, title):
super().__init__(None, title=title)
self.panel = wx.Panel(self)
self.initUI()
self.Centre()
def initUI(self):
vbox = wx.BoxSizer(wx.VERTICAL)
button1 = wx.Button(self.panel, label="START Calculation")
button1.Bind(wx.EVT_BUTTON, self.start_test)
button2 = wx.Button(self.panel, label="STOP Calculation")
button2.Bind(wx.EVT_BUTTON, self.stop_test)
vbox.Add(button1, 0, wx.ALL, 5)
vbox.Add(button2, 0, wx.ALL, 5)
self.panel.SetSizer(vbox)
self.stop = False
def create_thread(self, target):
thread = threading.Thread(target=target)
thread.daemon = True
thread.start()
def calculate(self):
for i in range(20000):
if self.stop:
break
print("Program is running...")
time.sleep(5)
self.stop = False
def start_test(self, e):
self.create_thread(self.calculate)
def stop_test(self, e):
print("The calculation has been stopped!")
self.stop = True
if __name__ == '__main__':
app = wx.App()
Test("A large program").Show()
app.MainLoop()
如果自动停止是真的,它从foor循环中跳出。这样,您就可以开始和停止计算,只需单击两个按钮。在