所以我在我的一个项目中编写了这段代码,并将 n 定义为布尔值 True。然后,我用它来制作暂停/恢复按钮的切换案例。出于某种原因,我收到了在 if 语句中使用 n 的错误,然后据称将它分配到 if 和 else 代码中,尽管我已经将它分配在整个函数之上。
有人可以解释这个错误吗?也许建议一种方法来解决它?
n = True
def pauseresume():
if n:
pauseb.configure(text="Resume")
n = False
else:
pauseb.configure(text="Pause")
n = True
答案 0 :(得分:0)
如果要使用全局变量,需要通过global
关键字明确使用。
n = True
def pauseresume():
global n
pauseb.configure(text="Resume" if n else "Pause")
n = not n # switch to other bool value
答案 1 :(得分:0)
不能在函数中使用全局变量 解决方案:
def pauseresume():
global n
if n:
...