如何在Python(tkinter)中使用无限循环停止程序?

时间:2019-05-03 10:28:39

标签: python python-3.x multithreading tkinter

我在停止程序时遇到问题。当我单击退出按钮时,主循环停止,但程序仍在运行。我是新手,我不知道该怎么办。我知道问题是线程仍在运行,我不知道如何停止它。

这是我的代码:

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()

1 个答案:

答案 0 :(得分:0)

为退出按钮创建一个函数,该函数也会停止您的线程

def exit():
    switch = False
    root.destroy()

后来:

exit_button = Button(root, text='Exit', command=exit, width=50)

每当用右上方的X按钮关闭窗口时,您也可以调用相同的方法。只需将您的方法绑定到事件即可:

root.protocol("WM_DELETE_WINDOW", exit)

Ps:您无需在此处使用global,因为嵌套函数可以访问外部函数变量