python - 如何在 Python 中为用户定义的函数添加计数器?
问题描述
>>> Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Maximillian\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:\Python-koding\steinsakspapir.py", line 64, in scissors
botwin += 1
UnboundLocalError: local variable 'botwin' referenced before assignment
-尝试从其余代码中删除 botwin 和 youwin -尝试使用 youwin = youwin + 1
def scissors():
bot = random.randint(1,3)
user = 3
if user == bot:
printfuver = ("Stalemate, booth players choose scissors")
printfu = Label(lowerframe, text=printfuver, fg="blue")
printfu.pack()
if user == 3 and bot == 1:
printfuver = ("Rock crushes scissors, bot win! ")
printfu = Label(lowerframe, text=printfuver, fg="red")
printfu.pack()
botwin += 1
if user == 3 and bot == 2:
printfuver = ("Scissors cut paper, you win! ")
printfu = Label(lowerframe, text=printfuver, fg="green")
printfu.pack()
youwin += 1
只希望 botwin 在每次运行函数后增加 1 的值。
提前致谢
解决方案
除了代码中的缩进错误之外,这可能是一个范围问题。检查以确保您botwin = 0
的代码中有或类似的东西。如果该代码在函数中或超出全局范围,请将其放在代码的顶部。然后,在所有引用它的函数中,按照此处global botwin
的说明放在函数的开头。
我希望这可以帮助你。
推荐阅读
- r - 拟合优度统计 Tobit 模型
- javascript - 如何在回调函数NodeJS之外获取变量值
- python-3.x - 使用 time.sleep 在 python 上进行线程化
- python - 如何在 python 中进行特定组合?
- c# - Xamarin.Forms Android 上的 HttpClient 无响应和冻结(棱镜)
- python - 使用 Pytorch API 和 Fast-ai 进行分类的训练结果不同
- reactjs - 使用上下文消费者从 Firebase 中检索 UID
- ios - 如何在 iOS 中获取人类友好的当前本地语言名称?
- reactjs - firebase中usestate保存数据的问题
- java - 我正在尝试使用@OneToOne 作为双向映射来映射实体,但出现奇怪的异常