好的,所以我正在编写一个脚本,该脚本使用带有Raspberry Pi 3b的SBC电机屏蔽板来控制电机。
我遇到的问题是,如果我只运行脚本,则会弹出一秒钟的窗口,允许按下a键将电动机向前移动,或者我已经在脚本中定义的任何其他键,但是仅持续一秒钟,然后窗口自动退出,我返回到终端。
现在,当我尝试添加循环以保持代码运行时,窗口将保持打开状态,但是当我按下脚本中定义的键时,窗口将不再识别。。我花了很多时间研究和修改我编写的脚本,一直找不到解决方案。我是python的新手,感谢您提供的任何输入。
我也正在运行python 3.6,谢谢
import pygame
import sys
import pygame.locals
import PiMotor
import time
m1 = PiMotor.Motor("MOTOR1",1)
m2 = PiMotor.Motor("MOTOR2",1)
pygame.init()
(width, height) = (300, 200)
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Johnny, motor controls!')
pygame.event.pump()
for event in pygame.event.get():
if event.type == pygame.locals.QUIT:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
m1.forward(100), time.sleep(0)
if event.type == pygame.KEYUP:
if event.key == pygame.K_a:
m1.stop()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
m1.forward(100)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
m1.stop()
答案 0 :(得分:1)
在获取事件并检查何时退出时,您只需要添加while True:
。
如果您尝试过但没有成功,也许您的缩进错误?我发现您发布的代码现在有问题。
类似的东西:
while True:
for event in pygame.event.get():
if event.type == pygame.locals.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
m1.forward(100), time.sleep(0) # BTW, do you really need this sleep?
[... Rest of your code ...]