ExceptGY 2021-10-27 07:52 采纳率: 75%
浏览 44
已结题

python按键执行倒计时小程序不能实现要求,要怎么改才好?


import keyboard #Using module keyboard
import time
from tkinter import *  # 导入图形界面库
#import tkinter.messagebox  # 对话框

win = Tk()  # 注册窗口
win.wm_attributes('-topmost', 1)  # 窗口置顶

win.geometry("240x100+1100+0")  # 设置窗口大小和位置

win.title("离告辞还有:")  # 窗口标题

win.resizable(width=False, height=False)  # 锁定窗口大小

分钟 = 0  # 初始化分钟
秒数 = 5  # 初始化秒钟

#程序退出函数
def quit():
    #tkinter.messagebox.showerror(title="下去吧您嘞", message="十分已至 , 圆润爬开")
    win.quit()
    win.destroy()
    exit()

# 主循环函数
def turn():
    # 声明分钟和秒数是全局变量
    global 分钟
    global 秒数

    秒数 -= 1  # 秒数自减

    if 秒数 < 0:  # 秒数减到小于0时重新赋值为59,同时使分钟数减一
        秒数 = 0
        分钟 -= 0


    # if int(分钟) == 0 and int(秒数) == 0:
    #     quit()  # 当分钟数和秒数都减为0时执行退出函数结束程序

    txt = str("%2d:%2d" % (分钟, 秒数))  # 格式化输出剩余时间
    # text内容全局保持
    Lb.config(text=txt)
    Lb.text = txt
    win.after(1000, turn)  # 每隔1000毫秒调用一次自己


# 创建Label图像层控件
Lb = Label(win,  # 窗口对象
           text=str("%d:%2d" % (分钟, 秒数)),  # 格式化输出剩余时间
           font=("黑体", 60, "bold"),  # 字体定义
           fg="blue",  # 设置前景色
           width=240, height=100,  # 控件大小
           anchor='n', compound='center')  # 对齐方式

Lb.pack()  # 把控件对象绑定到窗口

while True:  # making a loop
    try:  # used try so that if user pressed other than the given key error will not be shown
        if keyboard.is_pressed('q'):  # if key 'q' is pressed
            turn()
            win.mainloop()
            time.sleep(0.5)

            continue  # finishing the loop
        else:
            pass
    except:
        break  # if user pressed other than the given key the loop will break

要求是按下q键开始倒计时5s,当时间显示为0时候就保持住。直到又开始按了q键再从5s开始倒计时。但是我写的只能执行一次,按第二次没反应。求大大们帮帮忙看看出了什么问题,在原来的基础上怎么改才能改对?

  • 写回答

1条回答 默认 最新

  • 普通网友 2021-10-27 09:06
    关注

    有没有报错?

    有没有日志看下?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 11月4日
  • 已采纳回答 10月27日
  • 创建了问题 10月27日

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改