HyperCom
Posts: 2
Joined: Thu Nov 02, 2017 10:09 pm

pygame input from keyboard doesn't work

Thu Nov 02, 2017 10:35 pm

Hi all,

i'm trying to create a little program with python and pygame but i have a problem.
I have the first model of Raspberry with 512 MB of RAM.
In my program the input from keyboard doens't work.

Code: Select all

import pygame
from pygame.locals import *
from sys import exit
  
  
#initializing variables
pygame.init()
screen=pygame.display.set_mode((640,480),0,24)
pygame.display.set_caption("Key Press Test")
f1=pygame.font.SysFont("comicsansms",24)
  
#main loop which displays the pressed keys on the screen
print("xx")
while True:
 for i in pygame.event.get():
  if i.type==QUIT:
   exit()
  a=100
  screen.fill((255,255,255))
  if pygame.key.get_focused():
    press=pygame.key.get_pressed()
    for i in range(0,len(press)): 
      if press[i]==1:
       name=pygame.key.name(i)
       print(name)
       text=f1.render(name,True,(0,0,0))
       screen.blit(text,(100,a))
       a=a+100
      pygame.display.update()
This program should print on the screen the pressed key but it doesn't print.
The programm print on the screen only numlock but not the other keys.
On Windows this program run correctly.
Can you help me?

Thank you all

User avatar
OutoftheBOTS
Posts: 711
Joined: Tue Aug 01, 2017 10:06 am

Re: pygame input from keyboard doesn't work

Fri Nov 03, 2017 10:20 am

Ok I have just had a quick look at your code and did just notice 1 thing at the bottom of your loop you call "pygame.display.update()" then the loop jumps back up to the top and calls "screen.fill((255,255,255))" is it possible that you need a time.sleep(0.2) after the pygame.display.update()

HyperCom
Posts: 2
Joined: Thu Nov 02, 2017 10:09 pm

Re: pygame input from keyboard doesn't work

Fri Nov 03, 2017 10:43 pm

Thank's for the solution but the program doesn't work. I did a lot of tests and I think the reason why the program doesn't work is that the loop "for i in range(0,len(press)):" is too long and the RPI is too slow. I modified the program using the event keydown and it run correctly. In your opinion my idea is correct? :) :?:

Return to “Python”