全局变量在Python Tkinter中充当局部变量

时间:2018-09-30 21:20:39

标签: python tkinter

我正在尝试在tkinter中创建一个秒表,并且我需要一个counter变量才能做到这一点。但是,问题在于,即使我将其声明为全局变量,该变量也充当局部变量。

这是我的剧本:

import tkinter as tk

root = tk.Tk()


global counter
counter = 0


def go():
    label.config(text=str(counter))
    counter+=1
    root.after(1000,go2)
def go2():
    label.config(text=str(counter))
    counter+=1
    root.after(1000,go)
def stop():
    label.config(text=str(0))


gobutt = tk.Button(text = "Go", command = lambda: go())
stopbutt = tk.Button(text = "Stop", command = lambda: go2())
gobutt.pack()
stopbutt.pack()

label = tk.Label(text = "0")
label.pack()

root.mainloop()

这是我的错误消息:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 1699, in __call__
    return self.func(*args)
  File "/Users/MinecraftMaster/Desktop/Python/Tests/TkinterTest/Tkinter Test.py", line 29, in <lambda>
    gobutt = tk.Button(text = "Go", command = lambda: go())
  File "/Users/MinecraftMaster/Desktop/Python/Tests/TkinterTest/Tkinter Test.py", line 18, in go
    label.config(text=str(counter))
UnboundLocalError: local variable 'counter' referenced before assignment

1 个答案:

答案 0 :(得分:0)

您应该将global counter放在函数定义中,以便将在函数内部引用的counter用作全局范围内定义的那个

counter = 0

def go():
    global counter
    label.config(text=str(counter))
    counter+=1
    root.after(1000,go2)

def go2():
    global counter 
    label.config(text=str(counter))
    counter+=1
    root.after(1000,go)