簡體   English   中英

瀏覽文件並將路徑存儲在 function

[英]Browse for a file and store the path in a function

我創建了一個 function 在文件夾中搜索 a.txt 文件,然后讀取它並將結果打印到另一個.txt 文件中。

import os


# this will check for the file list file in the d3 folder

def file_list():
    for f_name in os.listdir('D:\\d3 Projects\\python_test'):

        if f_name.endswith('.txt'):
            print(f_name)

            # this will read and print the filelist.txt file

            myfile = open("D:\\d3 Projects\\python_test\\filelist.txt", "r")
            contents = myfile.read()
            myfile.close()
            print(contents)


if __name__ == "__main__":
    file_list()

現在我想讓輸入路徑和 output 路徑用戶可選擇,並帶有一點界面。 (我正在考慮使用 tkinter。)

關於我怎么做的任何想法? 我能夠創建 window 和瀏覽按鈕,但我不知道如何將它存儲在我的 function 中。

你可以試試這個:

from tkinter import *
from tkinter import ttk
from tkinter import filedialog
 
 
 
class Root(Tk):
    def __init__(self):
        super(Root, self).__init__()
        self.title("Python Tkinter Dialog Widget")
        self.minsize(640, 400)
        self.wm_iconbitmap('icon.ico')
 
        self.labelFrame = ttk.LabelFrame(self, text = "Open File")
        self.labelFrame.grid(column = 0, row = 1, padx = 20, pady = 20)
 
        self.button()
 
 
 
    def button(self):
        self.button = ttk.Button(self.labelFrame, text = "Browse A File",command = self.fileDialog)
        self.button.grid(column = 1, row = 1)
 
 
    def fileDialog(self):
 
        self.filename = filedialog.askopenfilename(initialdir =  "/", title = "Select A File", filetype =
        (("jpeg files","*.jpg"),("all files","*.*")) )
        self.label = ttk.Label(self.labelFrame, text = "")
        self.label.grid(column = 1, row = 2)
        self.label.configure(text = self.filename)
 
 
 
 
 
root = Root()
root.mainloop()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM