To allow my users to choose a file I'm using tkinter's askopenfilename. The function works fine, but after opening a file or pressing cancel the file open window goes empty and just stays open. The rest of the program moves forward correctly but even once the program ends the window remains open. And I'm not getting any errors. Is there anyone else who has experienced this behavior and has a solution? Alternatively, do you know any other easy methods of implementing a GUI file open prompt?
here's a pertinent example:
from Tkinter import Tk
from tkFileDialog import askopenfilename
Tk().withdraw()
filename = askopenfilename()
print(filename)
Related
I was trying to open a code with pycharm and the following lines are the begining . but it doesn't open any window . what should I do ?
import tkinter
mainwindow=tkinter.Tk()
mainwindow.title("Calculator")
mainwindow.geometry('480x240')
buttonOne= tkinter.Button(mainwindow,text='1')
it runs and instantly closes without opening any window
In order to make sure the window doesn't close you need the mainloop function.
import tkinter
mainwindow=tkinter.Tk()
mainwindow.title("Calculator")
mainwindow.geometry('480x240')
buttonOne= tkinter.Button(mainwindow,text='1')
tkinter.mainloop()
I am trying to make a Tkinter script to select files through Windows File Explorer. I don't need the Tkinter window to show, just the File Explorer interface.
import tkinter
from tkinter import filedialog
import os
window = tkinter.Tk()
#window.geometry("1x1")
window.withdraw()
def open_files():
files = filedialog.askopenfiles(mode='r')
global filenames
filenames = [os.path.abspath(file.name) for file in files]
window.destroy() # analysis:ignore #says "window" is undefined becasue of "del window" below
window.after(0, open_files)
window.mainloop()
del window
The first time I run this in Spyder, if window.withdraw() is not commented out, the console just shows runfile(*my_file_name*) and the code does... something... in the background, but nothing seems to actually happen. Nothing changes on-screen, but I cannot type in the console so I know the code is running.
If I open a new console tab and run the code with window.withdraw() commented out, everything works, and the Tkinter GUI is visible. If I then run this code again in the same tab, with window.withdraw() not commented out, then the code works as intended, with only the File Explorer window opening up, and the Tkinter GUI staying hidden. This is the case even if I click the "Remove all variables" button in Spyder, so as far as I understand the code is not saving any variables that allow it to run properly after the first time.
My question is, why does this code work the 2nd, 3rd, 4th, etc. time I run it, but not the first time?
I kept playing around, and changed -alpha to alpha and got this error:
TclError: wrong # args: should be "wm attributes window ?-alpha ?double?? ?-transparentcolor ?color?? ?-disabled ?bool?? ?-fullscreen ?bool?? ?-toolwindow ?bool?? ?-topmost ?bool??"
So I ended up changing window.attributes('-alpha',0) to window.attributes('-topmost',True, '-alpha',0), and this works! It brings up File Explorer on the first run without showing the Tkinter window. Thank you #Thingamabobs for your help.
My final code is:
import tkinter
from tkinter import filedialog
import os
window = tkinter.Tk()
window.attributes('-topmost',True, '-alpha',0)
filenames = [os.path.abspath(file.name) for file in filedialog.askopenfiles(mode='r')]
window.destroy()
del window
Tkinter is a great package and filedialog has some very helpful features. Both askopenfilename and asksaveasfilename have the 'filetypes' attribute, but it works differently for each one.
With askopenfilename it provides options in the GUI and returns the filetype, BUT
with asksaveasfilename it only provides options in the GUI and does not return the filetype. Example code is shown below:
import tkinter as tk
from tkinter import filedialog
old_file_name = filedialog.askopenfilename(title = "Choose file",filetypes=\
(('All files','*.*'),\
('tagData','*.tagData'),\
('FDAX files','*.fdax'),\
('CSV files','*.csv')))
new_file_name = filedialog.asksaveasfilename(initialdir = "/",filetypes=\
(('tagData','*.tagData'),\
('FDAX files','*.fdax'),\
('CSV files','*.csv'),\
('XLS files','*.xls')))
print(old_file_name)
print(new_file_name)
Output:
C:/Users/christian.abbott/Desktop/FDAX_Error/example.csv
C:/Users/christian.abbott/Desktop/example
I have looked for good filedialog documentation but have not been able to find it. Why does the package behave this way? Is there a better option to extract the full path of a user-prompted file path?
I had this same problem with Python 3 on Windows 10. I managed to solve it by removing the * before the period in the file types tuples. The following change should, hopefully, do what you want:
new_file_name = filedialog.asksaveasfilename(initialdir = "/",filetypes=\
(('tagData','.tagData'),\
('FDAX files','.fdax'),\
('CSV files','.csv'),\
('XLS files','.xls')))
This worked for me, good luck!
This has nothing to do with tkinter. Windows file explorer hides the file extensions from you by default. So when you see a "example" file in file explorer, Windows is lying to you. The actual filename is "example.csv". Most programs (including python) do not lie, and show you the actual filename.
For entering the filename tkinter uses the OS file selection widget and just displays whatever it returns. I tested it with Win7 and it did not include the extension; however in Debian Jessie it did. If it does not you can always add some code to do it for the user:
if not new_file_name.endswith(('tagData','fdax','csv','xls')):
new_file_name += '.csv'
Search in the start menu for "show extensions" and you can turn this "feature" off.
I have a selection of excel data that I am analyzing, and have just recently added the ability for the user to open the file explorer and locate the file visually, as opposed to entering the file location on the command line. I found this question (and answer) to make the window appear, which worked for a while.
I am still using the command line for everything except locating the file. Currently, this is a skeleton of what I have to open the window (nearly identical to the answer of the question linked above)
Tk().withdraw()
data_file_path = askopenfilename()
# other code with prompts, mostly print statements
Tk().withdraw()
drug_library_path = askopenfilename()
Once the code reaches the first two lines of code, the command line just sits with a blinking cursor, like it's waiting for input (my guess, for askopenfilename() to return a file location), but nothing happens. I can't ctrl+C to get out of the program, either.
I have found this question, which is close to what I'm looking for, but I'm on Windows, not Mac, and I can't even get the window to open -- most questions I see talk about not being able to close the window.
Thanks for any help!
Note: At this point in the program, no data from excel has been loaded. This is one of the first lines that is ran.
Try easygui instead. It's also built on tkinter, but unlike filedialog it's made to run without a full GUI.
Since you are using Windows, use this command in the command line (not in python) to install easygui:
py -m pip install easygui
then try this code:
import easygui
data_file_path = easygui.fileopenbox()
# other code with prompts, mostly print statements
drug_library_path = easygui.fileopenbox()
If you want to use an internal module, you can import tkFileDialog, and call:
filename = tkFileDialog.askopenfilename(title="Open Filename",filetypes=(("TXT Files","*.txt"),("All Files","*.*")))
I use this in many projects, you can add arguments such as initialdir, and you can specify allowable filetypes!
I had the same problem, but I found that the issue was that I was getting input with input() before I called askopenfilename() or fileopenbox().
from tkinter import Tk
from tkinter.filedialog import askopenfilename
var = input()
Tk().withdraw()
filepath = askopenfilename()
I simply switched the positions of askopenfilename() (or fileopenbox()) and input(), and it worked as usual.
Tk().withdraw()
filepath = askopenfilename()
var = input()
I'm developing an interface with Tkinter that makes use of a file dialog with tkFileDialog.
I want to run a function immediately after the user has chosen a file from the dialog box.
With buttons, we have a command keyword from which we run a function (usually named def callback():). Is there a similar keyword for the file dialog or askopenfilename?
The askopenfilename function consists of the opening of a dialog, and returns immediately when the latter was closed (including when a file has been selected).
Put your callback right after this function to have it run right after the closing of the dialog.
For instance:
from tkinter.filedialog import askopenfile
fileDescriptor = askopenfilename()
print(fileDescriptor)
will open a file selection dialog, and as soon as the user has selected a file, the corresponding object that was created will be printed out.