Right now I am using Tkinter to prompt the user for a file.
Tk().withdraw() # keep the root window from appearing
file_path = askopenfilename() # show dialog box and return file path
# check if extension is valid
If the user selected the wrong file type, I re-prompt them with a new window.
Is there a way, instead, to keep the same tkinter window open unless the file selected is valid?
so instead of this:
# 1) prompt user to open file
# 2) close file browser window
# 3) check if extension is valid
# 4) if not, print error and re-prompt user with new browser window
I want to do this:
# 1) prompt user to open file
# 2) check if extension is valid while keeping window open
# 3) if not, print error, re-prompting with same window
Any help is appreciated.
If you want the user to open a particular file type, use the filetypes argument. It takes a list of file type definitions, which you specify as a description and an extension:
filepath = askopenfilename(filetypes = [
('Text Files', '.txt'),
('Python Scripts', '.py'),
('INI Files', '.ini')
])
You could set the file browser window to only display the file type you want to user to select, but they can get around that rather easy by selecting the type drop down box. You could however on file select (user clicks OK to select the file and close the file browser window) check to see if the file extension is one of the types you desire and if it is not simple clear the file path variable and call the file browser open function again. That way they are trapped in selecting a file until they select the correct file type. This does however present the issue of them possible no knowing why they are back where they started from, so you may want to add a popup window or something before reopening the file browser window to make it a little more user friendly.
Related
I have created an exe file using autopy to exe.
At the beginning, I ask the user to enter the file to use using the following code:
filename = filedialog.askopenfilename(initialdir="/", title="Select file to convert")
But when the user click on "Cancel" or hit the "X" in the upper right side, an error code appear as you can see on the image
how to stop the code from continue running if the user click one of the two option mentioned above so that the error code will not appear?
I know some questions have already been asked about similar subject but I couldn't adapt them to my case. I hope I have been clear enough
The root cause of the FileNotFoundError is that it cannot find the file with an empty string path, which it will never find that one.
I will elaborate on what #Sagitario has explained. The os.path.exists(filename) used to check if the filename is valid and exists or not:
import os
if os.path.exists(filename):
do_something() # like trying to open a file in this condition.
else:
print(f"{filename} not found, please select other path")
Nevertheless, if your path is empty, it will surely go in an else condition. Instead, you can check the path input that it's not empty and exists.
In addition, the try-except block can help handle the error here. But you also need to solve the main problem of an empty file path somewhere in your code, by using the above if condition to verify the file path.
try:
filename = filedialog.askopenfilename(initialdir="/", title="Select file to convert")
# ... the rest of your code relating the file opening ...
except FileNotFoundError:
print(f"{filename} not found, please select other path")
Just check if the provided path exists with os.path.exists(filename)
I am trying to use the browse function in PySimpleGUI. I have used PySimpleGUI file browser specific file type to find out how to browse. However there are two file types that I want to choose from and multiple files need to be selected for this to work. My question:
How do you use the browse function for browsing two types of files? and also How do you allow multiple files to be browsed? and finally How do you tell each file apart?
I know that there is a key function for getting data but how can I do that for more than one file.
In case you are a tiny bit confused:
The user must select the browse function and must be able to choose from .txt and .Docx files while selecting more than one file. The program must be able to tell the difference between the files so a function can be run on each file separately.
My code so far:
import PySimpleGUI as sg
sg.theme('DarkAmber') # Add a touch of color
# All the stuff inside your window.
layout = [ [sg.FileBrowse(file_types=(("Text Files", "*.txt"),))],
[sg.Button('Lets GO!!!')]
]
# Create the Window
window = sg.Window('Test', layout).Finalize()
window.Maximize()
Can someone finish this code?
According to the documentation:
file_types=(("Text Files", "*.txt"),("CSV Files", "*.csv"),)
works.
I am trying to use PyQt to open a file dialog and then allow the user to select a new location to create a new directory which will be used in the program.
Currently my code looks like this:
dialog = QFileDialog()
dialog.setOption(QFileDialog.ShowDirsOnly, True)
dialog.setWindowTitle(title)
dialog.setAcceptMode(QFileDialog.AcceptOpen)
dialog.setNameFilter(nameFilter)
dialog.setFileMode(QFileDialog.Directory)
if dialog.exec_() == QFileDialog.Accepted:
return dialog.selectedFiles()[0]
However in the file dialog all the files are still shown and their is no option to select a directory if the user want to overwrite it.
The wanted outcome would show just the directories in the explorer.
Is there a way of doing this using PyQt file dialogs?
I have a GUI with a tool button next to a Combobox. The tool button opens a directory browser to select a file and then adds that file Name to the Combobox drop-down list.
def showFileOpenDialogLoad(self):
""" Opens dialog to get Load file path """
filename = QFileDialog.getOpenFileName(self, 'Open file',
'/home')
self.comboBoxFilePathLoad.addItem(filename)
This works perfectly, however, I then want the Combobox to directly display the last added filename. I have tried using .insertItem(0,filename)instead and then setting self.comboBoxFilePathLoad.currentIndex = -1but it still displays the first added filename even though in the Dropdown list the last added filename is now above the old and displayed one. Apparently in C# you would use cmbBox.SelectedIndex = cmbBox.Items.count -1 but Pyqt does not have a SelectedIndexmethod.
This does not seem like such a difficult question but somehow I can not find a solution to it online... The QComboBox Class Reference does not explain count and CurrentIndex either. Thank you for your help!
I am using static method:
path = QtGui.QFileDialog.getSaveFileName(self, SAVE_TO_STR, NAME_STR, 'CSV(*.csv)')
where I get path as full_path\some_name.csv
but I need to set different language to buttons and labels of dialog, so I've been looking at docs and find out that I can't do that with static method and I've come up with this code:
ddd = QtGui.QFileDialog(self, SAVE_TO_IN_OTHER_LANGUAGE_STR, NAME_STR, 'CSV(*.csv)')
ddd.setAcceptMode (QtGui.QFileDialog.AcceptSave)
ddd.setLabelText( QtGui.QFileDialog.Accept, "Save - in other language" )
ddd.setLabelText( QtGui.QFileDialog.Reject, "Cancel - in other language" )
ddd.setLabelText( QtGui.QFileDialog.LookIn, "Look in - in other language" )
if ddd.exec_():
path = QtCore.QString(ddd.selectedFiles()[0])
I am trying to set it to look like first one so my questions are:
path I get is ok, but missing .csv at the end, so it saves file with no extension.
should I manually add .csv at the end of the path?
when I choosing where to save and click on folder, "save" button turns to "open". How to change that button text to "Open" in other language?
folders list at the left side of dialog is not complex as when I use QtGui.QFileDialog.getSaveFileName() , it shows only My Computer and User, instead of modern tree with favorites and partitions under My Computer.
1) path I get is ok, but missing .csv at the end, so it saves file with
no extension. should I manually add .csv at the end of the path?
Answer: I think you shouldn't manually add .csv at the end of the path. In PyQt API have this solution to solve it, use QFileDialog.setDefaultSuffix (self, QString suffix);
pathQFileDialog = QtGui.QFileDialog(self)
pathQFileDialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
pathQFileDialog.setNameFilter('CSV(*.csv)')
pathQFileDialog.setDefaultSuffix('csv')
Reference: http://pyqt.sourceforge.net/Docs/PyQt4/qfiledialog.html#setDefaultSuffix
2) when I choosing where to save and click on folder, "save" button
turns to "open". How to change that button text to "Open" in other
language?
Answer: My opinion of PyQt, No. In Qt (C++) at file qfiledialog.cpp I found your problem in method void QFileDialogPrivate::_q_updateOkButton() at line between 2886 and 2888. It force "&Open" label;
button->setEnabled(enableButton);
if (acceptMode == QFileDialog::AcceptSave)
button->setText(isOpenDirectory ? QFileDialog::tr("&Open") : acceptLabel);
Reference: https://qt.gitorious.org/qt/qt/source/57756e72adf2081137b97f0e689dd16c770d10b1:src/gui/dialogs/qfiledialog.cpp#L2796-2888
3) folders list at the left side of dialog is not complex as when I use
QtGui.QFileDialog.getSaveFileName() , it shows only My Computer and
User, instead of modern tree with favorites and partitions under My
Computer.
Answer: Because on Windows, Mac OS X and Symbian^3, this static function (QtGui.QFileDialog.getSaveFileName()) will use the native file dialog and not a QFileDialog.
Reference: pyqt.sourceforge.net/Docs/PyQt4/qfiledialog.html#getSaveFileName
Regards,