编写一个函数来结束程序?

时间:2015-03-29 00:44:23

标签: python tkinter

如何保存设置闹钟时返回的闹钟的引用,然后取消闹钟?我需要一个停止功能,以便用户可以结束程序。

p = ' IDKMYBFFJILL!'
k = 0

def new_char():
    global k
    label.config(text=p[k])
    k = (k+1)%len(p)
    window.after(500,new_char)

def end():
    window.after.cancel(new_char)

from Tkinter import *

window=Tk()
window.title('New char program')

label = Label(window,text='',width=2,font=('Times New Roman',200))
label.grid()

begin_button = Button(window,text='begin',command=new_char)
begin_button.grid(row=1,column=1,sticky='EW')

end_button = Button(window,text='end',command=end)
end_button.grid(row=1,column=2,sticky='EW')

window.mainloop()

2 个答案:

答案 0 :(得分:1)

您必须捕获alarm()的输出,这是一个“警报标识符”,然后您可以将其传递给alarm_cancel(),即alarm_cancel(<alarm_identifier>)。 (注意:语法为alarm_cancel(),带有下划线 - 而非alarm.cancel(),就像您尝试的那样)

执行此操作的一种方法是将警报功能封装在一个类中,我称之为Alarm

from Tkinter import *

p = ' IDKMYBFFJILL!'
k = 0

# Create Alarm class
class Alarm(object):
    def __init__(self):
        self.alarm_id = None

    def new_char(self):
        global k
        label.config(text=p[k])
        k = (k+1)%len(p)
        self.alarm_id = window.after(500,self.new_char)

    def end(self):
        window.after_cancel(self.alarm_id)

# Create Alarm instance (called alarm)
alarm = Alarm()

window=Tk()
window.title('New char program')

label = Label(window,text='',width=2,font=('Times New Roman',200))
label.grid()

begin_button = Button(window,text='begin',command=alarm.new_char)  # Note change
begin_button.grid(row=1,column=1,sticky='EW')

end_button = Button(window,text='end',command=alarm.end)           # Note change
end_button.grid(row=1,column=2,sticky='EW')

window.mainloop()

您可以更进一步,将pk移到Alarm类中,无需global - 但无需解决问题。

答案 1 :(得分:1)

您可以设置停止标志,以指示何时停止以及循环停止后要执行的操作:

from Tkinter import *


p = ' IDKMYBFFJILL!'
k = 0

stop_loop = False # the stop flag set when cancel is pressed

def new_char():
    global k

    if stop_loop: # execute this when you press cancel
        print("K value when cancel was stopped: ", k)
        return

    label.config(text=p[k])
    k = (k+1)%len(p)
    window.after(500,new_char)

def end():
    global stop_loop
    stop_loop = True # set the flag that you want to stop (done when pressed cancel button)