首页 > 解决方案 > 为什么我需要使用 'key_event' ?它的作用是什么?

问题描述

我有一个代码,你能帮我解释一下吗:

def key_event(e):
    global curr_pos
    global remove_data
    if e.key == "right":
        curr_pos += 1
    elif e.key == "left":
        curr_pos -= 1
    elif e.key == "d":
        remove_data.append(curr_pos)
        print(remove_data)

    else:
        return
    curr_pos = curr_pos % len(Alldata)  # This prevents index error

ax.cla()  
x = [i * step_size for i in range(len(Alldata[curr_pos]))]  # make the x-cords
ax.plot(x, np.log10(Alldata[curr_pos]))  # make the new plot
ax.set_title(curr_pos)  # Set the title to keep track of where you are in the list
fig.canvas.draw()

print("Plotting histograms for all data")
plot_histograms(Alldata)  # flatten list of lists into one long list
print("Plotting traces for each experimental run")
curr_pos = 0  # Initialise value
remove_data = []
fig = plt.figure()
fig.canvas.mpl_connect("key_press_event", key_event)
ax = fig.add_subplot(111)
ax.set_title(curr_pos)  # Set the title to keep track of where you are in the list
ax.plot([i * step_size for i in range(len(Alldata[curr_pos]))], Alldata[curr_pos])  # plot first value
plt.xlabel('$\log_{10}(G/G_0)$')
plt.ylabel('Counts')
plt.show()

为什么我需要使用 'key_event' ?它的作用是什么?为什么我需要全局变量'curr_pos'?

标签: python-3.xmatplotlibglobal-variables

解决方案


推荐阅读