开发者

How to use python curses module to create a key event?

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


Generating a keypress:

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

  • The crude way: os.system('xvkbd -text "\\\\CP" ')
  • Alternatives:
  • Simulate keystroke in Linux with Python
  • Simulating Key Press event using Python for Linux
  • This module is interesting, uses a kernel module: http://codegrove.org/projects/python-uinput
  • Couldn't find mention of generating keypress events in curses.

Getting a key press:

Use of curses is a bit much for this case.

  • Something like: getting a char at a time would be simpler.
  • Easier than curses would be to use urwid.
  • Finally, the curses way: http://docs.python.org/release/2.6/howto/curses.html#user-input


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜