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
Related
I am using tkinter asopenfilename to trigger a file chooser so as to read files from my local directory. My problem is that after the file is chosen, the window freezes and python is 'not responding'.
I've tried the answer from this post: Tkinter askopenfilename() won't close no luck.
Below is my code:
from tkinter import Tk
from tkinter.filedialog import askopenfilename
root = Tk()
root.withdraw()
root.update()
filename = askopenfilename()
print(filename)
Is there anything that I am missing? Let me know if you need more clarity. Thanks!
I tried all above solutions but didn't seem to solve the same issue for me. The dialog box was opening but somewhere in the background.
Found this code elsewhere and it works like a charm for me. On windows 10 too, python 3.x, and using Jupyter Notebook.
Posting it here in case it could help others.
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
root.call('wm', 'attributes', '.', '-topmost', True)
file_path = filedialog.askopenfilename(
%gui tk
print(file_path)
I tried using root.update() after filename = askopenfilename() in my MacOS.
Following worked for me-
from tkinter import Tk
from tkinter.filedialog import askopenfilename
root = Tk()
root.withdraw()
filename = askopenfilename()
root.update()
print(filename)
I had the same behavior on MacOS and adding the iPython magic %gui tk appears to be solving the issue:
from tkinter import Tk
from tkinter.filedialog import askopenfilename
%gui tk
root = Tk()
root.withdraw()
filename = askopenfilename(multiple=True)
print(filename)
From the docs:
%gui tk # enable Tk event loop integration
askopenfilename doesn't work in windows
from tkinter import *
#from tkFileDialog import askopenfilename
import tkinter.filedialog
def callback():
name= tkinter.filedialog.askopenfilenames()
print (name)
errmsg = 'Error!'
Button(text='File Open', command=callback).pack(fill=X)
mainloop()
I am using python 3.6 and have the following issue.
These lines of codes apparently open two windows, but I only expect one to be opened.
from tkinter.filedialog import asksaveasfilename
file_name = asksaveasfilename()
root.withdraw()
IIRC, you're supposed to call withdraw before you call asksaveasfilename. Same as in Choosing a file in Python with simple Dialog.
import tkinter
from tkinter.filedialog import asksaveasfilename
tkinter.Tk().withdraw()
file_name = asksaveasfilename()
when you do filename = asksaveasfilename() you call the function
and that makes tkinter open the second window put that in a function and on
a button click the second window will open
from tkinter.filedialog import asksaveasfilename
import tkinter
root = tkinter.Tk()
root.withdraw()
asksaveasfilename()
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)
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.
I building a messenger with possibility to send files. Iv'e added this line to prevent the tk window to be shown:
Tk().withdraw()
and I'm opening files with this command
tkFileDialog.askopenfilename()
through IDLE python editor it all seems to be working, but when I open python script through cmd and try to send a file , the gui do not show up at all, and the dialog to choose file doesn't open.
when I remove the command Tk().withdraw() , it seems to be working again , but this stupid blank Tk window is still shown up.
How do I prevent the blank Tk from being shown up when I running the script from cmd without causing the choose file dialog to disappear?
this is the code (I'm using python 2.7 , and this is not the whole code, I pasted just the necessary parts):
from Tkinter import Tk
import tkFileDialog
messege = raw_input()
if messege == "SEND":
print "Starting to send file..."
isSendingFile = True
resDir = tkFileDialog.askopenfilename()
filetype = resDir[(resDir.rfind('.')):]
filename = resDir[(resDir.rfind('/') + 1):-(len(filetype))]
s.send("SEND|name:" + filename + "|type:" + filetype)
fileToSend = open(resDir, "rb")
messege = fileToSend.read()
s.send(messege)
fileToSend.close()
isSendingFile = False
You could try to keep a reference to the main window:
import os
try: # Python 2
from Tkinter import Tk
from tkSimpleDialog import askstring
from tkFileDialog import askopenfilename
except ImportError: # Python 3
from tkinter import Tk
from tkinter.simpledialog import askstring
from tkinter.filedialog import askopenfilename
root = Tk()
root.withdraw() # hide main window
message = askstring("Message", "What is the message?")
if message == "SEND":
resdir = askopenfilename()
root.destroy() # done with gui
path, filetype = os.path.splitext(resdir)
filename = os.path.basename(path)