如何让Python Tkinter消息框显示脚本其他位置的点击计数数值
修复后的可运行代码
import time from tkinter import * from tkinter import messagebox f = ("Arial",24) root = Tk() root.title("点击计数器") root.config(bg='#345') root.state('zoomed') #窗口最大化打开,无需设置Geometry参数 count = 0 def clicked(): global count count = count + 1 myLabel.configure(text=f'按钮已被点击 {count} 次!') hour=StringVar() minute=StringVar() second=StringVar() hour.set("00") minute.set("00") second.set("10") hour_tf= Entry( root, width=3, font=f, textvariable=hour ) hour_tf.place(x=80,y=20) mins_tf= Entry( root, width=3, font=f, textvariable=minute) mins_tf.place(x=130,y=20) sec_tf = Entry( root, width=3, font=f, textvariable=second) sec_tf .place(x=180,y=20) TheButton = Button(root, height= 30, width=100, bg="light blue", text="点击我", command=clicked) TheButton.pack() myLabel = Label(root) myLabel.pack() def startCountdown(): global count # 重置计数,仅统计本次倒计时时段内的点击次数 count = 0 # 倒计时运行时禁用启动按钮,避免重复触发 start_btn.config(state=DISABLED) try: userinput = int(hour.get())*3600 + int(minute.get())*60 + int(second.get()) except: messagebox.showwarning('', '输入无效,请输入数字!') start_btn.config(state=NORMAL) return while userinput >-1: mins,secs = divmod(userinput,60) hours=0 if mins >60: hours, mins = divmod(mins, 60) hour.set("{0:2d}".format(hours)) minute.set("{0:2d}".format(mins)) second.set("{0:2d}".format(secs)) root.update() time.sleep(1) if (userinput == 0): # 使用f-string格式化字符串,插入count变量 messagebox.showinfo("时间到!", f"本次倒计时内你一共点击了 {count} 次") userinput -= 1 # 倒计时结束后恢复启动按钮 start_btn.config(state=NORMAL) start_btn = Button( root, text='开始倒计时', bd='5', command= startCountdown ) start_btn.place(x = 120,y = 120) root.mainloop()
修改说明
- 解决全局变量调用报错问题:在
startCountdown函数开头添加global count声明,标识该函数内使用的count是全局变量,避免局部变量未定义的运行时错误 - 修复消息框不显示真实点击数的问题:将原固定字符串改为f-string格式,正确读取全局count变量的值并展示
- 新增单次计数逻辑:每次启动倒计时时重置count变量为0,保证统计的是当前倒计时时段内的点击次数
- 新增按钮状态控制:倒计时运行时禁用启动按钮,避免用户多次点击触发多个倒计时线程导致计数混乱
内容的提问来源于stack exchange,提问作者Andy Robertson
相关产品推荐
相关产品推荐

