简体   繁体   中英

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"*

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.

And I've also tried the threading option and the daemon thread , but I didn't get any response.

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? also try (not suggested) adding root.update() somewhere in the starts() method (root, is whatever is Your root (like interface))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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