我创建了一个条目小部件,当它们单击OK时它会输入输入的数字(这将成为函数重复的秒数(n)),我想每隔n秒调用一次该函数。单击确定后,我想在屏幕上显示一个按钮,该按钮将停止该功能重复出现。我怎么能这样做?
这就是我所拥有的:
def ok_func():
global stop
stop = 1
timer_pop.destroy()
seconds = seconds_entry.get()
seconds = int(seconds)
stop_timer.grid()
while stop == 1:
stop_timer.config(highlightbackground=mycolor)
background()
time.sleep(seconds)
这就是我用于停止计时器按钮的内容:
def stopTimer():
global stop
stop = 0
stop_timer.grid_forget()
由于 编辑:
global counter
counter = 0
def ok_func():
global stop_timer
print('function: "ok" is running now.')
global counter
counter += 1
def stopTimer():
global recur
stop_timer.destroy()
timer_pop.after_cancel(recur)
try:
if counter == 1:
global time
time = int(seconds_entry.get())
timer_pop.destroy()
stop_timer = Button(app, text="Stop Timer", command=stopTimer)
stop_timer.grid(row=0, column=6, padx=10)
#stop_timer.config(highlightbackground=ok_func)
global recur
print ('function will start again in', time, 'seconds')
recur = app.after(1000*time, background)
else:
print ('function will start again in', time, 'seconds')
recur = app.after(1000*time, background)
#stop_timer.config(highlightbackground=mycolor)
except ValueError:
counter = 0
print("thats not a number")
我尝试了你说的但仍然没有工作。颜色只改变一次,然后停止。此外,我想停止按钮改变背景背景,但它不起作用。谢谢你的帮助。
答案 0 :(得分:1)
这是一个完整的例子,可以满足您的需求(我认为。)
创建了一个重复出现的函数,你可以选择再次出现的频率,然后你可以按下按钮来杀死它(使用after_cancel
,这样程序仍会运行,但不会做任何事情。)。
from tkinter import *
root = Tk()
global counter
counter = 0
def ok():
print('function: "ok" is running now.')
global counter
counter += 1
def stop():
global recur
label.destroy()
stop_button.destroy()
root.after_cancel(recur)
try:
if counter == 1:
global time
time = int(entry.get())
label.config(text = 'your only option now is to stop the function')
entry.destroy()
ok_button.destroy()
stop_button = Button(text = 'stop', command = stop)
stop_button.pack()
global recur
print ('function will start again in', time, 'seconds')
recur = root.after(1000*time, ok)
else:
print ('function will start again in', time, 'seconds')
recur = root.after(1000*time, ok)
except ValueError:
counter = 0
print('thats not a number')
label = Label(root, text = 'pick a number of seconds for the function to recur in')
label.pack()
entry = Entry(root)
entry.pack()
ok_button = Button(root, text = 'Ok', command = ok)
ok_button.pack()
root.title('cool recurring function')
root.mainloop()
希望这就是你想要的,如果不是大喊(告诉我你想要的是什么)!