我是tkinter
的新用户,并试图在Windows上打开explorer
,以便我可以选择要在程序中使用的文件夹。我找到了tkinter
的模板,并对其进行了更改,以使其与我的功能以及我如何需要filepath
一起使用。在尝试使用tkinter
“选择我的文件夹”之前,我已经在glob.glob
函数中像这样的glob.glob(r'C:\Users\Desktop\Spyder\*.log')
手动写入了目录(并且有效)。因此,我的新思路是将r'C:\Users\Desktop\Spyder\*.log'
的路径名输入替换为存储相同路径名的variabel,但现在它使用tkinters askdirectory()
来查找inte目录。
import glob
import os
from itertools import zip_longest
import tkinter as tk
from tkinter import filedialog
#-------------Connect to Access2013------------------
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.pack()
self.create_widgets()
def create_widgets(self):
self.select_folder = tk.Button(self)
self.select_folder["text"] = "Open WindowsExplorer"
self.select_folder["command"] = self.ask_directory_to_folder
self.select_folder.pack(side="top")
self.quit = tk.Button(self, text="QUIT", fg="red",
command=root.destroy)
self.quit.pack(side="bottom")
def ask_directory_to_folder(self):
clerdatabase() # a funktion that resets the autonumber and deleats all data from every table
print("Open!")
filepath = filedialog.askdirectory()
log_filepath = "r'"+ str(filepath +"/*.log'")
right_log_filepath = log_filepath.replace('/','\ ').replace(' ','')
find_filenames(right_log_filepath)
root = tk.Tk()
app = Application(master=root)
app.mainloop()
#--------------Scan selected folder for .log files and starts to scan files---------
def find_filenames(right_log_filepath): #finds every file in the chosen filepath
print(right_log_filepath) # r'C:\Users\Desktop\Spyder\*.log'
print("ok")
filenames = [] # list for all the found filenames
for filepath_search in glob.glob(str(right_log_filepath), recursive=True): #A for loop that opens every .log file in the chosen directory folder
print('run')
我的问题是我没有使for loop
filepath_search
正常工作(打印“确定”)。但是for循环中的run
一词无法显示,我想是因为它在此之前被卡住了吗?有人对tkinter有更多的经验可以帮助我吗?谢谢
答案 0 :(得分:1)
我猜这是由于传递给glob.glob
的内容引起的,因为它找不到任何内容。看来,这主要与您在right_log_filepath的开头和结尾处添加'
字符这一事实有关。
在ask_directory_to_folder
函数中替换:
log_filepath = "r'"+ str(filepath +"/*.log'")
right_log_filepath = log_filepath.replace('/','\ ').replace(' ','')
find_filenames(right_log_filepath)
使用:
from os import path # should be at the top of your file
log_filepath = path.join(filepath, "*.log")
find_filenames(log_filepath)