首页 > 解决方案 > 在按键事件函数内访问/分配全局变量

问题描述

我正在尝试使用按键事件功能来滚动浏览我生成的数据图。代码应该做一个简单的检查,看看当前位置是否是一个有效的索引,然后在给定的击键时更新 curr_pos 的值。

     def test_key():
        import matplotlib.pyplot as plt

        curr_pos=0
        dt = 1
        numtimes = 5

        def key_event(e):
            global curr_pos

            if curr_pos - dt <= 0:
                if e.key == "right":
                    curr_pos = curr_pos + dt
                else:
                    return
            elif curr_pos + dt >= numtimes:
                if e.key == "left":
                    curr_pos = curr_pos - dt
                else:
                    return
            else:
                if e.key == "right":
                    curr_pos = curr_pos + dt
                elif e.key == "left":
                    curr_pos = curr_pos - dt
                else: 
                    return
                ax.cla()
                ax.plot([1,1,1], [1,1,1])
                ax.title('time index: '+str(curr_pos))
                fig.canvas.draw()
        fig = plt.figure()
        fig.canvas.mpl_connect('key_press_event', key_event)
        ax = fig.add_subplot(111)
        ax.plot([1,1,1], [1,1,1])
        plt.show()

代码被简化了很多,显然我不想在这里画一堆。我从文件中读取数据,并且不想在上传这个问题时处理这个问题。无论如何,curr_pos 最终将用于选择将要绘制的数据的索引。这应该重新创建我遇到的错误,但它是:

Traceback (most recent call last):
  File "/home/ckswee/.local/lib/python3.6/site-packages/matplotlib/cbook/__init__.py", line 216, in process
    func(*args, **kwargs)
  File "/home/ckswee/Documents/strahl/test_key.py", line 18, in key_event
    if curr_pos - dt <= 0:
NameError: name 'curr_pos' is not defined

我是否必须以不同的方式定义我的变量 curr_pos 才能像这样访问它?

标签: pythonmatplotlibcanvasglobal-variables

解决方案


在您给出的代码curr_pos中,被定义为范围内的局部变量test_key()而不是全局范围。考虑以下简单示例:

def a():
    i = 0
    def b():
        print(i)
    b()

a()

这将毫无错误地工作,因为它引用了在 .范围内声明print(i)的变量。现在如果我们这样做ia()

def a():
    i = 0
    def b():
        global i
        print(i)
    b()

a()

print(i)现在正在寻找i在全局范围内声明的一个,但没有找到它会引发错误。正确的声明是

def a():
    global i
    i = 0
    def b():
        global i
        print(i)
    b()

a()

或者

I = 0
def a():
    def b():
        global i
        print(i)
    b()

a()

其中任何一个都可以正常工作


推荐阅读