gpt4 book ai didi

python - 在一定时间后调用函数并在按下按钮时终止,tkinter

转载 作者:太空宇宙 更新时间:2023-11-03 18:10:05 25 4
gpt4 key购买 nike

我制作了一个条目小部件,当单击“确定”时,它会获取输入的数字(这将成为函数重复执行的秒数(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")

你说的我都试过了,还是不行。颜色只改变一次,然后停止。另外,我希望停止计时器按钮可以随背景更改背景,但它不起作用。感谢您的帮助。

最佳答案

这是一个完整的示例,它可以实现您想要的功能(我认为)。

创建了一个重复函数,您可以选择它重复的频率,然后您可以通过按下按钮来终止它(使用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()

希望这就是你想要的,如果没有大喊大叫(并告诉我你想要什么)!

关于python - 在一定时间后调用函数并在按下按钮时终止,tkinter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26152426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com