2
votes

Firstly, I'm a complete beginner, so I do not have any experience, I have however searched all the possible places these last 2 days for a resolve, and could not find it.

I'm using this on a Raspberry PI 3 with Raspbian.

I'm trying to build a simple code in Python 3.6 that will do the following: When pressing a keyboard key:

1.it should print 'press' if the key was pressed, without repeating.

(if the key is being held down, it should print 'press' only once and stop).

2.it should print 'release' if the key was released without repeating.

Basically I want to print once the last state of the key,

The problem I am having is:

while holding down the key, I'm getting consecutive press/release press/release press/release events, even if no key was physically released, instead of getting only 1 'press'.

Below is the code that I'm trying to use.

#!/usr/bin/env python
import pygame
from pygame.locals import *
from time import sleep
import time

pygame.init()
screen = pygame.display.set_mode((800,800))

keys= [False]
last = None
pygame.key.set_repeat()

while True:
        if keys[0]==True and last != 'press': 
            print ('press')
            last = 'press'

        if keys[0]==False and last != 'release':
            print('release')
            last = 'release'

        for event in pygame.event.get():
            if event.type==pygame.QUIT:
                pygame.quit()
                exit(0)

            if event.type == pygame.KEYDOWN:
                if event.key==K_d:
                    keys[0]=True                        

            if event.type == pygame.KEYUP:
                if event.key==K_d:
                    keys[0]=False
1
pygame.key.set_repeat() enables automatic repetition of pressed key. Also, just a good practice thing - you don't need to compare boolean values with True and False, keys[0] and last.., or not keys[0] for false is better - Michal Polovka
if you want to disable key repetition, set set_repeat() to set_repeat(0) - Michal Polovka
I have previously tried to set pygame.key.set_repeat() to pygame.key.set_repeat(0) but to no effect, in fact, on the python documentation it says that repetition is disabled by default, but even without this line, the end result is the same, up/down events while key pressed, and thank you for the advice. - Dragos
wow, it was because I was using VNC, and not the keyboard that was actually plugged into the RPi, it works as expected now. Thank you! wasted 2 days of my life for nothing. - Dragos
Instead of adding "Solved", write your comment as an answer, then accept it (by clicking on the green hollow check mark). This will make the question is resolved in the system. - Burhan Khalid

1 Answers

2
votes

Problem solved, it was because I was using a VNC instead of using the keyboard directly connected to the Raspberry Pi.