Get text when enter is pressed in a text box in wxPython - python

I have a (single line) TextCtrl. The user types data into this. When they press enter, the contents of the box need to be extracted so they can be processed. I can't figure out how to catch enter being pressed.
According to the docs, with the style wx.TE_PROCESS_ENTER set on my TextCtrl, it should generate a wx.EVT_COMMAND_TEXT_ENTER event when enter is pressed in the box, which I could then catch. However, wx.EVT_COMMAND_TEXT_ENTER seems not to exist (I get "module has no attribute EVT_COMMAND_TEXT_ENTER), so I'm a bit stuck. Googling just gets a couple of hits of people complaining wx.EVT_COMMAND_TEXT_ENTER doesn't work, so I guess I need another way of doing it.

I've never seen wx.EVT_COMMAND_TEXT_ENTER. I have used wx.EVT_TEXT_ENTER though...

Use style = wx.TE_PROCESS_ENTER in TextCtrl and Bind with Event wx.EVT_TEXT_ENTER
self.Text_Enter = wx.TextCtrl(self , 2 ,style = wx.TE_PROCESS_ENTER, size =(125,150), pos = (170,0))
self.Text_Enter.SetForegroundColour(wx.RED)
self.Bind(wx.EVT_TEXT_ENTER, self.Txt_Ent, id = 2)
def Txt_Ent(self,event):
msg1 = (str(self.Text_Enter.GetValue()))
wx.MessageBox(msg1)

Related

PsychoPy - If user doesn’t press anything, automatic assignment for key to “left” key

I am currently designing an experiment where the user has to press either “left” or “right” on a screen sequence which would be used in a later screen input.
Window 1:
Do you think that A or B will happen?
A: press left arrow key
B: press right arrow key
Window 2 has a code behind it something of the sort from below in order for variables to be output in the backend for future analysis.
if(‘left’ in keyDecisionResponse.keys):
something to happen
elif(‘right’ in keyDecisionResponse.keys):
something else to happen
However, if the user doesn’t press anything (which could happen if the user is not paying attention), I receive the error:
TypeError: argument of type ‘NoneType’ is not iterable
Experiment ended.
Therefore, I would like to automatically assign ‘left’ to ‘None’ in Window 1, something of the sort:
if (‘None’ in keyDecisionResponse.keys):
keyDecisionResponse.keys = ‘left’
It does not work. Also, I tried several things, but none of them worked.
Can you please help?
Thanks.
Check if keyDecisionResponse.keys is type NoneType then select default.
if keyDecisionResponse.keys is None:
keyDecisionResponse.keys = "left" # Or however you assign it
Also, make sure that you retain indentation and use proper quotation marks.

Is the function call to update a tkinter label after a button command was executed reason for unexpected behavior?

first of all let me start off by saying I started coding around 6 weeks ago in self-study, so it is very likely, that the approach may still be a total mess.
I have a program running (fine for me) in cli, but I want to make it usable for people that faint, when they see plain white text on a black background which they have to operate without a mouse.
Besides my main window, which is running in the background I wanted to have a message window, which displays the information if all necessary files where selected. which is shown below.
files_to_open = {'File_1':'', 'File_2':'', 'File_3':''}
def selectfiles_window():
global message_window
message_window = Tk()
...
content = Label(message_window, text=get_open_file_status_txt(), **txt_status_general)
content.pack(side='top')
button_select_file1 = Button(message_window,text = 'File 1',font = txt_general['font'],command = lambda:(
select_file_action(name='File 1', filetypename='Excel workbook', extension='*.xlsx'),
content.configure(text=get_open_file_status_txt())))
button_select_file1(side='bottom')
message_window.mainloop()
def select_file_action(name, filetypename, extension):
global files_to_open
files_to_open[name] = filedialog.askopenfilename(title = f'Select {name}', filetypes=[(filetypename, extension)])
def get_open_file_status_txt():
global files_to_open
message =f'''
[File_1] is {"NOT SET" if (files_to_open["File_1"] == "") else "SET"}'''
return message
I expected, that the text is updated after the filedialog was closed (which is partly working as expected).
Now what I don't understand: If I click the button to select File_1 and cancel it for the first time, the value for key File_1 is set to (). Any time after that, if I click the button to select File_1 and cancel it, the value for key File_1 is set to ''. If I select a file the path is saved correctly as value (also on the first attempt). If I cancel it is set again to ''.
Anybody an idea about why the value is set to () on the first cancel but afterwards runs as expected?
I would also be grateful for a different solution to update the text, if my approach is totally off.
Thank you and best regards,
Thomas
Turns out, that the function call was not the issue, rather that it is a (strange to me but maybe intended) behavior of filedialog.askopenfilename, which returns an empty tuple if cancel is selected on first call but an empty string on every further canceled calls.

Getting input in python via the same window?

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

PyQt trigger a button with ctrl+Enter

I'm trying to make a trigger for the Ok button in my application
The current code I tried was this:
self.okPushButton.setShortcut("ctrl+Enter")
However, it doesn't work, which kind of makes sense. I tried looking up some key sequences here, but, again, a similar issue if I try with the shift or alt keys.
How can I trigger the OkButton with ctrl+Enter
According to the docs:
Qt.Key_Enter 0x01000005 Typically located on the keypad.
That is to say when you set Enter we refer to the key that is on the numeric keypad.
But if you want to use the default enter you must use Return.
self.okPushButton.setShortcut("Ctrl+Return")
# seq = QKeySequence(Qt.CTRL+Qt.Key_Return)
# self.okPushButton.setShortcut(seq)

Python 3.3 tkinter's Entry widget update on key

I am using tkinter for a GUI. I bound an event to an entry like so:
EntryFilePath.bind("<Key>", updateAmountOfPeople)
It works, but the problem is that it only updates when a key other than typing input is being pressed. Backspace triggers it, arrows trigger it, just not letters or numbers. I am looking for this functionality.
Other info that might be important:
PathFileName = StringVar()
EntryFilePath = Entry(topLeftMidFrame, textvariable = PathFileName, width=45)
EntryFilePath.pack(side=TOP, pady=32, padx=10)
How to make it trigger on any key?
EDIT: I found out that this only happens when it just got selected. It needs one of the "other" non [a-Z0-9] keys once, after that it is good to go. This is problematic though, in case people start immediately writing.
EDIT2: It might have to do with it having update delay.
The binding should work for every keypress -- if it's not, you're doing something somewhere else in your code to prevent it from working, or your testing is flawed.
If you want a function to be called whenever the value changes, you might want to consider setting a trace on the variable associated with the entry widget. The trace will fire whenever the value changes, no matter whether it's through keyboard input, pasting with the mouse, etc. It will not call your callback when the user uses the arrow keys or the return key, or any other key that doesn't affect the value.
For example:
def var_callback(*args):
print "the variable has changed:", PathFileName.get()
PathFileName.trace("w", var_callback)
It can be solved by changing
EntryFilePath.bind("<Key>", updateAmountOfPeople)
to
EntryFilePath.bind("<KeyRelease>", updateAmountOfPeople)

Categories