繁体   English   中英

使用 tkinter 和类创建“停止”按钮

[英]Creating "Stop" button using tkinter & classes

我正在编写模拟代码,并且我已按类将模拟和接口分开。 我一直在寻找一个停止按钮来停止我的长模拟代码,但是我创建的界面“没有响应”,直到:

  • 整个模拟停止,或
  • 我收到一个错误,或者
  • 我使用 Spyder“停止命令”停止它*

结构如下:

class interface(tk.Tk):
    def __init__(self):
        super().__init__()
        self.startInterface()

    def startInterface():
        self.title('Simulation')  # Window's title
        self.minsize(450, 180)  # Window's size
        .
        .
        .
        frm_Mediumdown = tk.Frame(self, bd=7, relief='flat')
        frm_Mediumdown.grid(row=3, column=0, padx=0, pady=0)

        BTN_stop = tk.Button(frm_Mediumdown, text='Stop', command = self.stop)
        BTN_stop.grid(row=1, column=2, sticky=tk.W, padx=4)

        BTN_simulate = tk.Button(frm_Mediumdown, text='Simulate', 
                                                    command = self.Simulate)
        BTN_simulate.grid(row=1, column=0, sticky=tk.W, padx=4) 

    def Simulate(self):
        # here this function call another class which start the long simulation code
        Simulation.starts(a, b, etc)
        
    def stop(self):
        # here it should appear the code option to stop the simulation
        


class Simulation():
    # Long code which do the simulation
.
.
.

if __name__ == '__main__':
    print('Start')
    app = interface()
    app.mainloop()

我试图在接口class中的 stop 和Simulate函数 def 中放置一个global选项,但它不起作用,当我启动代码时它有同样的问题。

而且我也尝试了threading选项和daemon thread ,但我没有得到任何回应。

尝试这样做:

def simulate(self):
    simulation = Simulation()
    self.after(1000, simulation.starts, a, b, etc)

然而, starts()方法是否循环运行? 也尝试(不建议)在starts()方法中的某处添加root.update() (root,是你的root(如接口))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM