Reputation: 165
Ok, I'm a C, VisualBasic, and Fortran programmer (yes we do still exist). I am missing a paradigm piece of Python 3.2. In the code below, why doesn't my function start_DAQ
see all my globals? The function seems to make its own local variables for do_DAQ
, data_index
, and start_time
, but not store_button
. I've read the response to several similar questions and still don't get it. I imagine I could use a global statement, but was told that that was bad practice.
#-----------------------------------------------------------------------
# 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)
below this is some code for building a 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)
Upvotes: 2
Views: 109
Reputation: 170084
Add the following to your function:
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 implements name hiding in local scope upon write. When you try to read a global(module scoped variable), the interpreter looks for the variable name in increasingly no-local scopes. When you attempt to write, a new variable is created in local scope, and it hides the global.
The statement we added, tells the interpreter to look for the name in global scope upon write. There is also a nonlocal
statement (in python 3.*, not sure about 2.7) which has the interpreter write to the variable in the closest nolocal scope, rather than just in module scope.
Upvotes: 7