Как мне выйти из while l oop нажатием клавиши без использования KeyboardInterrupt? [питон] - PullRequest
0 голосов
/ 10 июля 2020

Я делаю таймер, который подает звуковой сигнал каждые x секунд, но таймер перезапускается при нажатии определенной клавиши. Первая часть кода запускает таймер. Затем у таймера наступает время l oop. Я хочу прервать l oop, не нажимая клавишу прерывания клавиатуры, а другую клавишу.

Любая помощь? Вот код ниже

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

1 Ответ

0 голосов
/ 11 июля 2020

Вот пример, который я вам обещал.

Мне не нужно было импортировать какие-либо моды для этой программы, но я считаю, что мод msvcrt , который я использую для управления вводом с клавиатуры, Windows специфические c. Как бы то ни; Несмотря на то, что мы используем разные методы для управления вводом с клавиатуры, я надеюсь, вы увидите, как вашим секундомером можно управлять нажатием клавиш, в то время как основная программа постоянно зацикливается и обрабатывает ввод с клавиатуры.

Если вы найдете этот пример полезным, пожалуйста не забудьте нажать на команду «Принять ответ». Спасибо и получайте удовольствие !!

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.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...