代码之家  ›  专栏  ›  技术社区  ›  Aroon

用于从文本框传递值的Python tkinter操作

  •  0
  • Aroon  · 技术社区  · 8 年前

    实际上,我已经为做了一个脚本。docx操作。这个脚本将计算总数。docx文件在文件夹中,并给出一些报告。现在我计划在上面使用GUI操作。在我的脚本中,我将该文件夹放在python目录中,因此它可以工作,但我想在这里,用户将在文本框中输入路径,如“C:/User/app/data/folder\u name”,当按下提交按钮时,它将显示报告。这里我附上了代码

    import os
    import glob
    from docx import Document
    
    from tkinter import *
    def print_input():
    
        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)
        table=0
        for name in os.listdir(mypath):
             for word in glob.glob('*.docx'):
              doc=Document(word)
              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)
    Button(root, text='Submit', command=print_input).grid(row=3, column=0, sticky=W, pady=4)
    mainloop()
    

    这是我的新代码。但我在那个文件夹中只有一个文件,它由5个表组成。这段代码给出了2个文件和312个表。我能做什么?

    1 回复  |  直到 8 年前
        1
  •  2
  •   silverhash    8 年前

    您可以使用 get() 方法 Entry 小部件以获取用户输入的内容。因此,这样的方法应该有效:

    from tkinter import *
    def get_path():
        #Something like this
        #replace your default path with the user's path
        mypath = text_entry.get()
        files=0
        for name in glob.glob(mypath):
        files=files+1
        print("Total No of Files:",files)
    
    root = Tk()
    Label(root, text="Enter Path").grid(row=0)
    #Create text entry and add it to the window:
    text_entry = Entry(root)
    text_entry.grid(row=1, column=0)
    #This button will call the get_path function when it is clicked
    Button(root, text='Submit', command=get_path).grid(row=3, column=0, sticky=W, pady=4)
    mainloop()
    

    编辑:您也可以使用 Text 小部件显示您的结果时,相同的 提交 按钮被调用