【问题标题】:How to stop a program with infinity loop in Python (tkinter)?如何在 Python(tkinter)中停止具有无限循环的程序?
【发布时间】: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,因为switchmain() 中的局部变量,而不是全局变量。

标签: python python-3.x multithreading tkinter


【解决方案1】:

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

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,因为你的嵌套函数可以访问外部函数变量

【讨论】:

  • 它的工作方式相同。 Mainloop 已停止,但脚本仍在运行。我需要单击 PyCharm 中的停止按钮来停止脚本。
  • @ArturOwczarek 我认为您所看到的是 PyCharm 正在停止解释器而不是脚本。你试过quit()吗?
猜你喜欢
  • 2013-11-19
  • 2015-02-07
  • 1970-01-01
  • 1970-01-01
  • 2023-01-13
  • 1970-01-01
  • 2018-11-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多