如何在不使用KeyboardInterrupt的情况下从按键退出while循环?[蟒蛇]

塞普尔

我正在制作一个每x秒发出哔声的计时器,但是在某些按键过程中计时器会重新启动。代码的第一部分使计时器启动。然后进入计时器的while循环。我想中断循环而不按键盘中断,而是按另一个键。

有什么帮助吗?这是下面的代码

import time, winsound, keyboard
x = 0
while x == 0:
    if keyboard.is_pressed(','):
        x = x+1
while True:
    try:
        while x==1:
            for i in range(29):
                time.sleep(1)
                print(i)
                if i == 28:
                    winsound.Beep(300,250)
    except KeyboardInterrupt: 
        continue
用户名

这是我向你保证的例子。

我不需要为此程序导入任何mod,但是我相信用来控制键盘输入msvcrt mod是Windows特定的。是因为它可能; 即使我们使用不同的方法来控制键盘输入,但我希望您能看到在主程序重复循环并处理键盘输入时如何通过按键来控制秒表。

import time     # Contains the time.time() method.
import winsound # Handle sounds.
import msvcrt   # Has Terminal Window Input methods 
# ===========================================
# -------------------------------------------
# --              Kbfunc()                 --
# Returns ascii values for those keys that
# have values, or zero if not.
def kbfunc():
    return ord(msvcrt.getch()) if msvcrt.kbhit() else 0
# -------------------------------------------
# --           Get_Duration()              --
# Gets the time duration for the stopwatch.
def get_duration():
    value = input("\n How long do you want the timer to run? ")
    try:
        value = float(value)
    except:
        print("\n\t** Fatal Error: **\n Float or Integer Value Expected.\n")
        exit()
    return value
# ===========================================
#                   Body    
# ===========================================
# To keep the program as simple as possible, we will only use
# standard ascii characters. All special keys and non-printable
# keys will be ignored. The one exception will be the
# carriage return key, chr(13).
# Because we are not trapping special keys such as the
# function keys, many will produce output that looks like
# standard ascii characters. (The [F1] key, for example,
# shares a base character code with the simicolon.)

valid_keys = [] # Declare our valid key list.
for char in range(32,127):  # Create a list of acceptable characters that
    valid_keys.append(char) # the user can type on the keyboard.
valid_keys.append(13)       # Include the carriage return.

# ------------------------------------------
duration = 0
duration = get_duration()

print("="*60)
print(" Stopwatch will beep every",duration,"seconds.")
print(" Press [!] to turn Stopwatch OFF.")
print(" Press [,] to turn Stopwatch ON.")
print(" Press [@] to quit program.")
print("="*60)
print("\n Type Something:")
print("\n >> ",end="",flush = True)

run_cycle = True # Run the program until user says quit.
stopwatch = True # Turn the stopwatch ON.
T0 = time.time() # Get the time the stopwatch started running.

while run_cycle == True:
    # ------
    if stopwatch == True and time.time()-T0 > duration: # When the duration
        winsound.Beep(700,300)  # is over, sound the beep and then
        T0 = time.time()          # reset the timer.
    # -----
    key = kbfunc()
    if key == 0:continue # If no key was pressed, go back to start of loop.    
    
    if key in valid_keys: # If the user's key press is in our list..
        
        if key == ord(","): # A comma means to restart the timer.
            duration = get_duration()         # Comment line to use old duration.
            print(" >> ",end="",flush = True) # Comment line to use old duration.
            t0 = time.time()
            stopwatch = True
            continue # Remove if you want the ',' char to be printed.
        
        elif key == ord("!"): # An exclamation mark means to stop the timer.")
            stopwatch = False
            continue # Remove if you want the "!" to print.
        
        elif key == ord("@"):  # An At sign means to quit the program.
             print("\n\n Program Ended at User's Request.\n ",end="")
             run_cycle = False # This will cause our main loop to exit.
             continue # Loop back to beginning so that the at sign
                      # is not printed after user said to quit.
             
        elif key == 13: # The carriage return means to drop down to a new line.
            print("\n >> ",end="",flush = True)
            continue
             
        print(chr(key),end="",flush = True) # Print the (valid) character. 
        # Keys that are not in our list are simply ignored.

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在不使用break的情况下退出C ++中的循环?

如何在不使用for / while循环的情况下遍历ndarray?

如何在不使用while循环的情况下以一对多关系更新多行

如何在不使用“goto”和“do while”循环的情况下进入程序的初始阶段?

如何在不使用循环的情况下多次打印?

Python如何在不结束代码且不使用KeyboardInterrupt的情况下手动结束收集数据的while循环?

如何在不使用Win32 API激活Window的情况下模拟按键组合

如何在Blazor中不使用输入标签的情况下检测按键

如何在不使用Ordereddict的情况下按键对Python字典进行排序?

Java-如何在不使用while循环的情况下检查Scanner输入是否为整数?

如何在不使用C ++ 98的情况下退出进程?

如何在不使用鼠标的情况下退出Chromium搜索栏?

如何在不使用lsof或fuser的情况下退出OpenSSH控件主进程?

如何在不使用“except”python的情况下退出不和谐机器人

如何在不使用标准Ctrl +]组合的情况下退出telnet?

如何在不使用Ctrl + c的情况下退出“ tail -f”模式?

在不使用线程的情况下并行while循环

如何在不进入 Next 的情况下退出 For 循环

如何在不使用numpy或tensorflow中使用任何循环的情况下获取矩阵行?

如何在不使用for循环的情况下使用numpy数组访问列表的条目

如何在不使用循环的情况下使用numpy.lexsort

如何在不使用define的情况下使用乌龟图形和嵌套循环创建棋盘?

如何在不使用循环的情况下使用filter()查询集

如何在不使用numpy在python中使用for循环的情况下实现矩阵映射?

如何在不使用for循环的情况下使用str_split拆分嵌套列表?

如何在不使用while(true)的情况下使用recv函数?

如何在不使用for循环的情况下计算图像中像素强度的出现次数?

如何在不使用循环的情况下对 3 个以上的多维数组进行元素乘法

如何在不使用任何循环的情况下从PHP中的数组获取偶数键值