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

2024-09-29 23:19:06 发布

您现在位置:Python中文网/ 问答频道 /正文

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

  • 整个模拟停止,或者
  • 我出错了,或者
  • 我使用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,但没有得到任何回应


Tags: the代码selfdefcolumntkclassgrid
1条回答
网友
1楼 · 发布于 2024-09-29 23:19:06

尝试这样做:

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

但是starts()方法是否在循环中运行?还可以尝试(不建议)在starts()方法中的某处添加root.update()(root,是您的根(比如接口))的任何部分

相关问题 更多 >

    热门问题