Hi,
if You want to get key events also for non-character keys like
"enter", the TextCtrl widget needs an extra style setting
wx.WANTS_CHARS, i.e:
self.display = wx.TextCtrl(self, -1, style=wx.TE_RIGHT|wx.WANTS_CHARS)
than you should obviously uncomment the Bind call:
self.display.Bind(wx.EVT_KEY_DOWN, self.OnKeyPress)
and modify your OnKeyPress function to call event.Skip() for keys,
which should be passed further to the widget (i.e. written to the
textctrl), otherwise this is not done, if you are catching the
respective event with an event handler function.
With the following simplistic change, the calculator seems to react reasonably:
def OnKeyPress(self, event):
keycode = event.GetKeyCode()
if keycode in (wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER):
self.enter()
elif keycode in (wx.WXK_ADD, wx.WXK_NUMPAD_ADD):
self.add()
elif keycode in (wx.WXK_SUBTRACT, wx.WXK_NUMPAD_SUBTRACT):
self.sub()
elif keycode in (wx.WXK_MULTIPLY, wx.WXK_NUMPAD_MULTIPLY):
self.mult()
elif keycode in (wx.WXK_DIVIDE, wx.WXK_NUMPAD_DIVIDE):
self.div()
# add further keys and functions as needed
else:
event.Skip()
however, you might need to fine-tune the logic - in this version you
can write anything to the calculator like letter characters etc.,
which most lkely can't be handled; probably the logic should be
reversed to only call Skip() on chars, which are meaningful as input
for your calculator; on "functional" characters like + / ... you won't
call event.Skip() but use the corresponding function call instead; the
remaining keys, you are not going to accept as input will be
"swallowed" this way.
I believe, the gui should be usable this way, however, I don't have
experiences with the mentioned calculators nor the computations in
question, hence I can't comment on this part.
hth,
vbr
···
2016-03-31 5:54 GMT+02:00 Colby Christensen <colby.christensen1@gmail.com>:
I have been learning to program using Python (self-teach) and wanted to
create something useful while learning. I am using wxPython to create the
interface. The calculator uses RPN similar to an HP48 series calculator and
has the display appearance similar to an HP48 as well. The app works if I
use the mouse to click the buttons. I've been trying to get it to recognize
operation key-ins like the addition using the num pad +. It will register
the keystrokes but the binding for the event handler to run the operation
commands isn't working. I originally had it bound to the button then
realized it should be bound to the TextCtrl. When I bind the event to the
TextCtrl, it no longer recognizes any input from the keyboard. I would like
it to recognize key-ins like [enter], +, -, *, and / as operations and not
text input.
The code for the app is below. I know this isn't the cleanest written code
and would also appreciate any advice to clean it as well as to how to get it
to recognize input from clicking on the buttons and from the keyboard.
I'm using Python 2.7.10 64-bit
wxPython 3.0.2.0-2
Windows 10