我想做什么:
我正在尝试使用filedialog保存文件。保存部件工作正常,但如果单击对话框上的“取消”选择不保存,则会出现此错误。如何删除此错误
我收到的错误:
Exception in Tkinter callback
FileNotFoundError: [Errno 2] No such file or directory: ''
During handling of the above exception, another exception occurred:
xlsxwriter.exceptions.FileCreateError: [Errno 2] No such file or directory: ''
下面是我的代码:
import xlsxwriter
import tkinter as tk
import tkinter.ttk as ttk
from tkinter import filedialog
def save():
filename = filedialog.asksaveasfilename(filetypes=[("Excel files", ".xlsx .xls")],defaultextension='.xlsx')
workbook = xlsxwriter.Workbook(filename)
worksheet = workbook.add_worksheet()
worksheet.write('A1', 'Common Information')
worksheet.write('A2', 'Circumference of Tank')
worksheet.write('C2', 'Height of Tank')
worksheet.write('A3', 'Minimum Thickness of Tank')
worksheet.write('C3', 'Maximum Thickness of Tank')
workbook.close()
window = tk.Tk()
window.configure(background='white')
ws = window.winfo_screenwidth()
hs = window.winfo_screenheight()
w = 700 # width for the Tk root
h = 585 # height for the Tk root
x = (ws / 2) - (w / 2)
y = (hs / 2) - (h / 2)
window.geometry('%dx%d+%d+%d' % (w, h, x, y))
canvas = tk.Canvas(window,bg="white",width=700, height=585, highlightthickness=0)
canvas.pack()
save1 = ttk.Button(canvas, text='Save', command= lambda: save())
canvas.create_window(15, 15, window=save1, anchor=tk.NW)
window.resizable(False, False)
window.mainloop()
按下按钮后
save
函数将被调用因为当您停止选择路径时,文件名将是
(it is a
str
类型,但其长度==0)。并且workbook = xlsxwriter.Workbook(filename)
将引发异常因此,在保存xlsx文件之前,应该使用
if
语句而
save()
函数应该是:相关问题 更多 >
编程相关推荐