python - 带有全局变量和局部变量声明的python错误,在声明后更改变量值
问题描述
所以我不断收到错误:UnboundLocalError: local variable 'old_result' referenced before assignment
,我不知道为什么。我通常用 javascript 编写代码,所以我是 python 的新手,但我认为它是因为我再次在函数中声明 old_result,但我想让它成为全局的,只是在函数中更改它的值。无论如何我可以解决这个问题?
from PIL import Image, ImageGrab
import pytesseract
import threading
import winsound
old_result = 100
def ocrit():
threading.Timer(5.0, ocrit).start()
img = ImageGrab.grab(bbox=(110,70,250,200))
result = pytesseract.image_to_string(img,
lang='eng')
print(result)
new_result = int(result)
if new_result < old_result:
print("play da music")
old_result = new_result
ocrit()
解决方案
在函数中,声明:
global old_result
推荐阅读
- javascript - 文件未缓存在 ServiceWorker 中
- css - SVG 超过了弹性项目容器
- flutter - 可增长数组的“状态不佳:元素太多”,但整个堆栈都在 Flutter 内部,没有我的任何代码
- mapbox - Mapbox GL JS V2 中 3D 地形的自定义 DEM
- matlab - 用 MATLAB 解决概率问题
- database - 使用阿姆斯壮公理证明 AD->B
- ios - 异步调用导致 EXC_BAD_INSTRUCTION 崩溃
- android - 在使用 Navigation 组件和 Kotlin 进行导航时向 backstack 添加额外的片段
- ubuntu - Makefile - 在循环中使用数学
- postgresql - 使用 AWS RDS PostgreSQL 数据库移动数据