python - 在按键事件函数内访问/分配全局变量
问题描述
我正在尝试使用按键事件功能来滚动浏览我生成的数据图。代码应该做一个简单的检查,看看当前位置是否是一个有效的索引,然后在给定的击键时更新 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 才能像这样访问它?
解决方案
在您给出的代码curr_pos
中,被定义为范围内的局部变量test_key()
,而不是全局范围。考虑以下简单示例:
def a():
i = 0
def b():
print(i)
b()
a()
这将毫无错误地工作,因为它引用了在 .范围内声明print(i)
的变量。现在如果我们这样做i
a()
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()
其中任何一个都可以正常工作
推荐阅读
- build - 如何在 Azure 开发操作中设置构建管道
- javascript - 字符串分数到数字
- mule - Mule Anypoint studio Kafka 连接器 - 消费者无法接收消息
- c# - 每当我射击子弹时如何只播放一次动画(闪光动画)
- python - 测量金属零件孔的直径图片,用远心、单色相机和opencv拍摄
- python - 给定名称列表,搜索文本文件,将找到名称的整行保存到新变量中
- python - 在 ubuntu 上的 Atom 中运行 python3 代码的问题
- html5-canvas - 如何在fabricjs中增加移动设备上的触摸区域控制点(不增加控制点的显示大小)?
- angular - 动态创建的模块和组件无权访问父注入器
- c++11 - 模板参数扣除/替换失败错误,同时迭代两个映射时