简体   繁体   中英

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 os

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:

Getting a key press:

Use of curses is a bit much for this case.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM