2

我正在尝试编写一个脚本,允许用户通过 matplotlib 中的事件处理来操作图形,但我需要让他们通过终端输入一些附加信息

调用raw_input()似乎会破坏脚本,并引发RuntimeError: can't re-enter readline错误

这是一段简单的代码来演示这一点:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(np.random.rand(10))

def keypress(event):
    print 'You press the "%s" key' %event.key
    print 'is this true? Type yes or no'
    y_or_n = raw_input()

cid = fig.canvas.mpl_connect('key_press_event', keypress)
plt.show()

如果我使用 python 运行它,这可以正常工作,但使用 ipython --pylab 会中断。不幸的是,我需要交互模式

我看到其他人遇到过这个问题,但我还没有看到解决方案

4

1 回答 1

3

您遇到了麻烦,因为 matplotlib 仍在监听按键。不幸的是,简单地断开它的事件监听对我来说并没有交互作用。然而,这个解决方案确实奏效了。尽管它限制了您不能使用“y”、“e”、“s”、“n”或“o”键。如果这是必要的,有解决方法。

import matplotlib.pyplot as plt
import numpy as np

#disable matplotlib keymaps
keyMaps = [key for key in plt.rcParams.keys() if 'keymap.' in key]
for keyMap in keyMaps:
    plt.rcParams[keyMap] = ''

str = ''

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(np.random.rand(10))

def keypress(event):
    global str

    if event.key in ['y','e','s','n','o']:
        str += event.key
    else:   
        print 'You press the "%s" key' %event.key
        print 'is this true? Type yes or no'

    if str == 'yes':
        print str
        str = ''
    elif str == 'no':
        print str
        str = ''

cid = fig.canvas.mpl_connect('key_press_event', keypress)
plt.show()
于 2012-10-10T13:12:36.327 回答