Python Tkinter - cannot select directory (tkFileDialog not found) - python

We're trying to store a directory path in a variable using Tkinter's tkFileDialog, and it won't work (details later).
from Tkinter import *
import os
from tkFileDialog import askopenfilename, askdirectory
# Create the window
root = Tk()
# Application title & size
root.title("Title")
root.geometry("1000x600")
# Creating frame to add things to
app = Frame(root)
app.grid() # Adding app frame to grid
# Method that opens file chooser
# Gets used when button is clicked (command)
def openFileBox():
directoryPicked = tkFileDialog.askdirectory()
#easygui.fileopenbox()
for filePicked in os.listdir(directoryPicked):
if filePicked.lower().endswith(".jpg") or filePicked.lower().endswith(".gif") or filePicked.lower().endswith(".png"):
print filePicked
#TODO: add button 'Select Folder'
loaderButton = Button(app)
loaderButton["text"] = "Select Folder"
loaderButton["command"] = openFileBox
loaderButton.grid()
# Tells the program to run everything above
root.mainloop()
So what needs to happen? The way we see it (and we're beginners looking for feedback here), it should be running the openFileBox method when the button is pressed. When the method runs, it should store a selected directory to directoryPicked and print it to the console just to be sure it's working, but when we press the button it simply says 'tkFileDialog' is not defined.
Any thoughts?

It's because you're only importing askopenfilename, askdirectory from tkFileDialog you're not actually importing tkFileDialog itself
So you need to change directoryPicked = tkFileDialog.askdirectory() to directoryPicked = askdirectory()

Related

Getting file directory from tkinter function

I am running a simple python script that opens a window with a button inside of it. When the user clicks the button a dialog box opens and asks the user to select a file directory. I want to pull that directory location out of the function. This is what the code looks like:
from tkinter import *
from tkinter import filedialog
def openFile():
filePath= filedialog.askdirectory()
return filePath
window = Tk()
button = Button(text="open", command=openFile)
button.pack()
window.mainloop()
I would like the file directory to be saved in a variable inside the window. I am able to print the filepath inside the function but I am unable to bring it out of the function.
Any help will be greatly appreciated
You cannot use the return value for functions added to buttons, as there is no way of picking up whatever is returned.
So instead you can write the return to a global variable, or a class variable, instead. Example with global variable below;
from tkinter import *
from tkinter import filedialog
my_path = None
def openFile():
global my_path
filePath = filedialog.askdirectory()
my_path = filePath
window = Tk()
button = Button(text="open", command=openFile)
button.pack()
window.mainloop()
You will then be able to pick up the my_path variable later in your script after clicking the button.

How can I add a file chooser in python?

Right now, I have a GUI program that allows you to change parameters and stuff like that. I want to make it so you can choose a picture instead of only having one for the whole thing.
I have this:
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
When I try to use this, it will just say that it cannot import filedialog.
EDIT:
Okay, so I just fixed that error by using:
import tkFileDialog as filedialog
Now I just need help making the file I choose be the one that appears on the canvas. Right now, I have this:
__dir__ = os.path.dirname(os.path.abspath(__file__))
filename = os.path.join(__dir__, root.filename)
img = PIL.Image.open(filename)
shrek= img.resize((100,100))
root = Tk() # create main window; must be done before using ImageTk
root.filename = filedialog.askopenfilename(initialdir = "E:/Images",title = "choose your file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
print (root.filename)
I am trying to make the file that I choose from the explorer replace the current file.
This is for Python 2.x import tkFileDialog as filedialog
I guess you use Python 2.x..

Python 2.71.11 Tkinter window not closing "Application not Responding"

I'm trying to open a simple file dialog to ask the user to select a file. The code I have is:
from Tkinter import Tk
from tkFileDialog import askopenfilename
Tk().withdraw()
filename = askopenfilename()
print(filename)
sys.exit(0)
The program retrieves the file name successfully, however the window remains open and does not close. The only way I can exit it is through Force Quit. I am using Mac OS X 10.11 and Python 2.7.11.
Thank you
There seems to be some issues based on your development environment. See reference [2]. This worked for me:
from Tkinter import Tk
from tkFileDialog import askopenfilename
root = Tk() #To initialize Tkinter, we have to first create a Tk root widget
filename = askopenfilename() # store filename
# root.mainloop() may be necessary for your development environment (see [2])
root.destroy() #destroy the event loop - only required in some python environments (see [2])
print(filename)
[1] http://effbot.org/tkinterbook/tkinter-hello-tkinter.htm
[2] http://effbot.org/tkinterbook/tkinter-hello-again.htm

TKinter tkFileDialog.askopenfilename Always behind other windows

I want to create a simple TKinter file selection dialog with a function that I will use from other scripts and not a wider GUI.
My current code is:
# Select a single file and return the full path as a string
def select_file(data_dir):
chdir(data_dir)
root = Tkinter.Tk()
root.withdraw()
file_path = tkFileDialog.askopenfilename()
return file_path
When I run this the file dialog is always behind other windows. If I have Spyder maximised, it opens behind it so I have to minimise.
There are a few questions related to this, but I've been unable to get any of the suggested code to work, so apologies if this is viewed as a duplicate question.
Ben
Just have to use root.deiconify() after file_path = tkFileDialog.askopenfilename()
But it's a bad idea to create a new Tk here.
Use root.focus_force() to make the root window on top and the fileDialog should also be on top:
from Tkinter import *
import tkFileDialog
def select_file(data_dir):
root = Tk()
root.withdraw()
root.focus_force()
return tkFileDialog.askopenfilename(parent=root, initialdir=data_dir)
select_file(data_dir)

tkinter - how to open multiple filedialogs?

in python's default editor, IDLE, it is possible to have multiple 'Open' dialogs opened at the same time.
I'm looking at their source, but I can't find where I can have this behavior replicated. from their IOBinding.py's :
from tkinter import filedialog as TkFileDialog
...
class IOBinding:
...
def askopenfile(self):
dir, base = self.defaultfilename("open")
if not self.opendialog:
self.opendialog = tkFileDialog.Open(master=self.text,
filetypes=self.filetypes)
filename = self.opendialog.show(initialdir=dir, initialfile=base)
return filename
so they do use tkinter's built-in filedialog module, but I can't find way to have some 'modeless' dialogs. I can have dialogs opened by two codes, which are basically same:
from tkinter import filedialog as tkFileDialog
file_name = tkFileDialog.Open( ... ).show()
file_name = tkFileDialog.askopenfilename()
but they blocks whole application - users cannot switch windows or issue new command until they close the dialog. also, I can't call these dialog functions from different thread - that will kill whole my Tk app. What should I do?
filedialog have parent option. You can change it to hidden window to prevent blocking the root window:
from tkinter import filedialog as tkFileDialog
from tkinter import *
def ask_open():
p = hidden if attach_to_hidden.get() else root
tkFileDialog.Open(parent=p).show()
root = Tk()
hidden = Toplevel()
hidden.withdraw()
attach_to_hidden = IntVar()
Checkbutton(root, text='Attach to hidden window', variable=attach_to_hidden).pack()
Button(root, text='Open', command=ask_open).pack()
root.mainloop()

Categories