little_fat123 2020-08-07 21:15 采纳率: 0%
浏览 703

请教大神如何使用tkinter选择文件夹路径然后加以使用?

我弄了一个将文档中excel表合并的小程序,在用tkinter设计UI的时候一直报错,貌似主要问题在于文件夹地址,前面selectPath()函数用askdirectory()选择确定文件夹路径后,在combine()函数中想使用前面的文件夹地址不成功,
content= os.listdir(path.get())
excelPath = os.path.join(path.get(), content[y])
这两个地址抓取有问题。
请教一下大神该怎么修正?感谢感谢!

from tkinter import *
from tkinter.filedialog import askdirectory
import pandas as pd
from pandas import Series, DataFrame
import os

root = Tk()
path = StringVar()
root.geometry('520x250') #设置窗口大小
#root.resizable(0, 0) # 窗口大小固定

class mainwork():
def selectPath():
path_ = askdirectory()
path.set(path_)

label1=Label(root,text = "目标路径:").grid(row = 0, column = 0)
entry=Entry(root, textvariable = path,width=40)
entry.grid(row =0, column =1)
Button(root, text = "路径选择", command = selectPath).grid(row = 0, column =2)
label2=Label(root,textvariable =path,justify=LEFT,height=5,width=40)
label2.grid(row =5, column =1)    

def combine():
    content= os.listdir(path.get())  
    #print(content)  #打印文件夹中的文件名称
    #print(len(content))
    y=0
    b=[]#添加文件名称的行号
    c=1
    total=pd.DataFrame(columns=['行'])
    filename=[]
    for i in range(30):
        excelPath = os.path.join(path.get(), content[y]) #拼接路径
        data2=pd.read_excel(excelPath) 
        for i in range(data2.shape[0]):
            filename.append(content[y])
        kk1=pd.DataFrame(data2)
        kk1['行']=filename
        #print(kk1.shape)
        total=total.append(kk1)  
        y=y+1
        filename.clear()
    #print(filename)
    #df = pd.read_excel(excelPath)
    #print(df)
    excelPath2 = os.path.join(path.get(), '汇总数据.xls') #拼接路径
    total.to_excel(excelPath2)
    print('合并完成')

Button(root, text = "合并", command = combine()).grid(row = 5, column =2)  

root.mainloop()

  • 写回答

2条回答 默认 最新

  • threenewbee 2020-08-07 21:40
    关注
    评论

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型