使用python tkinter对.docx进行一些操作

时间:2017-10-31 20:14:55

标签: python-3.x tkinter filepath docx glob

我创建了一个脚本,用于从用户获取路径名并执行一些.docx操作。当我运行脚本时,它给出该文件夹中的.docx总数,但它不适用于表计数。我不知道我在 tkinter 中使用了正确的代码。我尝试了 pathlib os.path ,但它不起作用。

这是我的代码:

    import os
    import glob
    import os.path
    from docx import Document

    from tkinter import *
    def print_input():

#To print how many files with .docx extension in the folder 

        mypath = text_entry.get()
        files=0
        for name in os.listdir(mypath):
            if name.endswith('.docx'):
              files=files+1
        print("Total No of Files:",files)

        #To read the .docx and print how many tables in that 

        table=0
        for name in glob.glob('/*.docx'):
          doc=Document(name)
          for t in doc.tables:
            for ro in t.rows:
             if ro.cells[0].text=="ID" :
                table=table+1
          print("Total Number of Tables: ", table)

    root = Tk()
    Label(root, text="Enter Path").grid(row=0)

    text_entry = Entry(root)
    text_entry.grid(row=1, column=0)
    text_entry.config(background="yellow", foreground="blue")
    Button(root, text='Submit', command=print_input).grid(row=3, column=0, sticky=W, pady=4)
    mainloop()

当我尝试在glob中指定路径名时它正在工作但是当我尝试从文本框传递值时,它没有执行而不是给出正确的细节它显示随机数。希望你能理解我的问题

1 个答案:

答案 0 :(得分:1)

不知道"什么不起作用"意思是,但你从" mypath"

获得名字
for name in os.listdir(mypath):

但表来自' / *。docx'

for name in glob.glob('/*.docx'):

在一次操作中完成(并查看filedialog.askdirectory)

    mypath = text_entry.get()
    files=0
    for name in os.listdir(mypath):
        if name.endswith('.docx'):
          files=files+1
    #print("Total No of Files:",files)

    #To read the .docx and print how many tables in that 

          table=0
    ##for name in glob.glob('/*.docx'):
          doc=Document(name)
          for t in doc.tables:
              for ro in t.rows:
                  if ro.cells[0].text=="ID" :
                      table=table+1