0

I'm trying to make a key event in python. I think that with curses module i can do that but i don't know how to. Please help me.

How can i call a function with a press of a keyboard key. Like, if "space" key is pressed do something, if "c" key is pressed show image, if "s" key is pressed save image. My problem is only to make that key event. I'm using Linux o.s.

I tried to use urwid module and when i use this code:

import PIL
import Image 
im=Image.open("im.tif")
imshow(im,cmap=cm.gray ,origin=1)
import urwid 
def save(input):
     if input in ('s'):
         savefig("im2.png")

appeared this error:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1413, in __call__
    return self.func(*args)
  File "/usr/lib/pymodules/python2.6/matplotlib/backends/backend_tkagg.py", line 312, in key_press
    FigureCanvasBase.key_press_event(self, key, guiEvent=event)
  File "/usr/lib/pymodules/python2.6/matplotlib/backend_bases.py", line 1143, in key_press_event
    self.callbacks.process(s, event)
  File "/usr/lib/pymodules/python2.6/matplotlib/cbook.py", line 163, in process
    func(*args, **kwargs)
  File "/usr/lib/pymodules/python2.6/matplotlib/backend_bases.py", line 1703, in key_press
    self.canvas.toolbar.save_figure(self.canvas.toolbar)
TypeError: save_figure() takes exactly 1 argument (2 given)

What am i doing wrong ? How can i make it work?

ps: I'm sorry for my ignorance but i'm very new in python.

Thank you for answer

1
  • Don't use urwid and Tkinter together, bad idea. Their event loops will likely conflict. Commented Sep 1, 2011 at 18:49

2 Answers 2

2

Generating a keypress:

On Windows it is quite easy to generate keypresses. On Linux a bit more difficult:

Getting a key press:

Use of curses is a bit much for this case.

Sign up to request clarification or add additional context in comments.

1 Comment

I may be wrong here but I think the OP was asking about firing a key press event by a script, as opposed to handling a key press event from a user.
0

Events such as you describe are usually associated with some sort of GUI container (window, canvas, frame, what have you) so "events" really don't have any meaning without some sort of GUI. I could give a more detailed answer if you would say what GUI framework you are using, but barring that, here are links descibing how to handle events using TKInter and WxPython

1 Comment

I think he meant "reading a keypress" by using raw mode on the tty.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.