简体   繁体   English

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

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

I am working on a simulation code, and I had separated by classes the simulation and the interface.我正在编写模拟代码,并且我已按类将模拟和接口分开。 I was looking for a stop button to stop my long simulation code, but the interface I have created "Is not responding" until:我一直在寻找一个停止按钮来停止我的长模拟代码,但是我创建的界面“没有响应”,直到:

  • the whole simulation stops, or整个模拟停止,或
  • I get an error, or我收到一个错误,或者
  • I stop it using Spyder "stop command"*我使用 Spyder“停止命令”停止它*

The structure is the following:结构如下:

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

I have tried to put a global option in the stop and Simulate functions def inside the interface class , but it doesn't work, it has the same problem when I launch the code.我试图在接口class中的 stop 和Simulate函数 def 中放置一个global选项,但它不起作用,当我启动代码时它有同样的问题。

And I've also tried the threading option and the daemon thread , but I didn't get any response.而且我也尝试了threading选项和daemon thread ,但我没有得到任何回应。

try doing this instead:尝试这样做:

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

however does the starts() method run in loop?然而, starts()方法是否循环运行? also try (not suggested) adding root.update() somewhere in the starts() method (root, is whatever is Your root (like interface))也尝试(不建议)在starts()方法中的某处添加root.update() (root,是你的root(如接口))

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

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