簡體   English   中英

如何僅在按下鍵時運行python函數?

[英]How to have python function run only while key is pressed?

我正在嘗試制作一個簡單的程序,當您按住'w'時,它會使用forward ()但是當您放開時,它會使用stop()停止電動機。 目前,我只能讓它在按下“ w”時連續前進,而在按下另一個鍵時才停止。 這是我的代碼

#!/usr/bin/env python3
 # so that script can be run from Brickman

 import termios, tty, sys, time
 from ev3dev.ev3 import *

 # attach large motors to ports B and C, medium motor to port A
 motor_left = LargeMotor('outA')
 motor_right = LargeMotor('outD')
 motor_a = MediumMotor('outC')

 #==============================================

 def getch():
     fd = sys.stdin.fileno()
     old_settings = termios.tcgetattr(fd)
     tty.setcbreak(fd)
     ch = sys.stdin.read(1)
     termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)

     return ch

 #==============================================

 def fire():
    motor_a.run_timed(time_sp=3000, speed_sp=600)

 #==============================================

 def forward():
    motor_left.run_forever(speed_sp=1050)
    motor_right.run_forever(speed_sp=1050)

 #==============================================

 def back():
    motor_left.run_forever(speed_sp=-1050)
    motor_right.run_forever(speed_sp=-1050)

 #==============================================

 def left():
    motor_left.run_forever(speed_sp=-1050)
    motor_right.run_forever(speed_sp=1050)

 #==============================================

 def right():
    motor_left.run_forever(speed_sp=1050)
    motor_right.run_forever(speed_sp=-1050)

 #==============================================

 def stop():
    motor_left.run_forever(speed_sp=0)
    motor_right.run_forever(speed_sp=0)

 #==============================================

 print("ready")
    k = getch()
    print(k)
    if k == 'w':
       forward()
    if k == 's':
       back()
    if k == 'a':
       left()
    if k == 'd':
       right()
    if k == 'f':
       fire()
    if k == ' ':
       stop()
    if k == 'q':
       stop()
       exit()

有什么想法讓stop()在未按下'w'時運行?

您可以使用pygame的KEYUP和KEYDOWN功能。 以下是使用pygame的代碼片段:

import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
finished = False
isKeyPressed = False
while not finished:
    for event in pygame.event.get():
        if isKeyPressed:
            print "Key is currently pressed...Move forward!"
        if event.type == pygame.QUIT:
            finished = True
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                isKeyPressed = True
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_w:
                isKeyPressed = False
                #Perform action (here) when 'w' is unpressed 
        pygame.display.flip()
        clock.tick(60)
pygame.quit()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM