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



所以我试图在Spyder中运行下面的程序,但经常面临以下重复出现的错误:

>Exception in Tkinter callback
>>Traceback (most recent call last):
>>>File "C:ProgramDataAnaconda3libtkinter__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'\data4users2wyoung3My DocumentsSalmann Projecttest') #directory where files will be kept

# oppath = pathlib.Path(r'\data4users2wyoung3My DocumentsSalmann Projecttestsource.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()

根据您显示的代码,您在inputTAF中定义了OP0_df,但您的代码在调用outputTAF之前可能不会运行inputTAF,因此OP0_df永远不会被定义。

最新更新