天天看点

Python Tkinter界面应用开发-04 开始和结束

上节课,我们的界面已经搭好了,我们注意到,这里的按钮没有任何命令,那么这节课,我们来为这2个按钮添加命令的处理。所以,当他们被点击时,我们给他们创建一个命令函数,因此,当start按钮被点击时,我们需要创建一个新的函数来响应,当stop按钮被点击时,我们需要另一个函数来响应,所以我们来到类的底部。定义一个启动计时器的函数,我们想做的第一件事就是确保:每次启动我们计时器时,计时器能够设置回全长。所以我们需要重新把它设置回DEFAULT_GAP。

timer.grid(row = 1, column = 0, sticky ='nsew')
 
    def start_timer(self):        self.time_left.set(DEFAULT_GAP)      

接下来,我们要创建一个变量,来记录计时器是否正在运行,所以在init函数中,我们添加一个新的变量self.running,并且它的初始值为false:

self.time_left.set(DEFAULT_GAP)
        self.running = False      

因为当我们的应用程序启动时,定时器还没有运行。但是,当我们回到start_timer函数,我们希望running现在等于true,因为计时开始了.所以running等于true。

def start_timer(self):
self.time_left.set(DEFAULT_GAP)
        self.running = True      

那么现在,回到我们创建的start按钮的地方,在这里,我们添加按钮命令的调用,这里command将等于self.start_timer.

self.start_button = tkinter.Button(
build_frame,text = 'start',
            command = self.start_timer
)      

这里我们不需要括号,因为当按钮被点击时,它就会调用这个函数,好的,这就是我们现在的开始按钮。

同样地,让我们继续添加停止按钮的命令响应:

self.stop_button = tkinter.Button(
build_frame,text='stop',
            command = self.stop_timer
)      

然后在类的底部定义stop_timer函数,我们希望stop_timer设置self.running等于False,因为当我们按下stop按钮时,这时候应该停止计时:

def stop_timer(self):        self.running = False      

所以这就是我们要做的。

这里我们运行看看效果。我点击开始,我点击停止。什么事情都没有发生,这是因为我们也没做什么事情。但是这个命令函数确实执行了。

那么,实际上,这些按钮有它们自己的状态,你可以选择禁用它。我们希望当计时器还没有开始运行时,stop按钮被禁用,当计时器运行时,start按钮被禁用,对吧。所以,让我们回到创建按钮的的函数中。我们要确保stop按钮是默认禁用的:

self.start_button.grid(row = 0, column = 0, sticky = 'ew')
self.stop_button.grid(row=0, column=1, sticky='ew')
        self.stop_button.config(state = tkinter.DISABLED)      

因为程序开始运行时,计时器还没有开始计时,这时候stop按钮应该被禁用,对吗?运行下,你看,stop按钮被禁用了:

那么,同样的道理。当我们点击开始时,我们希望恢复stop按钮,这个时候,start按钮也应该被禁用。

def start_timer(self):
self.time_left.set(DEFAULT_GAP)self.running = True
        self.stop_button.config(state = tkinter.NORMAL)        self.start_button.config(state=tkinter.DISABLED)      

紧接着,把这两行复制,然后粘贴到他们stop按钮的事件中。这里和start按钮的事件应该恰好相反:

def stop_timer(self):
self.running = False
        self.stop_button.config(state = tkinter.DISABLED)        self.start_button.config(state=tkinter.NORMAL)      

继续阅读