Im new to tkinter and trying to open the explorer (on windows) so that i can chose what folder i want to use in my program. I found a template for tkinter and altered it to work with my function and how i need the filepath to be. Before i tried using tkinter to "select my folder", i had manually writen the directory in the glob.glob function like this glob.glob(r'C:\Users\Desktop\Spyder\*.log') (and it worked). So my new ide was to replace the pathname input from r'C:\Users\Desktop\Spyder\*.log' to a variabel that stored the same pathname but now it used tkinters askdirectory() to finde the directory inteed.
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')
My problem ist that i don´t get the for loop filepath_search to work (it prints "ok"). But the word run inside the for loop dose not print, i guess it´s because it gets stuck somewhere before that? Someone who has more experience with tkinter that can help me? Thanks
I guess issue caused by what is passed to glob.glob since it doesn't find anything. It seems that it is mostly related to the fact that you add ' characters at the beggining and end of your right_log_filepath.
In ask_directory_to_folder function replace:
log_filepath = "r'"+ str(filepath +"/*.log'")
right_log_filepath = log_filepath.replace('/','\ ').replace(' ','')
find_filenames(right_log_filepath)
With:
from os import path # should be at the top of your file
log_filepath = path.join(filepath, "*.log")
find_filenames(log_filepath)
Related
from PIL import Image
from tkinter import filedialog as fd
import os
import ctypes
import tkinter
class ImageList:
path = ""
dir = ""
top = tkinter.Tk()
canvas = tkinter.Canvas()
canvas.pack()
def __init__(self):
self.path = os.path.expanduser('~/')
def findImage(self):
image = Image.open(self.dir, "rb")
image.show()
def fileExplorer(self, path):
self.canvas.destroy()
self.canvas = tkinter.Canvas()
self.canvas.pack()
obj = os.scandir(path)
for entry in obj:
if entry.is_dir():
#self.path = os.path.abspath(self.path)
b = tkinter.Button(self.canvas, text=entry.name, command=lambda: self.fileExplorer(os.path.abspath(entry).replace('//', '\\')))
b.pack()
elif entry.is_file():
b = tkinter.Button(self.canvas, text=entry.name, command=lambda: print(entry.name))
b.pack()
else:
obj.close()
self.top.mainloop()
As shown in the code above, I am trying to make exe that shows the subdirs and files after C:\Users using buttons in tkinter and repeating it by using recursion.
The first error is that in "os.path.abspath(entry).replace('//', '\')" shows path in a format of "C://Users" and I intended to change that to "C:\Users" using the replace method. However, using "\" doesn't replace "//" and still shows as the original format.
The second error is that after running the code, when I press any button it acts as if I pressed the last button in the tkinter window, meaning that it recursively called the last subdir or the file below "C:\Users".
I'm just getting used to python and this is my first time using stackoverflow. I'm sorry if I did not abide by any of the rules in stackoverflow. Thanks for anyone helping.
Using Tkinter, os, and, pygame modules im finding all files and making a button to play the file because it will be an mp3 file but every time the function overwrites itself so I want to be able to write a function but inside the command parameter in the Tkinter button so it isn't a function but it operates like one
the code i already have:
import os
import pygame
import tkinter as tk
dir_path = os.path.dirname(os.path.realpath(__file__))
d = dir_path+"\\mp3s"
root = tk.Tk()
frame=tk.Frame(root)
root.title("title")
frame.pack()
for path in os.listdir(d):
full_path = os.path.join(d, path)
full_name = os.path.basename(full_path)
def playsong():
pygame.init()
pygame.mixer.music.load(full_path)
pygame.mixer.music.play()
play = tk.Button(frame,
text=full_name,
command=playsong)
play.pack()
root.mainloop()
the function inside the for statement is getting overwritten and I knew this would happen but I was still going to try this works for one file but I want a bunch of different files inside of the folder named "mp3s"
the rest of the code works this is the part that does not
def playsong():
pygame.init()
pygame.mixer.music.load(full_path)
pygame.mixer.music.play(
I wanted to run multiple functions in a line more specifically than lines and I figured out how to do this using lambda
import tkinter as tk
root = tk.Tk()
frame=tk.frame(root)
button = tk.Button(frame, text="name", command= lambda: [func1(), func2()])
I just started programming with Python and I'm trying to create a GUI using tkinter where it would ask the user to select a zip file and file destination to send it to after extracting. What I have noticed is that when a user re-enters a destination, it would still store the previous file directory as well. How do I prevent this?
import tkinter as tk
from tkinter import filedialog
# Setting the window size
screenHeight = 450
screenWidth = 350
root = tk.Tk()
# get the location of the zip file
def input_dir():
input_filedir = filedialog.askopenfilename(initialdir='/', title='Select File',
filetypes=(("zip", "*.zip"), ("all files", "*.*")))
my_label.pack()
return input_filedir
# get location of destination for file
def output_dir():
output_filename = filedialog.askdirectory()
# Setting the canvas size to insert our frames
canvas = tk.Canvas(root, height=screenHeight, width=screenWidth)
canvas.pack()
# Setting the frame size to insert all our widgets
frame = tk.Frame(root, bg='#002060')
frame.place(relwidth=1, relheight=1)
# button to get user to chose file directory
openFile = tk.Button(frame, text='Choose the file path you want to extract', command=input_dir)
openFile.pack(side='top')
# button to get destination path
saveFile = tk.Button(frame, text="Chose the location to save the file", command=output_dir)
saveFile.pack(side='bottom')
extractButton = tk.Button(frame, text="Extract Now")
root.mainloop()
I have tried adding this line of code in the def input_dir function but it changed the positioning of the buttons. I'm still working on the code for extracting the zip.
for widget in frame.winfor_children():
if isinstance(widget, tk.Label):
widget.destroy()
The files/directories the user clicks are not saved really. Your variables input_filedir and output_filename are garbage collected when their respective functions are completed. If you are talking about how the dialog boxes go back to the most recent places opened in a dialog, that is not really something you can mess with too much. The easy answer is you can add the keyword 'initialdir' when you make the dialog to just pick where it goes like this:
output_filename = filedialog.askdirectory(initialdir='C:/This/sort/of/thing/')
The long answer is that filedialog.askdirectory actually creates an instance of filedialog.Directory and in that class, it saves that information for later in a method called _fixresult (but that method also does other things that are important.) You could overwrite this by doing something like this:
class MyDirectory(filedialog.Directory):
def _fixresult(self, widget, result):
"""
this is just a copy of filedialog.Directory._fixresult without
the part that saves the directory for next time
"""
if result:
# convert Tcl path objects to strings
try:
result = result.string
except AttributeError:
# it already is a string
pass
self.directory = result # compatibility
return result
def askdirectory (**options):
"Ask for a directory, and return the file name"
return MyDirectory(**options).show()
and then using your own askdirectory function instead of filedialog.askdirectory, but that is really convoluted so I recommend using initialdir instead if you can.
P.S. When a button is clicked, it calls the function you set after "command=" when you made the button; it seems you got that. But these functions are 'void', in that their return is just ignored. That is to say, the "return input_filedir" line does nothing.
So when I am calling the list directory code below directly then it's working fine. But when I am calling main.py which uses app class from gui which calls the list directory function, It prints "yoo" but prints an empty list instead of list of directories. I am stuck and can't figure out why that's happening. Any ideas?
Outputs:
When list directory called directly :
["/home/shubham/Desktop/movies/djangounchained.mkv"]
"yoo"
When called by main.py with same argument:
[]
"yoo"
Here is my main script
from gui import app
from list_directory import display_files
import tkinter as tk
root = tk.Tk()
directory = input("Enter directory name:")
root.geometry("400x300")
widgets_creator = app(root)
name = "get list"
directory_button = widgets_creator.create_button(name,function=display_files,path=directory)
root.mainloop()
Here is my gui script
import tkinter as tk
class app(tk.Frame):
def __init__(self,master):
super(app,self).__init__(master=master)
self.master = master
self.init_window()
def init_window(self):
# changing the title of our master widget
self.master.title("GUI")
# allowing the widget to take the full space of the root window
self.pack(fill=tk.BOTH, expand=1)
# creating a button instance
quitButton = tk.Button(self, text="Quit")
# placing the button on my window
quitButton.place(x=0, y=0)
def create_button(self,button_name,function,path):
button = tk.Button(self.master,text=button_name,command=lambda: function(path))
button.place(x=200,y=5)
return button
Here is my list_directory code:
import glob
def display_files(path):
x = glob.glob(path)
print(x)
print("yoo")
if __name__ == '__main__':
display_files("/home/shubham/Desktop/movies/*")
I might have found your problem. The code works fine, the problem is your argument. For example, if I enter '/Users/rudy/Desktop/*' when the input prompt comes up, I have the same result as you.
However, when I enter /Users/rudy/Desktop/* (without quotes), everything works fine. input() already saves the input as a string, so you don't need to add additional quotes.
Hi Everyone I am working on my final project and I am creating a directory snooper
So here is the bottomline of this script:
GUI with Tkinter that asks user for directory and prompts user to
save a cvs file to the space of their choosing. CSV will contain
filename,file extension and file size taken from the directory that
the user inputed.
My GUI has a text scroll box that should print the process of the
script and print when it is done,
My problems:
When saving CSV. It does not produce a CSV and I get this error
"ValueError: I/O operation on closed file".asksaveasfilename() is
not working
GUI text scroll box is not working and printing out the information
i need
How do I add headers to my CSV so that my CSV will have
filename,extension,size, and comment
Attached below is my script. Can anyone help me with this?
from Tkinter import Tk
from tkFileDialog import askdirectory
from array import *
import os
version = '1.0'
import os
import csv
from Tkinter import BOTH, LEFT, TOP, END, StringVar
from ttk import Frame, Entry, Button, Label
from ScrolledText import ScrolledText
from tkFileDialog import askdirectory
from tkFileDialog import asksaveasfilename
class FileWalkerWindow(Frame):
def __init__(self):
Frame.__init__(self)
self.pack(expand=True, fill=BOTH)
self.master.title("Directory Snooper v" + version)
self.master.iconname("Directory Snooper")
self.dir = StringVar() # tkinter does not work with standard python variables
self.dir.set(os.getcwd()) # set to current working directory
description = "This program walks through a directories " \
+ "print out name of directory file path. " \
+ "prints out mumber of files in your in your directory. " \
+ "It list files and tests for corrupted zipfiles and " \
+ "creates a CSV file of the findings"
row1 = Frame(self)
Label(row1, text="Choose Directory:").pack(side=LEFT, pady=10)
self.dir_ent = Entry(row1, width=80, textvariable=self.dir)
self.dir_ent.pack(side=LEFT)
Button(row1, text="Browse", width=10, command=self.browse).pack(side=LEFT, padx=5)
row1.pack(side=TOP, ipadx=15)
row2 = Frame(self)
btn = Button(row2, text="Snoop", command=self.savefile, width=15)
btn.pack(side=LEFT, padx=5, pady=10)
row2.pack(side=TOP)
self.output = ScrolledText(self, height=15, state="normal",
padx=10, pady=10,
wrap='word')
self.output.insert(END, description)
self.output.pack(side=LEFT, fill=BOTH, expand=True, padx=5, pady=5)
self.bind('<Key-Return>', self.savefile) # bind enter press to walk
def browse(self):
dirpath = askdirectory(parent=self, title="Select Directory")
self.dir.set(dirpath)
def savefile (self):
self.output.delete(1.0, END)
name=asksaveasfilename()
with open(name,'w') as csvfile:
dirList = os.listdir(self.dir.get())
data = ((fname, str(os.path.getsize(self.dir.get() + "/" + fname)), str(os.path.splitext(fname)[1]),) for
fname in
dirList)
for entry in data:
create=csv.writer(csvfile)
create.writerow(','.join(entry) + '\n')
csvfile.close()
if __name__ == '__main__':
FileWalkerWindow().mainloop()
When saving CSV. It does not produce a CSV and I get this error
"ValueError: I/O operation on closed file"
You do close the file in your for loop:
for entry in data:
create=csv.writer(csvfile)
create.writerow(','.join(entry) + '\n')
csvfile.close()
Unindent it to close the file after the for loop. You should move the csv.writer() outside of the for loop as well (as mentioned in comments):
create=csv.writer(csvfile)
for entry in data:
create.writerow(','.join(entry) + '\n')
csvfile.close()
GUI text scroll box is not working and printing out the information i need
The question is when you want to display the information!
You can add a button to print the content of the chosen directory or print it automatically when the user selects a folder to browse.
To do the latter, you can edit you browse method, which should look like:
def browse(self):
dirpath = askdirectory(parent=self, title="Select Directory")
self.dir.set(dirpath)
self.output.insert(END, "\n" + "\n".join(os.listdir(dirpath)))
How do I add headers to my CSV so that my CSV will have
filename,extension,size, and comment
Just write a Python string containing your headers before writing actual values:
with open(name,'w') as csvfile:
csvfile.write("filename,extension,size,comment")
dirList = os.listdir(self.dir.get())
# some other stuff after...
Please note also that, while it is strongly discouraged by Python guidelines to use from module import * in general, the standard way to import Tkinter is from Tkinter import * :)