好的,我是 C、VisualBasic 和 Fortran 程序员(是的,我们仍然存在)。我缺少 Python 3.2 的范例。在下面的代码中,为什么我的函数 start_DAQ
看不到我所有的全局变量?该函数似乎为 do_DAQ
、data_index
和 start_time
创建了自己的局部变量,但不是 store_button
。我已经阅读了对几个类似问题的答复,但仍然不明白。我想我可以使用全局声明,但被告知这是不好的做法。
#-----------------------------------------------------------------------
# define my globals
#-----------------------------------------------------------------------
#make an instance of my DAQ object and global start_time
myDaq = DAQ_object.DAQInput(1000,b"Dev2/ai0")
start_time = time.time()
#build data stuctures and initialize flags
time_data = numpy.zeros((10000,),dtype=numpy.float64)
volt_data = numpy.zeros((10000,),dtype=numpy.float64)
data_queue = queue.Queue()
data_index = 0
do_DAQ = False
#-----------------------------------------------------------------------
# define the functions associated with the buttons
#-----------------------------------------------------------------------
def start_DAQ():
do_DAQ = True
data_index=0
start_time = time.time()
store_button.config(state = tk.DISABLED)
下面是一些用于构建 GUI 的代码
#make my root for TK
root = tk.Tk()
#make my widgets
fr = tk.Frame()
time_label = tk.Label(root, text="not started")
volt_label = tk.Label(root, text="{:0.4f} volts".format(0))
store_button = tk.Button(root, text="store Data", command=store_DAQ, state = tk.DISABLED)
start_button = tk.Button(root, text="start DAQ", command=start_DAQ)
stop_button = tk.Button(root, text="stop DAQ", command=stop_DAQ)
exit_button = tk.Button(root, text="Exit", command=exit_DAQ)
最佳答案
将以下内容添加到您的函数中:
def start_DAQ():
global do_DAQ
global data_index
global start_time
do_DAQ = True
data_index=0
start_time = time.time()
store_button.config(state = tk.DISABLED)
Python 在写入时将名称隐藏在本地范围内。当您尝试读取全局(模块作用域变量)时,解释器会在越来越多的非局部作用域中查找变量名称。当您尝试写入时,会在本地范围内创建一个新变量,并隐藏全局变量。
我们添加的语句告诉解释器在写入时在全局范围内查找名称。还有一个 nonlocal
语句(在 python 3.* 中,不确定 2.7)它让解释器写入最近的非本地范围内的变量,而不仅仅是在模块范围内。
关于python - 为什么我的函数只能看到我的一些全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14023861/