好吧,我是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)
Run Code Online (Sandbox Code Playgroud)
下面是一些用于构建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)
Run Code Online (Sandbox Code Playgroud)
将以下内容添加到您的函数中:
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)
Run Code Online (Sandbox Code Playgroud)
Python在写入时实现名称隐藏在本地范围内.当您尝试读取全局(模块范围的变量)时,解释器会在越来越多的本地范围内查找变量名称.当您尝试编写时,会在本地范围内创建一个新变量,并隐藏全局变量.
我们添加的语句告诉解释器在写入时在全局范围内查找名称.还有一个nonlocal语句(在python 3.*中,不确定2.7),它使解释器在最接近的nolocal范围内写入变量,而不仅仅是在模块范围内.
| 归档时间: |
|
| 查看次数: |
94 次 |
| 最近记录: |