请问大神,以下代码为什么在单击打开时就自动打开文件夹,且再次单击打开就无效了,求助

from tkinter import *
import os
import win32com.client as win32
import easygui as eg

def save_as_xlsx(fname):
    excel = win32.DispatchEx('Excel.Application')
    wb = excel.Workbooks.Open(fname)
    wb.SaveAs(fname + "x", FileFormat=51)  # FileFormat = 51 is for .xlsx extension
    wb.Close()  # FileFormat = 56 is for .xls extension
    excel.Application.Quit()

def pick_package():
    # 打开windows窗口,选择一个文件夹
    return eg.diropenbox()

def xls_to_xlsx():
    package = pick_package()
    files = os.listdir(package)
    for fname in files:
        if fname.endswith(".xls"):
            print(fname + "正在进行格式转换,请稍后~")
            try:
                currentfile = package + "\\" + fname
                save_as_xlsx(currentfile)
                print(currentfile + "格式转换完成,O(∩_∩)O哈哈~")
            except:
                print(currentfile + "格式转换异常,┭┮﹏┭┮")
        else:
            print("跳过非xls文件:" + fname)
    # input("输入任意键退出")
root=Tk()
root.title("xls_to_xlsx")
root.geometry("300x200")
label1=Label(root,text="请打开文件夹后即开始转换……")
label1.pack()
OpenBtn=Button(root,text="打开",width=10,command=xls_to_xlsx())
OpenBtn.pack(side=LEFT)
CloseBtn=Button(root,text="确定",width=10,command=root.destroy)
CloseBtn.pack(side=LEFT)
root.mainloop()

 

  • OpenBtn=Button(root,text="打开",width=10,command=xls_to_xlsx()) 中,command 参数应该传递函数名而非函数的返回值。应为command=xls_to_xlsx
  • except: 子句中,应该至少捕捉一种异常类型并给出相应的处理方式,避免发生未知错误导致程序崩溃。
  • input("输入任意键退出") 语句中,应该将其注释掉或者删除,因为其在界面上没有任何实际作用。

完整代码如下

import os
import win32com.client
from tkinter import *
from tkinter import filedialog


def xls_to_xlsx():
    file_path = filedialog.askopenfilename()
    excel = win32com.client.Dispatch("Excel.Application")
    try:
        excel.DisplayAlerts = False
        wb = excel.Workbooks.Open(file_path)
        wb.SaveAs(os.path.splitext(file_path)[0]+".xlsx", FileFormat=51)
        wb.Close()
        excel.Quit()
    except Exception as e:
        print("转换失败,错误信息:{}".format(str(e)))


root = Tk()
root.title("Excel 格式转换器")
OpenBtn = Button(root, text="打开", width=10, command=xls_to_xlsx)
OpenBtn.pack(pady=10)
root.mainloop()
  • command 参数传递了函数名 xls_to_xlsx
  • except 子句中增加了异常捕捉和提示信息;
  • input("输入任意键退出") 语句删除。