【发布时间】:2019-05-03 10:28:39
【问题描述】:
我在停止程序时遇到问题。当我单击退出按钮时,主循环停止但程序仍在运行。我是新手,我不知道该怎么做。我知道问题是线程仍在运行,我不知道如何停止它。
这是我的代码:
from tkinter import *
import simulation as s
import graph as g
import numpy as np
from tkinter import filedialog
import threading
def main():
root = Tk()
root.title("Simulator")
switch = True
def get_filename():
return filedialog.askopenfilename(parent=root)
def play():
def run():
while switch:
s.simulation(s.particle, np.inf, s.initial_time_step, get_filename())
thread = threading.Thread(target=run)
thread.start()
def start_simulation():
global switch
switch = True
v.set('Simulation is running!')
play()
def stop_simulation():
global switch
v.set('Simulation is stopped!')
switch = False
def draw_graphs():
g.create_graphs()
start = Button(root, text='Start simulation', command=start_simulation, width=50)
start.pack()
finish = Button(root, text='Stop simulation', command=stop_simulation, width=50)
finish.pack()
graphs = Button(root, text='Graphs', command=draw_graphs, width=50)
graphs.pack()
exit_button = Button(root, text='Exit', command=root.destroy, width=50)
exit_button.pack()
v = StringVar()
statement = Label(root, textvariable=v)
statement.pack()
root.mainloop()
if __name__ == '__main__':
main()
【问题讨论】:
-
您可以在销毁主窗口之前调用
stop_simulation()。或者将线程设置为守护模式。 -
守护模式有效,谢谢!
-
您应该将所有
global switch更改为nonlocal switch,因为switch是main()中的局部变量,而不是全局变量。
标签: python python-3.x multithreading tkinter