Is there a command for python shell that allows key input without using enter, like a tkinter bind or a cmd choice. any suggestions
I've tried a tkinter bind. pynput is not out for python 3.7 yet :(. any other suggestions? This did not work.
canvas.bind_all('<KeyPress-Left>',Left)
canvas.bind_all('<KeyPress-Right',Right)
def Right():
if R == 0:
X = X + 1
def Left():
if L == 0:
X = X - 1
I expected it to change x, but it didn't change.
(x is declared before these statements are called.)
use this if your os is windows
msvcrt.getch()
Read a keypress and return the resulting character. Nothing is echoed to the console. This call will block if a keypress is not already available, but will not wait for Enter to be pressed. If the pressed key was a special function key, this will return '\000' or '\xe0'; the next call will return the keycode. The Control-C keypress cannot be read with this function.
check --> https://docs.python.org/2/library/msvcrt.html
Related
I'm trying to make a simple python program that is meant to be run from a gnome-terminal.
I have an "#" character on screen that I want to move left (when left arrow pressed) and right (when right arrow pressed). How can I do this without using the curses library?
You will have a hard time doing that without using a library such us curses, and I discourage you to do so since you would have to deal with several pitfalls.
That said, you are facing two issues: detecting key presses and printing over the same line several times.
If you do some research you would find that in linux you can read from the standard input disabling the buffering using tty and termios (see here for example). You may use that to detect the pressing of an arrow key.
About printing on the same line, you have some special control character such as the carriage return \r which you may use to achieve your goal.
Putting everything together, the most basic program to move a "#" using the arrow keys would look like this:
#!/usr/bin/env python3
import sys
import termios
import tty
K_RIGHT = b'\x1b[C'
K_LEFT = b'\x1b[D'
def read_keys():
stdin = sys.stdin.fileno()
tattr = termios.tcgetattr(stdin)
try:
tty.setcbreak(stdin, termios.TCSANOW)
while True:
yield sys.stdin.buffer.read1()
except KeyboardInterrupt:
yield None
finally:
termios.tcsetattr(stdin, termios.TCSANOW, tattr)
def reset_line():
print(
'\033[F' + # move up
'\033[K', # clear row
end=''
)
def print_sprite(x):
print((' '*x) + '#')
if __name__ == '__main__':
print('Press Ctrl+c to quit')
sprite_x = 0
print_sprite(sprite_x)
for k in read_keys():
if k == K_LEFT:
sprite_x -= 1
if k == K_RIGHT:
sprite_x += 1
reset_line()
print_sprite(sprite_x)
As you can see this is far away from being a "simple program" and the curses library is definitely the way to go.
So, I want to make some simple code with Python on Visual Studio Code where when I press Enter, it registers and adds one to a variable, like...
if Enter pressed:
variable += 1
Here is what I did using the keyboard module-
import keyboard
variable = 0
while True:
if keyboard.is_pressed("Enter"):
variable += 1
print(variable)
You may have to download keyboard. For this run this command in your computer's command prompt/terminal-
py -m pip install keyboard
There is probably a better way to do this using keyboard.on_press_key() , as using is_pressed adds 1 to variable continuously as long as the key is pressed.
Hope my answer helps!
import keyboard
variable = 0
print("Please Press Enter key")
def on_press_event(event):
global variable
if event.name == "enter":
variable += 1
print("pressed count %d times"%variable)
keyboard.on_press(on_press_event)
while True:
pass
I would like to know how to get user input in python without using the command line or an input box.
Let me explain. I do not want to do this
#All code is python 3
name=input("What is your name?")
Why? When running scripts, the command line is not auto-focused. Furthermore, it pops up another window, something I do not want because I can't hit escape to close it in a hurry (Something which you may want to do if you're playing a game).
What have I tried?
I looked at WX and it's dialog function, something like this:
import wx
app=wx.App()
def text_entry(title,message):
result=None
dlg=wx.TextEntryDialog(None, message,title)
if dlg.ShowModal()==wx.ID_OK: result=dlg.GetValue()
dlg.Destroy()
return result
text_entry("Text entry","Enter something here")
While this works, it pops up another window which again, I do not want. However, it is closer to what I am ultimately looking for, because I can hit escape to make it go away.
I have tried using pygame and it's key.get_pressed() function, but it inserts a lot of the same letter into the entry, even if I gently tap the key. Also, when I implemented it into the project, it can only pick up on normal letters. Writing 26 if statements to detect key presses for a single letter with or without the shift key seems a little counter intuitive.
Finally, I am a bit hesitant to try tkinter. I happen to be blind, and from what I read, tk is very visual, which makes me concerned that it won't play nicely with my screen reader (NVDA).
So, I'm here. After searching on google for "getting input without using command line in python 3", "input in the same window", and "input without using input()" yielded nothing.
To recap, I want to accept user input without using the input() function, and without any additional windows popping up for the duration of me doing so.
Thank you.
What about this solution using the msvcrt module. At any time if you press escape then the program will exit. Python sys.exit(), and built-ins exit() and quit() all call raise SystemExit so this is just one less call to perform. If you press the enter or return key then the while loop ends and you can use the keys that were pressed later in your program as they are stored in the variable user_input. The print at the end just proves that the pressed keys are stored in user_input variable and the input() function simply to leave the window open so you can see it working.
import msvcrt
user_input = b''
while True:
pressed_key = msvcrt.getche() # getch() will not echo key to window if that is what you want
if pressed_key == b'\x1b': # b'\x1b' is escape
raise SystemExit
elif pressed_key == b'\r': # b'\r' is enter or return
break
else:
user_input += pressed_key
print('\n' + user_input.decode('utf-8')) # this just shows you that user_input variable can be used now somewhere else in your code
input() # input just leaves the window open so you can see before it exits you may want to remove
So after doing some more research, I found this:
https://codeload.github.com/Nearoo/pygame-text-input/zip/master
I think this is what I am looking for, though it still needs to be slightly modified. Thank you for the assistance
Is there anyway for python 3 to recognise a keypress? For example, if the user pressed the up arrow, the program would do one thing whereas if the down arrow was pressed, the program would do something else.
I do not mean the input() function where the user has to press enter after the keypress , I mean where the program recognises the keypress as some as it was pressed.
Is this question too confusing? xD
Python has a keyboard module with many features. You Can Use It In Both Shell and Console.
Install it, perhaps with this command:
pip3 install keyboard
Then use it in code like:
import keyboard #Using module keyboard
while True: #making a loop
try: #used try so that if user pressed other than the given key error will not be shown
if keyboard.is_pressed('up'): #if key 'up' is pressed.You can use right,left,up,down and others
print('You Pressed A Key!')
break #finishing the loop
else:
pass
except:
break #if user pressed other than the given key the loop will break
You can set it to multiple Key Detection:
if keyboard.is_pressed('up') or keyboard.is_pressed('down') or keyboard.is_pressed('left') or keyboard.is_pressed('right'):
#then do this
You Can Also Do Something like:
if keyboard.is_pressed('up') and keyboard.is_pressed('down'):
#then do this
It Also Detect Key For The Whole Windows.
Thanks.
I assume this is a gui program,
If using the built-in gui module Tkinter, you can use bind to connect a function to a keypress.
main.bind('<Up>', userUpkey)
Where userUpKey is a function defined in the current scope.
I want to break an infinite loop when pressing space bar. I dont want to use Pygame, since it will produce a window.
How can i do it?
I got an answer. We can use msvcrt.kbhit() to detect a keypress. Here is the code i wrote.
import msvcrt
while 1:
print 'Testing..'
if msvcrt.kbhit():
if ord(msvcrt.getch()) == 32:
break
32 is the number for space. 27 for esc. like this we can choose any keys.
Important Note: This will not work in IDLE. Use terminal.
Python has a keyboard module with many features. You Can Use It In Both Shell and Console.
Install it, perhaps with this command:
pip3 install keyboard
Then use it in code like:
import keyboard #Using module keyboard
while True: #making a loop
try: #used try so that if user pressed other than the given key error will not be shown
if keyboard.is_pressed(' '): #if key space is pressed.You can also use right,left,up,down and others like a,b,c,etc.
print('You Pressed A Key!')
break #finishing the loop
except:
pass
You can set it to multiple Key Detection:
if keyboard.is_pressed('up') or keyboard.is_pressed('down') or keyboard.is_pressed('left') or keyboard.is_pressed('right'):
#then do this
You Can Also Do Something like:
if keyboard.is_pressed('up') and keyboard.is_pressed('down'): #if both keys are pressed at the same time.
#then do this
Hope This Helps You.
Thanks.
Using space will be difficult because each system maps it differently. If you are okay with enter, this code will do the trick:
import sys, select, os
i = 0
while True:
os.system('cls' if os.name == 'nt' else 'clear')
print ("I'm doing stuff. Press Enter to stop me!")
print (i)
if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
line = input()
break
i += 1
Source