簡體   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