如何根据用户在下拉菜单中的响应来定义使用哪个文件?

2024-04-23 07:36:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个很好的GUI,用户可以在其中输入一个文件,其中包含一些有关将被折旧的资产的信息。但是,折旧方法因国家不同而不同。因此,我还添加了一个下拉按钮,以便用户可以选择国家

这是我到目前为止的代码(没有导入):

@Gooey(program_name="DEPRECIATION")
def parse_args():
    parser = GooeyParser()

    parser.add_argument('Fixed_Assets_File',
                        action='store',
                        widget='FileChooser',
                        help="Excel file with all fixed assets to depreciate")

    parser.add_argument('Country',
                        widget='Dropdown',
                        choices=['Germany','France','Norway',
                                 'Poland','UK','NL','Sweden',
                                 'Russia','Spain',],
                        help="Choose the country")

    parser.add_argument('Output_File_Name',
                        action='store',
                        help="Name of the output file with .xlsx")

    args = parser.parse_args()
    return args
def country_selection(mapping_file):
    if 'Germany' in args.Country:
        mapping = pd.read_excel("germany_depreciation.xlsx")
    elif 'France' in args.Country:
        mapping = pd.read_excel("france_depreciation.xlsx")
    elif 'Norway' in args.Country:
        mapping = pd.read_excel("norway_depreciation.xlsx")
    elif 'Poland' in args.Country:
        mapping = pd.read_excel("poland_depreciation.xlsx")
    elif 'UK' in args.Country:
        mapping = pd.read_excel("uk_depreciation.xlsx")
    elif 'NL' in args.Country:
        mapping = pd.read_excel("nl_depreciation.xlsx")
    elif 'Sweden' in args.Country:
        mapping = pd.read_excel("sweden_depreciation.xlsx")
    elif 'Russia' in args.Country:
        mapping = pd.read_excel("russia_depreciation.xlsx")
    elif 'Spain' in args.Country:
        mapping = pd.read_excel("spain_depreciation.xlsx")

if __name__ == '__main__':
    args = parse_args()
    assets = args.Fixed_Assets_File
    country = args.Country
    print("You chose", country)

您可能已经注意到,每个国家都有一个主文件,其中包含所有必要的信息和资产的不同类别。我已经有了要为公式/折旧计算实现的代码。我可以复制并粘贴到每个if语句中,但这会使代码非常长

有没有办法告诉Gooey/Python根据用户在下拉按钮中选择的国家选择要导入的文件

例如:如果选择波兰,则忽略所有其他主文件,只导入波兰并将其定义为“映射”

ps:当我说主文件时,我指的是从excel导入的文件,格式为:nameofCountry_detaption.xlsx


Tags: 文件用户inparserreadargs国家xlsx
1条回答
网友
1楼 · 发布于 2024-04-23 07:36:32

您可以创建一个dict,将国家链接到相应的主文件

country_mapping = {
    'Germany': 'germany_depreciation.xlsx',
    'France': 'france_depreciation.xlsx',
    # other countries
}

然后你可以打电话:

mapping = pd.read_excel(country_mapping[args.Country])

然后可以删除函数country_selection()

您还可以使用country_mappingdict通过调用country_mapping.keys()来填充解析器中的国家选项

相关问题 更多 >