Python Tkinter file dialog

我正在编写一个以tkinter为gui的小型python程序来选择excel文件并打开它们,我达到了可以选择文件并打开它们的地步。我的问题是当用户不选择文件并单击取消它产生和错误时。如果用户没有在tkinter文件对话框中选择文件,如何继续编码?


import pandas as pd

import tkinter as tk

from tkinter import filedialog

import openpyxl

from openpyxl import load_workbook

import os

import sys

import numpy as np



root = tk.Tk()


canvas1 = tk.Canvas(root, width=300, height=300, bg='lightsteelblue')

canvas1.pack()



def getExcel():

    global df


    import_file_path = filedialog.askopenfilename()

    df = pd.read_excel(import_file_path)

    book = load_workbook(import_file_path)

    writer = pd.ExcelWriter(import_file_path, engine='openpyxl')

    writer.book = book

    x3 = (df.loc[(df['Var Cost'] < -500) | (df['Var Cost'] > 500)])

    df3 = pd.DataFrame(x3)

    df3.to_excel(writer, sheet_name='VarianceSorted')

    writer.save()

    writer.close()

    command = import_file_path

    os.system(command)



def end():

    sys.exit()



browseButton_Excel = tk.Button(text='Import Excel File', command=getExcel, bg='green', fg='white', font=('helvetica', 12, 'bold'))

canvas1.create_window(150, 150, window=browseButton_Excel)


quitbutton = tk.Button(text='Quit', command=end, bg='green', fg='white', font=('helvetica', 12, 'bold'))

canvas1.create_window(200, 200, window=quitbutton)


root.mainloop()


暮色呼如
浏览 121回答 1
1回答

尚方宝剑之说

在继续之前,您应该检查返回的:import_file_pathdef&nbsp;getExcel():&nbsp;&nbsp;&nbsp;&nbsp;global&nbsp;df &nbsp;&nbsp;&nbsp;&nbsp;import_file_path&nbsp;=&nbsp;filedialog.askopenfilename()&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;import_file_path: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;df&nbsp;=&nbsp;pd.read_excel(import_file_path) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;book&nbsp;=&nbsp;load_workbook(import_file_path) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;writer&nbsp;=&nbsp;pd.ExcelWriter(import_file_path,&nbsp;engine='openpyxl') &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;writer.book&nbsp;=&nbsp;book &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;x3&nbsp;=&nbsp;(df.loc[(df['Var&nbsp;Cost']&nbsp;<&nbsp;-500)&nbsp;|&nbsp;(df['Var&nbsp;Cost']&nbsp;>&nbsp;500)]) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;df3&nbsp;=&nbsp;pd.DataFrame(x3) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;df3.to_excel(writer,&nbsp;sheet_name='VarianceSorted') &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;writer.save() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;writer.close() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;command&nbsp;=&nbsp;import_file_path &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;os.system(command)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python