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()
请问大神,以下代码为什么在单击打开时就自动打开文件夹,且再次单击打开就无效了,求助
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- 「已注销」 2023-06-02 07:12关注
- 在
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("输入任意键退出")
语句删除。
解决 无用评论 打赏 举报 编辑记录 - 在
悬赏问题
- ¥15 C#算法问题, 不知道怎么处理这个数据的转换
- ¥15 YoloV5 第三方库的版本对照问题
- ¥15 请完成下列相关问题!
- ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
- ¥15 求daily translation(DT)偏差订正方法的代码
- ¥15 js调用html页面需要隐藏某个按钮
- ¥15 ads仿真结果在圆图上是怎么读数的
- ¥20 Cotex M3的调试和程序执行方式是什么样的?
- ¥20 java项目连接sqlserver时报ssl相关错误
- ¥15 一道python难题3