Doing print pygame.key.get_pressed() prints me lots of 0's, but is there any way that I can print those 0's out as a letter and then sign that letter to a variable?
This is what I mean:
import pygame
pygame.init()
import time
while True:
pressed = pygame.key.get_pressed()
print(pressed) #This prints 0, but I want it to print the button I am pressing
time.sleep(1)
EDIT: I should probaly add that I am working on a scoreboard in pygame and that is why I need to check which button is pressed to be able to enter a name
You can get a list of pressed keys as strings with this piece of code:
pressed = pygame.key.get_pressed() # already familiar with that
buttons = [pygame.key.name(k) for k,v in enumerate(pressed) if v]
print(buttons) # print list to console
pygame.key.name() takes the index of the current list object and returns its name as string. Read more here.
BUT if you are planning to use this list to test for key presses in your code, I highly recommend you to get familiar with pygames way of handling inputs. You can find a tutorial about that here.
Related
I'm having trouble using the keyboard module. I'm working on a typing game in turtle graphics. The user types and a "guide" arrow above the sentence shows the user how far they've typed. The arrow is supposed to turn red when an incorrect letter is typed, and it turns green when a correct letter is typed.
Knowing if the user has typed the correct letter is no problem, I'm using keyboard.is_pressed() to move the arrow forward and change green. However, the incorrect part is the problem. I need to use a function that returns the value of a any key, not a specific key. If it returns the value of the key the user types, then I can see if it is incorrect or not.
I tried using the conditional: if keyboard.read_key() != letter: which does what I want, but since I am using keyboard.is_pressed() to see if the letter is correct or not, the arrow only changes green for an instant, and then goes red. This is the code I am using:
count1 = 0
while True:
if x[count1].isupper():
if keyboard.is_pressed(x[count1]) and keyboard.is_pressed('shift'):
carmove()
arrowmove()
count1 += 1
try:
if keyboard.read_key() != x[count1]:
incorrect()
except:
IndexError
else:
if keyboard.is_pressed(x[count1]):
carmove()
arrowmove()
count1 += 1
try:
if keyboard.read_key() != x[count1]:
incorrect()
except:
IndexError
if count1 == length1:
break
x[count1] is a specific letter in the sentence. This code causes the arrow to turn green for second, then it goes right back to red.
I also tried making a list of all of the printable characters, then remove the correct letter the user must type, and then iterate through the list but that didn't seem to work either.
I read through the API docs for the keyboard module, but I couldn't find anything else that might work. I'm wondering if it is possible to use the keyboard module, or if I have to use another module. Any help is appreciated.
is_pressed() function is not blocking the code to get a button click. and you also use the read_key function in the same code which is blocking the code until it gets a key.
since there is nothing here mention that the initial state for the arrow to be red. I'm assuming that the error is not in this code. this code has an error which is if you clicked the right key too fast. might not count. because is_pressed needs to be clicking the key while it executes. and another function will be blocking the code in other parts
So, I suggest this edit for your code
count1 = 0
while True:
key = keyboard.read_key()
if key == x[count1]:
carmove()
arrowmove()
count1 += 1
else:
incorrect()
if count1 == length1:
break
and the read_key result for a capital key the letter in capital. no need to check for shift
You might be able to toss the keyboard module and use turtle's own onkey() event handling. If you leave off the (second) key argument to the onkey() function, it will call your key handler code when any key is pressed. The problem is, there's no mechanism to let you know which key was pressed.
The following answer includes code to work around this design error, rewriting the underlying code to pass tkinter's event.char to turtle's event handler in the case where no key has been set (i.e. key is None):
How can I log key presses using turtle?
so I'm using pyautogui to type, and I'm trying to hold a key down for more than a second but I've ran into this problem where the key only types a single letter
import pyautogui
import time
pyautogui.keyDown("w")
time.sleep(2)
pyautogui.keyUp("w")
my output is "w"
but my output should be "wwwwwwwwwwwwwww" since I'm holding down the key?
the same thing occurs when im using the press function for pyautogui,
pyautogui.press("w") #but instead of pressing a single key, it totally just doesnt get outputted but only works for main keyboard functions like windowsKey and enter
if this is wrong, is their a way i can make it so I'm holding down the key?
From the Documentation it seems that it's not possible to do the way you have tried, however this function can help for 'holding down' a letter for a set number of seconds:
def hold_character(hold_time, character, interval=0.1):
pyautogui.write(character * int(hold_time / interval), interval=interval)
hold_character(2, 'w')
...gives the 'wwwwwwwwwwwwwww' effect for me
My friend and I were building a typing test. We are using the input() function in python to get input from the user. The problem is that we have to press enter to make the input save and we want that button to be spacebar instead. Is there any way to do this or another module we could use to solve this problem?
for i in range(num_words):
print(final_sentence)
print("")
typed_word = input("Type>")
words_to_list(typed_word)
os.system('clear')
You should probably use other modules like keyboard or pynput because input() detects whole strings while those modules detect key presses. Detect key presses, print them, and stop when Key.space (in pynput case) is pressed.
Something like this:
from pynput.keyboard import Listener
from pynput.keyboard import Key
words=''
def on_press(key):
if key==Key.space:
listener.stop()
print (words)
def on_release(key):
global words
typed = str(key).replace("'", "")
words = words + typed
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
This code detects key press using pynput.keyboard's handy listener, and adds it to words until space is pressed. When space is pressed the script stops the listener and prints the typed sentence.
I have a dictionary with a list of key presses and file names stored in key-value pairs as strings. I want to check if the key pressed is in the dictionary then print the pressed key and the file name associated with it.
My issue is that after I press one key, it keeps looping through the same function and only prints that key. I know I need to stop it from looping, but I don't know how to do that without using "break" or "return" to end the program. The only condition I want the program to end under is if the "esc" key is pressed.
I feel like the answer is ridiculously easy and I'm missing something simple, please help.
Here is my code:
import keyboard
import pygame
# there is more in the dictionary, but it's not much different from what is already pasted here
keys = {"`": "sounds/c2.mp3", "1": "sounds/db2.mp3", "2": "sounds/d2.mp3",}
key = keyboard.read_key()
def sound():
play = keys.get(key, "")
pygame.mixer.init()
pygame.mixer.music.load(play)
pygame.mixer.music.play()
def keypress():
while True:
if key in keys.keys():
if key != "esc":
print(key)
sound()
else:
break
keypress()
I think you need to move key = keyboard.read_key() inside your while loop. (Probably just after while True:)
as the question suggest I am looking for a way to hide or mask user input within python without using the standard getpass library due to using spyder; I am wondering if this would potentially be possible using key pressed and recording each key pressed without it displaying until say enter is pressed? If this is possible would someone be able to help me with a snippet for this purpose
Thanks,
Sam Hedgecock
You should take a look at a kind of key-logging mechanism. You could detect which key the user pressed, store those keys in a buffer to finally output them after ENTER is pressed.
Working cross-platform example:
from getkey import getkey, keys
#Buffer holding all the pressed keys
pressed_keys = []
while True:
#Getting the pressed key
key = getkey()
#Appending it to array
pressed_keys.append(key)
#If ENTER is pressed, exit loop
if key == keys.ENTER:
break
#Outputting all pressed keys after ENTER is pressed
for key in pressed_keys:
print(key, end='')
You need to install getkey though. Use pip3 install getkey.