TKinter tkFileDialog.askopenfilename Always behind other windows - python

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)

Related

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

Python Tkinter - cannot select directory (tkFileDialog not found)

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

how do I get Tkinter askopenfilename() to open on top of other windows?

I am running a script that prompts the user for a file. There is no gui except for the file browser that opens up. I have 2 options: browse for file, or select entire folder using askdirectory(). The latter opens on top of all other windows, but the first one opens under everything, I have to minimize other windows to find it.
Here is the method I'm using for these operations
from Tkinter import Tk
from tkFileDialog import askdirectory, askopenfilename
root = Tk()
root.withdraw()
self.inpath = askdirectory() # To open entire folder
Path = askopenfilename() # Open single file
root.destroy() # This is the very last line in my main script.
This is everything Tk related in my code. askdirectory opens on top, askopenfilename doesn't.
Is there a way to force it to open on top?
root.wm_attributes('-topmost', 1) did it for me. I found it in another SO thread to be honest :-).
I had the same problem.
For me it works with:
file = filedialog.askopenfilename(parent=root)
So, the file dialog gets in front of toplevel window without uncomment root.attributes("-topmost", True)
I want to share that the following lines worked superbly in my case. But I had to use both window.wm_attributes('-topmost', 1) and window=parent to make this work, see below:
import tkinter as tk
from tkinter import filedialog
window = tk.Tk()
window.wm_attributes('-topmost', 1)
window.withdraw() # this supress the tk window
filename = filedialog.askopenfilename(parent=window,
initialdir="",
title="Select A File",
filetypes = (("Text files", "*.txt"), ("All files", "*")))
# Here, window.wm_attributes('-topmost', 1) and "parent=window" argument help open the dialog box on top of other windows
I had the same issue of the file dialog window opening below my current window but I couldn't reproduce the issue with your code (in Python 2 or 3).
This is the minimal example where the issue occurs (context is Windows 10, Python 3, script is called from Idle, and note the input function:
File dialog opens below:
from tkinter import filedialog, Tk
root = Tk()
root.withdraw()
input("\nType anything> ")
file = filedialog.askopenfilename()
To open file dialog on top, both root.lift() or root.attributes("-topmost", True) work (but the latter is specific for Windows)
from tkinter import filedialog, Tk
root = Tk()
#root.attributes("-topmost", True) # this also works
root.lift()
root.withdraw()
input("\nType anything> ")
file = filedialog.askopenfilename()
I'm running python 3.x so there is a difference in code, but both opened on top for me. Try giving it focus, it should put in on top.
self.inpath.focus()
I'm not sure if it's gonna work, since I cant reproduce the problem.

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