Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python程序在运行时无法识别全局变量_Python_Python 3.x_Tkinter_Spyder - Fatal编程技术网

Python程序在运行时无法识别全局变量

Python程序在运行时无法识别全局变量,python,python-3.x,tkinter,spyder,Python,Python 3.x,Tkinter,Spyder,因此,我试图在Spyder中运行下面的程序,并且经常遇到以下反复出现的错误: >Exception in Tkinter callback >>Traceback (most recent call last): >>>File "C:\ProgramData\Anaconda3\lib\tkinter\__init__.py", line 1705, in __call__ >>>>return self.func(*ar

因此,我试图在Spyder中运行下面的程序,并且经常遇到以下反复出现的错误:

>Exception in Tkinter callback
>>Traceback (most recent call last):
  >>>File "C:\ProgramData\Anaconda3\lib\tkinter\__init__.py", line 1705, in __call__
    >>>>return self.func(*args)
  >>>>>File "C:/Users/WYoung3/Training Team Flight Program v.5.py", line 128, in TAFLIGHT
    >>>>>>outputTAF (str(oppath))
  >>>>>>>File "C:/Users/WYoung3/Training Team Flight Program v.5.py", line 98, in outputTAF
    >>>>>>>>OP0_df.to_excel(writer, sheet_name='Origin-Dest. Airfare (Data)')
NameError: name 'OP0_df' is not defined
如果我单独运行定义的函数,结果将完全按照我的预期工作,但每次运行整个程序都会导致该错误。我可能做错了什么

import pandas as pd
import numpy as np

import openpyxl
from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.worksheet.table import Table, TableStyleInfo


"""
Input
"""
# inputTAF(r'//data4/users2/wyoung3/My Documents/Salmann Project/test/1.xlsx')                 
def inputTAF (Fdata):
    #for each file
#   open tab 6
#       Pull all data from row 4 onward for column C (Airfare)
#       pull all data from row 4 onward from clumn B (Country)
    stop_df = pd.read_excel(Fdata, sheet_name="6. Actual Expenses",skiprows=[0,1],usecols=[0])
    stop = stop_df.loc[stop_df['Name'] == 'Total'].index[0]
    airfare_df = pd.read_excel(Fdata, sheet_name="6. Actual Expenses",skiprows=[0,1],usecols=[1,2])
    airfare_df.head()
    airfare_df = airfare_df.iloc[:stop]
    airfare_df.dropna(axis=0, how='any', thresh=None, subset=None, inplace=True)
    print(airfare_df)
    print('airfare_done')

#   open tab 4
#       Pull the following entries:
#           Estimated Expenses: L26, L29, L31, L33-L36, L38
#           Actual Expenses: N26, N29, N31, N33-N36, N38
#           Convert list of tuples into dataframe

    workbook = load_workbook(Fdata, data_only=True)
    workbook.sheetnames
    sheet=workbook.worksheets[4]
    l4=sheet["L23:N39"]
    vl4 = [[l4[3][0].value,l4[3][2].value], [l4[5][0].value,l4[5][2].value], [l4[8][0].value,l4[8][2].value], [l4[6][0].value,l4[6][2].value],[l4[13][0].value,l4[13][2].value], [l4[4][0].value,l4[4][2].value],[l4[15][0].value,l4[15][2].value]]
    df_vl4 = pd.DataFrame(vl4, columns = ['Estimated', 'Actual'])
    df_vl4.head()
    df_vl5=df_vl4.T
    df_vl5.rename(columns={0 :'Airfare', 1 :'Hotel (086)', 2 :'Meals (084)', 3 :'Subsistence (087)', 4 :'Conference Materials', 5 :'Travel Allowance (085)', 6 :'Other Incidentals (039)'                       
}, inplace=True)
    df_vl5.reset_index(drop=True, inplace=True)
    print(df_vl5)
#   open table 0
#       Pull the following cells: B3-B8, B10, B13-B15,B20, B28
    basic_df = pd.read_excel(Fdata, sheet_name="0. Event Data",skiprows=[0],usecols=[1])
    basic_df.head()
    basic_df=basic_df.filter(items = [0,1,2,3,4,5,7,10,11,12,17,25], axis =0)

# append output dataframes
    airfare_df.insert(0,'Destination',basic_df.iat[4,0])
    airfare_df.insert(0,'Mission ID', basic_df.iat[7,0])
    airfare_df.insert(0,'DM',basic_df.iat[11,0])

    global OP0_df
    OP0_df = pd.DataFrame({'DM':[],'Mission ID':[], 'Destination':[], 'Country':[], 'Airfare':[]})
    global OP1_df
    OP1_df = pd.DataFrame({'Mission ID' :[], 'Country Name' :[], 'Start Date' :[], 'End Date' :[], 'DM Folder #' :[], 'Airfare' :[], 'Hotel (086)' :[], 'Meals (084)' :[], 'Subsistence (087)' :[], 'Conference Materials' :[], 'Travel Allowance (085)' :[], 'Other Incidentals (039)':[]})

    global OP2_df
    OP2_df = pd.DataFrame({'Mission ID' :[], 'Country Name' :[], 'Start Date' :[], 'End Date' :[], 'DM Folder #' :[], 'Airfare' :[], 'Hotel (086)' :[], 'Meals (084)' :[], 'Subsistence (087)' :[], 'Conference Materials' :[], 'Travel Allowance (085)' :[], 'Other Incidentals (039)':[]})


    df_vl5.insert(0,'DM', basic_df.iat[11,0])
    df_vl5.insert(0,'End Date',basic_df.iat[3,0])
    df_vl5.insert(0,'Start Date',basic_df.iat[2,0])
    df_vl5.insert(0,'Country Name',basic_df.iat[4,0])
    df_vl5.insert(0,'Mission ID', basic_df.iat[7,0])
    a_df = df_vl5.iloc[1]
    est_df = df_vl5.iloc[0]

    OP1_df = OP1_df.append(a_df, ignore_index=True) 
    OP2_df = OP2_df.append(est_df, ignore_index=True)  


"""
Output
"""
# outputTAF(r'//data4/users2/wyoung3/My Documents/Salmann Project/Output/Complete Database (V. Wesley).xlsx')
def outputTAF (Foutput):

    from time import localtime, strftime


    T = strftime('--%m-%d-%Y',localtime())
    with pd.ExcelWriter(Foutput+'\output'+T+'.xlsx', datetime_format='mmm d yyyy') as writer:
        OP0_df.to_excel(writer, sheet_name='Origin-Dest. Airfare (Data)')
        OP1_df.to_excel(writer, sheet_name='Quantitative (Merged Fund)')
        OP2_df.to_excel(writer, sheet_name='Estimates File')


    number_of_runs = str(len(IP))+" files have been processed"
    runlabel=Label(root, text=number_of_runs)
    runlabel.pack()
"""
Run
"""

#Instruct program to iterate over each file in a directory
import pathlib

# ipfilepath = pathlib.Path(r'\\data4\users2\wyoung3\My Documents\Salmann Project\test') #directory where files will be kept


# oppath = pathlib.Path(r'\\data4\users2\wyoung3\My Documents\Salmann Project\test\source.xlsx'), oppath.parents[0] #path to output file

def TAFLIGHT():
    global IP
    IP = [x for x in ipfilepath.glob('*') if not x.name == oppath.name]
    i = 1
    if i is not len(IP):
        for filepath in IP:
            inputTAF (str(filepath))
            i = i + 1

    else:
        outputTAF (str(oppath))

    pass


'''
GUI
'''

from tkinter import *
from tkinter import filedialog
import pathlib

root = Tk()
root.title('Training Team Flight Program')

root.geometry('320x200')

frame =LabelFrame(root,bg='Blue',height=100, width=30, padx=5,pady=5)
frame.pack(padx=10,pady=40)
frame2 = LabelFrame(frame, padx=5,pady=7.4)
frame2.grid(row=0,column=0)
frame3 = LabelFrame(frame)
frame3.grid(row=0,column=1)

def click1():
    root.directory = filedialog.askdirectory()
    outputbutton['state']='normal'
    print(root.directory)
    global ipfilepath
    ipfilepath = pathlib.Path(root.directory)
    print(ipfilepath)

def click2():
    root.directory = filedialog.askdirectory()
    Runbutton['state']='normal'
    print(root.directory)
    global oppath
    oppath = pathlib.Path(root.directory)
    print(oppath)
    print('ipfilepath: ', ipfilepath)


# Creating a label widget
inputlabel = Label(frame2, bg='red', text='Costing Data Directory' )
inputbutton = Button(frame3, text='click', command = click1)

outputlabel = Label(frame2, bg='yellow', text='Output File' )
outputbutton = Button(frame3, text='click', command = click2, state = 'disabled')

Runlabel = Label(frame2, bg='Green', text='Run Program' )
Runbutton = Button(frame3, text='click', command = TAFLIGHT, state = 'disabled')

# Shoving it onto the screen
inputlabel.grid(row=0, column=0)
inputbutton.grid(row=0, column=1)

outputlabel.grid(row=1, column=0)
outputbutton.grid(row=1, column=1)

Runlabel.grid(row=2, column=0)
Runbutton.grid(row=2, column=1)

root.mainloop()

根据您显示的代码,您可以在
inputAF
中定义
OP0_-df
,但在调用
outputAF
之前,您的代码可能不会运行
inputAF
,因此
OP0_-df
永远不会被定义。

您在
inputAF()
中使用的是
全局OP0_-df
,使
OP0_df
成为该函数中的(未定义)局部变量。与其他全局变量相同。提示:尝试删除全局变量,并将其作为参数传递给函数。在一个函数中将变量声明为全局变量不会使它在另一个函数中可见。@JohnGordon:您不正确。一个函数可以看到在另一个函数中定义的全局函数,而无需将其声明为全局函数。全局变量随处可见,这就是它们被称为全局变量的原因。@BryanOakley今天我学到了一些东西。谢谢你的更正!答案在我上面提到的问题中。