好的,我是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)
答案 0 :(得分:7)
将以下内容添加到您的函数中:
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),它使解释器在最近的nolocal范围内写入变量,而不仅仅是在模块范围内。