Getting folder path with Python Tkinter tkFileDialog - python

Using Python Tkinter I am trying to get the directory path of selected Folder. I do not want to load a file or navigate to a file but get the folder path like
How can I do this?
from Tkinter import *
from tkFileDialog import askopenfilename
def callback():
name= askopenfilename()
print name
errmsg = 'Error!'
Button(text='File Open', command=callback).pack(fill=X)
mainloop()
Update
from Tkinter import *
from tkFileDialog import askopenfilename
from tkinter import filedialog #for Python 3
def callback():
name= askopenfilename()
directory = filedialog.askdirectory()
print directory
errmsg = 'Error!'
Button(text='File Open', command=callback).pack(fill=X)
mainloop()

You can use askdirectory from filedialog as follows:
from tkinter import filedialog #for Python 3
directory = filedialog.askdirectory()

Ok Looks like I find the solution on my own. Putting here which might help someone else in future.
import Tkinter, tkFileDialog
root = Tkinter.Tk()
root.withdraw()
dirname = tkFileDialog.askdirectory(parent=root,initialdir="/",title='Please select a directory')
print(dirname)

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))

How to remove directory and show only file name in tkinter?

im trying to make only the file name show up using filedialog
here's the example :
import tkinter as tk
import pygame
from tkinter import filedialog
root = tk.Tk()
controls_frame = tk.Frame(root)
controls_frame.pack()
def add_name():
name = filedialog.askopenfile()
names.insert(filedialog.END,name)
names = tk.Listbox(root,bg="black",fg="red",width=60,height=6)
names.pack(pady=0,side='bottom')
add_name_btn = tk.Button(controls_frame , text='add name' , command=add_name)
add_name_btn.grid(column=3,row=0,padx=20)
root.mainloop()
it shows the full directory to the file, which i dont want.
how do i remove the directory that it shows on box?
The module os can help with this:
import os
def add_name():
name = os.path.basename(str(filedialog.askopenfile()))
name = name.replace("' mode='r' encoding='UTF-8'>", "")
names.insert(filedialog.END,name)
You can do it like this.
I found this solution on another post.
import tkinter
from tkinter import filedialog
def filename123():
global filename1, nopath1
filename1 = filedialog.askopenfilename()
nopath1 = filename1.split("/")[len(filename1.split("/"))-1]
filename123()

Tkinter not working in cmd (working in IDLE)

I am trying to display a directory selection dialog box (for getting a path and then for saving downloaded stuff).The code runs fine in IDLE but when i try to run it in CMD i get this error
NameError: name 'Tk' is not defined
I am using tkinter for gui.
Code Snippet
from tkinter import filedialog
root = Tk()
root.withdraw()
filename = filedialog.askdirectory()
Using Python 3.4.3. Any help/suggestions?
The statement from tkinter import filedialog only imports the filedialog module from tkinter. If you want the usual Tkinter stuff, you have to import that too. I'd recommend import tkinter as tk and then referring to it with e.g. root = tk.Tk() so you don't just dump everything into the global namespace. Or, if you really just want the root object, use from tkinter import Tk.
from tkinter import Tk
from tkinter import filedialog
root = Tk()
root.withdraw()
filename = filedialog.askdirectory()

Passing a variable from Tkinter to main program

Maybe this is easy, but I just don't figure it out ...
In the code below the "File Open" Button saves the filename to "name" -- but how can I access this variable outside of Tkinter? A return statement in "callback", but how would I access that since callback is inside the "Button" command?
from Tkinter import *
from tkFileDialog import askopenfilename
def callback():
name= askopenfilename()
print name
Button(text='File Open', command=callback).pack(fill=X)
mainloop()
#HOW DO I ACCESS FILENAME AFTER MAINLOOP?
name = ????
eh, How about this?
from Tkinter import *
from tkFileDialog import askopenfilename
value_list = []
def callback():
name = askopenfilename()
value_list.append(name)
print name
Button(text='File Open', command=callback).pack(fill=X)
mainloop()
# value_list[0] is filename

Get a file's directory in a string selected by askopenfilename

I'm making a program that you use the askopenname file dialog to select a file, which I then want to save the directory to a string so I can use another function (which I already made) to extract the file to a different location that is predetermined.
My button code that opens the file dialog is this:
`a = tkinter.Button(gui, command=lambda: tkinter.filedialog.askopenfilename(initialdir='C:/Users/%s' % user))`
This should be what you want:
import tkinter
import tkinter.filedialog
import getpass
# Need this for the `os.path.split` function
import os
gui = tkinter.Tk()
user = getpass.getuser()
def click():
# Get the file
file = tkinter.filedialog.askopenfilename(initialdir='C:/Users/%s' % user)
# Split the filepath to get the directory
directory = os.path.split(file)[0]
print(directory)
button = tkinter.Button(gui, command=click)
button.grid()
gui.mainloop()
If you know where the file actually is, you could always just ask for a directory instead of the file using:
from tkFileDialog import askdirectory
directory= askdirectory()
Then in the code:
import tkinter
import tkinter.filedialog
import getpass
from tkFileDialog import askdirectory
# Need this for the `os.path.split` function
import os
gui = tkinter.Tk()
user = getpass.getuser()
def click():
directory= askdirectory()
print (directory)
button = tkinter.Button(gui, command=click)
button.grid()
gui.mainloop()

Categories

Resources