Python:重复一个函数直到按键启动

2024-09-30 16:27:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我的函数'hello()'只是在屏幕上显示一个刺激2秒钟,在此期间可以按一个键。如果没有按下某个键,它将等待1秒,然后再次运行该功能,如果没有按键,则反复运行。当按下某个键时,它退出while循环并打印yes。由于某些原因,如果我让函数循环,例如,在我按下一个键之前循环4次,那么我将同时得到5个打印staments,而我只期望一个。有人能告诉我为什么它似乎在存储print语句,尽管我希望在我按下键之前永远无法访问print语句?在

def hello():
    test = 1 
    running = 1
    while running == 1:
        for frame in range(short_frames):      # 2 seconds
            fix.draw()
            window.flip()

            allKeys = event.getKeys(keyList = ('g','h'))
            for thisKey in allKeys:
                if thisKey == 'g':
                    keyTime=core.getTime()
                    test = 2
                elif thisKey == 'h':
                    keyTime=core.getTime()
                    test = 2

        window.flip()
        core.wait(1)

        if test == 1:               #if no key is pressed
            hello()                 #run the function again

        running = 2                 #exit out of while loop

    print "yes"

for i in range(1):
    hello()
core.quit()
window.close()

Tags: 函数incoretesthelloforifrange
2条回答

hello()正在递归地调用自己。每次调用时它都会打印一次输出。为了获得你想要的效果,你需要这样的东西:

def hello():
    test = 1 
    running = 1
    while running == 1:
        for frame in range(short_frames):      # 2 seconds
            fix.draw()
            window.flip()

            allKeys = event.getKeys(keyList = ('g','h'))
            for thisKey in allKeys:
                if thisKey == 'g':
                    keyTime=core.getTime()
                    test = 2
                elif thisKey == 'h':
                    keyTime=core.getTime()
                    test = 2

        window.flip()
        core.wait(1)
        running = test

    print "yes"

for i in range(1):
    hello()
core.quit()
window.close()

在while循环的底部,如果test没有改变(即没有按下一个键),running将被设置为1,循环将继续。如果按下2键,则循环将被设置为“运行”(2)。“yes”字符串只打印一次,因为hello()只调用一次。在

更新:

^{pr2}$

您已经在hello中调用了函数hello。这是递归。到第五次,你按一个键。它将打印您的thing,并结束第5次调用hello。您的程序返回到第4.thhello,并捕获按下的键。函数hello的第4次调用将再次打印,结束第4次hello并返回到第3次调用hello,以此类推。。。。。在

你应该小心recursion。 我不知道,为什么需要变量test和{}。但这些代码会起作用的。在

def hello():
    is_pressed = False
    while not is_pressed:
        for frame in range(short_frames):      # 2 seconds
            fix.draw()
            window.flip()

            allKeys = event.getKeys(keyList = ('g','h'))
            for thisKey in allKeys:
                if thisKey == in ['g', 'h']
                    keyTime=core.getTime()
                    is_pressed = True

        window.flip()
        core.wait(1)

    print "yes"

相关问题 更多 >