Python如何将Tkinter文本框输入值作为countdown函数参数传入?
问题根因
- 触发
countdown函数时未传递自定义时长参数,程序始终使用默认值10运行 - 原有读取用户输入时长的逻辑被注释,且原位置不合理:如果在递归函数内每次执行都读取输入框值,会覆盖倒计时的递减逻辑,仅需在首次触发倒计时的时候读取一次用户输入即可
修复方案
调整countdown函数的参数逻辑,首次调用无参数传入时,自动读取输入框的时长转换为秒作为初始倒计时值,递归调用时传递递减后的数值即可,同时修正回车绑定逻辑避免直接触发通知。
修正后完整代码
import time from tkinter import * from plyer import notification from tkinter import messagebox def space(): space = Label(text="", bg="darkgreen") space.grid() def countdown(count=None): # 首次调用时读取用户输入的时长 if count is None: if task_box.get() == "" or time_box.get() == "" or not time_box.get().isdigit(): messagebox.showwarning(title="Error", message="Please set task and / or time") return # 分钟转秒 count = 60 * int(time_box.get()) count_label["text"] = count if count > 0: root.after(1000, countdown, count-1) if count == 0: set_notifier() def set_notifier(): notification.notify( title = f"{task_box.get()}", message = "Don't be stupid, just do what I say!", timeout=3 ) root = Tk() # root.iconbitmap("yt.ico") root.title("Notifier") root.geometry("400x400") root.columnconfigure(0, weight=1) root.config(bg="darkgreen") space() space() space() task_label = Label(root, text="Enter task", bg="darkgreen", fg="white", font=("jost", 9, "bold")) task_label.grid() EntryVar = StringVar() task_box = Entry(root, width=27, textvariable=EntryVar) task_box.grid() space() time_label = Label(root, text="Set time (minutes)", bg="darkgreen", fg="white", font=("jost", 9, "bold")) time_label.grid() EntryVar = StringVar() time_box = Entry(root, width=27, textvariable=EntryVar) time_box.grid() space() space() set_btn = Button(width=23, height=1, bg="darkgreen", fg="white", text="Set", font=("jost", 11, "bold"), command=countdown) set_btn.grid() space() count_label = Label(root, text="", bg="darkgreen", fg="white") count_label.grid() space() space() # 修正回车绑定逻辑,触发倒计时而非直接发通知 root.bind('<Return>', lambda e: countdown()) root.mainloop()
内容的提问来源于stack exchange,提问作者Katkoota
相关产品推荐
相关产品推荐

