tkinter filedialog window persists after folder selection - python

I use the following sub-routine to get a path to the files I require
from tkinter import *
from tkinter import filedialog
def get_foldername(prompt):
root = Tk()
root.withdraw() # get rid of annoying little window
my_path = filedialog.askdirectory(initialdir="/Users/" + getuser(),title=prompt) + "/"
return my_path
The problem is, that the filedialog window persists until the program ends, how can I unload this window before returning to my main program routine?
The following code duplicates the persistence problem:
from getpass import getuser
from tkinter import *
from tkinter import filedialog
def get_foldername(prompt):
root = Tk()
root.withdraw() # get rid of annoying little window
my_path = filedialog.askdirectory(initialdir="/Users/" + getuser(), title=prompt) + "/"
return my_path
def main():
path_to_files = get_foldername("Choose source folder")
while True:
for idx in range(3000000):
print(path_to_files)
break
if __name__ == '__main__':
main()

Related

Input files path and return a list of files on tkinter

I'm trying to use Tkinter for the code below. My goal is to use the entry widget to input the path of a folder and click a button to search and return the list of "pdf" files from the folder(see below). The python code works fine but I'm not sure how to create it in tkinter.
from os import listdir,mkdir,startfile
from os.path import isfile, join,exists
from PyPDF2 import PdfFileMerger
import os
# Input file path and print the pdf files in that path
path = input("Enter the folder location: ")
pdffiles = [f for f in listdir(path) if isfile(join(path, f)) and '.pdf' in f]
print('\nList of PDF Files:\n')
for file in pdffiles:
print(file)
Output:
List of PDF Files:
file1.pdf.pdf
file2.pdf.pdf
file3.pdf.pdf
file4.pdf.pdf
To get text you could use tkinter.simpledialog.askstring(title, prompt)
import tkinter as tk
from tkinter import simpledialog
root = tk.Tk() # manually create main window
root.withdraw() # hide main window
path = simpledialog.askstring('Directory', 'name:')
root.destroy() # destroy main window
if not path:
print('Canceled')
else:
print(path)
But for directory can be more useful tkinter.filedialog.askdirectory(...)
import tkinter as tk
from tkinter import filedialog
root = tk.Tk() # manually create main window
root.withdraw() # hide main window
path = filedialog.askdirectory()
root.destroy() # destroy main window
if not path:
print('Canceled')
else:
print(path)
import tkinter as tk
#from tkinter import simpledialog
from tkinter import filedialog
import os
root = tk.Tk() # manually create main window
root.withdraw() # hide main window
#path = simpledialog.askstring('Directory', 'name:')
path = filedialog.askdirectory()
root.destroy() # destroy main window
if not path:
print('Canceled')
else:
print(path)
pdffiles = [fn for fn in os.listdir(path) if fn.lower().endswith('.pdf') and os.path.isfile(os.path.join(path, fn))]
print('\nList of PDF Files:\n')
for filename in pdffiles:
print(os.path.join(path, filename))

tkinter:2 windows pop up at the same time

As a beginner, I am not familiar with tkinter and I don't know how to improve the following codes which are supposed to function like this:
After running the renamer_v.py file, a window will pop up. It displays a short description at the top and beneath it there is an orange colored buttion 'Click Me'. Click the button and then pop up the second window to select a folder. All titles of files in the folder except the hidden ones and subfolders will be given a serialized prefix.
The problem is that the main window and the second widnow pop up at the same time. Howver, the latter is designed to appear after users clicked the button.
Here is my souce code.
renamer_V1.py:
import win32file
import win32con
import tkinter as tk
from tkinter import Button
from clicked import Clicked
root=tk.Tk()
root.geometry("550x200")
label=tk.Label(root,font=("Arial Bold",15),
text='Please select a directory to rename files in the folder:')
label.pack()
c=Clicked()
btn=Button(root,font=("Arial",15),bg='orange',text="Click Me",command=c.clicked)
btn.pack()
c.clicked()
file_lists=os.listdir(c.file_path)
n=0
for file in file_lists.copy():
oldname=c.file_path+os.sep+file
file_flag=win32file.GetFileAttributesW(oldname)
is_hiden=file_flag & win32con.FILE_ATTRIBUTE_HIDDEN
if os.path.isdir(oldname) or is_hiden:
continue
else:
oldname=c.file_path+os.sep+file
newname=c.file_path+os.sep+'('+str(n+1)+')'+file
os.rename(oldname,newname)
n+=1
label=tk.Label(root,text=str(n)+' file(s) renamed.')
label.pack()
root.mainloop()
clicked.py:
from tkinter import filedialog
class Clicked:
file_path=None
def __init__(self):
print()
def clicked(self):
self.file_path=filedialog.askdirectory(title='ReNamer')
The application is completed and now it is working perfectly under MacOS as desired. Here is the code:
import os
from tkinter import filedialog
import tkinter as tk
from tkinter import Button
root=tk.Tk()
class ReName():
def __init__(self):
self.n = 0
self.label1=tk.Label(root)
def rename(self):
file_path = filedialog.askdirectory(title='ReNamer')
self.file_lists = os.listdir(file_path)
for self.file in self.file_lists.copy():
self.oldname = file_path + os.sep + self.file
if os.path.isdir(self.oldname) or self.file.startswith('.'):
continue
else:
self.newname = file_path + os.sep + '(' + str(self.n + 1) + ')' + self.file
os.rename(self.oldname, self.newname)
self.n+=1
self.label1.config(text='{} file(s) renamed'.format(self.n))
self.label1.pack()
btn.config(state='disabled')
ins=ReName()
root.geometry("550x200")
label=tk.Label(root,font=("Arial Bold",15),
text='Please select a directory to rename files in the folder:')
label.pack()
btn=Button(root,font=("Arial",15),bg='orange',text="Click Me",command=ins.rename)
btn.pack()
root.mainloop()

tkinter askdirectory doesn't work from imported module

I have been using tkinter to supply a file dialog (in python 3.6) which allows users to select a directory. It works fine when it is a sub-function within the same module, but if I move that subfunction into a separate module and then try to import it from that module, it no longer works. Instead the code just hangs when the file dialog should pop up but it never appears.
working code:
This works if I run the main function
from tkinter import Tk
from tkinter.filedialog import askdirectory
def SelectDirectory():
# start up the tk stuff to have a file directory popup
print('start')
root = Tk()
print('postroot')
root.withdraw()
print('postwithdraw')
# let the user pick a folder
basepath = askdirectory(title='Please select a folder')
print('postselection')
root.destroy()
print('postdestroy')
return basepath
def main():
ans = SelectDirectory()
print(ans)
If I instead put this in another module and import it from that module, then it will print until 'postwithdraw' and then just hang.
submod.py:
from tkinter import Tk
from tkinter.filedialog import askdirectory
def SelectDirectory():
# start up the tk stuff to have a file directory popup
print('start')
root = Tk()
print('postroot')
root.withdraw()
print('postwithdraw')
# let the user pick a folder
basepath = askdirectory(title='Please select a folder')
print('postselection')
root.destroy()
print('postdestroy')
return basepath
and then run this:
from submod import SelectDirectory
def main():
ans = SelectDirectory()
print(ans)
It never gets past 'postwithdraw' and the file dialog never pops up.
Does anyone know what I am doing wrong here? I would think it has something to do with the tkinter window not appearing since its not the main module but is there some way to get past that?
Your both versions don't work. Both give 'module' object is not callable.
You have to use
root = Tk.Tk()
instead of
root = Tk()
and then both versions works.
Maybe two Tk in Tk.Tk() seems weird but usually we use lowercase tk instead of Tk in
import tkinter as tk
and then you have
root = tk.Tk()

Using tkinter to select and save a file

I am looking to create a reminder that prompts the user to select a file if they've completed it. After selecting the file they want, I would like the script to save that file to a specific folder. This is what I have so far...
import tkinter
import time
import win32api
from tkinter import messagebox
dialog_title = 'Complaince calendar'
dialog_text = 'Have you completed the monthly spreadsheet?'
answer = messagebox.askquestion(dialog_title, dialog_text)
if answer == 'yes':
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
else: # 'no'
win32api.MessageBox(0, 'Make sure you get that done', 'Compliance calendar')
How can I save the file_path to a specified folder?
Thanks!!

Open File Dialog freezes after tkinter askopenfilename method is called

I'm trying to simply get a file name from the user by tkinter.filedialog.askopenfilename(). The function returns fine and the code below displays the file name okay but the dialog window doesn't close immediately after hitting 'open' or 'cancel', it freezes. I'm using python 3.3.3 or OSX 10.9.1 and tcl/tK 8.5.9.
from tkinter import *
from tkinter.messagebox import *
from tkinter.filedialog import *
top = Tk()
top.withdraw()
file_name = filedialog.askopenfilename()
print (file_name)
Adding root.update() after filedialog.askopenfilename() gets the open file dialog to close after the file is chosen.
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
root.update()
Refer to: Tkinter askopenfilename() won't close
A work around that I used for this is to "withdraw" the tkinter window AFTER selecting the file from file explorer. Here is the code snippet I used -
import tkinter
from tkinter import filedialog
def selectCustomerFileTK():
root = tkinter.Tk()
root.wm_attributes('-topmost', 1)
filename = filedialog.askopenfilename()
root.withdraw()
return filename
getfile = selectCustomerFileTK()
It opens a tkinter window while you are selecting the file, but the moment you select the file and press "Open", the tkinter window and file explorer both close because of the "root.withdraw()" command after.
You don't need to specify module name in
file_name = filedialog.askopenfilename()
Try
file_name = askopenfilename()
instead

Categories

Resources