Python 带键处理程序的matplotlib绘图仅在鼠标移动时更新
我有一个交互式matplotlib窗口,当焦点在窗口上时,它由命令行和键盘输入驱动 问题是,当焦点在窗口上时,直到鼠标在屏幕上的任何位置移动,按键事件才会被触发 要运行下面的示例代码:运行脚本,然后在打开的命令行上键入plot。这将绘制带有随机彩色点的窗口。每次发布plot时,它都会以下一种颜色重新绘制随机点。当焦点在matplotlib窗口上时按“c”键时的键盘事件也会执行相同的操作,但在移动鼠标之前不会触发该事件 如果这对您有效,请报告您正在使用的后端(它会在启动时打印) 下面是一个最小的工作示例。除非您在mac上使用macports python,否则需要删除第一行以便运行/usr/bin/python:Python 带键处理程序的matplotlib绘图仅在鼠标移动时更新,python,macos,matplotlib,Python,Macos,Matplotlib,我有一个交互式matplotlib窗口,当焦点在窗口上时,它由命令行和键盘输入驱动 问题是,当焦点在窗口上时,直到鼠标在屏幕上的任何位置移动,按键事件才会被触发 要运行下面的示例代码:运行脚本,然后在打开的命令行上键入plot。这将绘制带有随机彩色点的窗口。每次发布plot时,它都会以下一种颜色重新绘制随机点。当焦点在matplotlib窗口上时按“c”键时的键盘事件也会执行相同的操作,但在移动鼠标之前不会触发该事件 如果这对您有效,请报告您正在使用的后端(它会在启动时打印) 下面是一个最小的工
#!/opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7
#!/usr/bin/python
import time, os, sys
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import random
import cmd
colors = [ 'red', 'green', 'blue' ]
colorindex = 0
def key_handler(event):
global colors
global colorindex
print('Key pressed:', event.key)
sys.stdout.flush()
if event.key == 'x':
print "Exiting..."
sys.exit(0)
elif event.key == 'c':
print "changing color"
colorindex += 1
if colorindex >= len(colors):
colorindex = 0
plotfig()
def plotfig():
global fig
global ax1
global colors
global colorindex
ax1.clear()
someX = range(1,1000)
someY = []
for i in someX:
someY.append(random.randrange(0, 1000))
ax1.plot(someX, someY, '.', color=colors[colorindex], markersize=8, label="Some Values")
plt.show()
class someShell(cmd.Cmd):
intro = 'some shell. Type help or ? to list commands.\n'
prompt = 'ss> '
def do_plot(self, arg):
global colorindex
colorindex += 1
if colorindex >= len(colors):
colorindex = 0
plotfig()
def do_exit(self, arg):
'Exits SomeShell'
return True
fig = plt.figure(figsize=(12, 7))
fig.canvas.mpl_connect('key_press_event', key_handler)
ax1 = fig.add_subplot(1,1,1)
print "Using plotting backend: %s" % plt.get_backend()
plt.ion()
someShell().cmdloop()
提示:创建一个问题列表,允许人们测试案例。否则这一切都是猜测。我已经添加了完全可以工作的代码。我正在使用windows 8.1、matplotlib 2.2.2和TkAgg后端运行它。它按预期工作,只是在窗口关闭后第二次键入
plot
时抛出并出错,并说“TclError:这不是Tk应用程序”(我认为这是预期的,不是问题的一部分)。它还使用Qt4Agg作为后端,没有第二个窗口可以打开。谢谢大家的帮助。切换到TkAgg后端似乎可以解决这个问题。其他后端也可以完成这项工作,但尚未对它们进行全部测试。