在不结束程序的情况下中断循环(python)

时间:2020-08-16 17:57:25

标签: python dictionary while-loop

我有一本字典,其中包含按键列表和以字符串形式存储在键值对中的文件名。我想检查按下的键是否在词典中,然后打印按下的键和与之关联的文件名。

我的问题是,当我按下一个键后,它会不断循环显示相同的功能,只打印该键。我知道我需要停止它的循环,但是我不知道如何在不使用“ break”或“ return”结束程序的情况下执行此操作。我希望程序结束的唯一条件是按下“ esc”键。

我觉得答案很简单,但我缺少简单的东西,请帮忙。

这是我的代码:

import keyboard
import pygame

# there is more in the dictionary, but it's not much different from what is already pasted here
keys = {"`": "sounds/c2.mp3", "1": "sounds/db2.mp3", "2": "sounds/d2.mp3",} 
key = keyboard.read_key()

def sound():
    play = keys.get(key, "")
    pygame.mixer.init()
    pygame.mixer.music.load(play)
    pygame.mixer.music.play()

def keypress():
    while True:
        if key in keys.keys():
            if key != "esc":
                print(key)
                sound()
            else:
                break

keypress()

1 个答案:

答案 0 :(得分:1)

我认为您需要在key = keyboard.read_key()循环内移动while。 (可能刚好在while True:之后)