我试着在Python 3.7中使用Matplotlib来获取一系列坐标在一个字典(或List)中的位置,我想用鼠标左键SHIFT来获取当前的位置,并将它们存储在临时字典中。我想用鼠标左键SHIFT来获取当前的位置,并将它们存储在一个临时字典中。然后我使用CONTROL+鼠标左键将临时字典添加到永久字典中。代码见附件。当我选择一个座标时,将其添加到永久字典中并不麻烦。我甚至可以多次添加同一个坐标。但是,每当我试图获得一个新的临时协调器时,它就会抹去永久字典中所有以前保存的项目,除了最后一个。我不想在列表中使用追加,因为我可能想修改以前存储的数据(这里不确定)。有什么办法吗?
from matplotlib.backend_bases import MouseButton
import matplotlib.pyplot as plt
import numpy as np
tmpDict={}
PermDict={}
i=0
t = np.arange(0.0, 1.0, 0.01)
s = np.sin(2 * np.pi * t)
fig, ax = plt.subplots()
ax.plot(t, s)
def on_click(event):
global tmpDict, PermDict, i
# get the x and y pixel coords
x, y = event.x, event.y
if event.key=='shift':
if event.button is MouseButton.LEFT:
ax = event.inaxes # the axes instance
print('Data set: %d, data coords %f %f' % (i, event.xdata, event.ydata))
tmpDict={'x':event.xdata, 'y':event.ydata}
print(tmpDict)
print(PermDict)
if event.key=='control':
if event.button is MouseButton.LEFT:
ax = event.inaxes # the axes instance
PermDict={str(i):tmpDict}
print(PermDict)
i+=1
plt.connect('button_press_event', on_click)
plt.show()
我想你要做的是
PermDict[str(i)] = tmpDict
tmpDict = {}
而不是 PermDict={str(i):tmpDict}