【问题标题】:How can I have my program wait for input, without being in a loop我怎样才能让我的程序等待输入,而不是在循环中
【发布时间】:2013-03-10 20:04:35
【问题描述】:

我正在编写一个 Pygame 程序,它需要用户输入来编写音乐。它等待特定事件(即键盘或鼠标输入)并立即分析输入,而无需用户在每次输入时按 Enter。

while (running == 1):
    for event in pygame.event.get():
# If event is a keypress
        if(event.type == pygame.KEYDOWN):
            key = pygame.key.get_pressed()  # get_pressed returns an boolean array
                                            # of every key showing pressed or not
# Find which key is pressed
            for x in range(len(key)):
                if(key[x] == 1):
                    break
# If a number key is pressed (0-9)
            if(x >= 48 and x <=57):
# Set the octave to keypress
                gui.setOctave(x-48)    # gui is an instance of a class 
                                       # that controlls pygame display

我知道这样做的唯一方法是使用无限 while 循环。但是,这几乎占用了所有 CPU 资源来运行。是否有另一种不使用循环的有效方法来解决这个问题?

【问题讨论】:

    标签: python pygame


    【解决方案1】:

    您可以使用event = pygame.event.wait() 等待事件。

    【讨论】:

    • 对不起,我是新手。谢谢你告诉我。
    猜你喜欢
    • 2013-02-22
    • 1970-01-01
    • 2013-08-18
    • 1970-01-01
    • 2015-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    相关资源
    最近更新 更多