I want to store a selected file's location as a string in Python. I am trying to use QFileDialog to accomplish this, I have:
self.filedialog = QtGui.QFileDialog(self)
self.filedialog.show()
filepath = str(self.filedialog.getOpenFileName())
This opens two QFileDialog windows. Interestingly, one of the windows does not inherit the 'style' of my GUI, set my setStyle, but does return the filepath string. The other QFileDialog does inherit the style, but can not return the filepath string. I have found the QFileDialog documentation helpful, but have not been able to create a QFileDialog box that both produces the filepath string, and inherits the style of my GUI. What mistake am I making?
You actually created 2 windows.
The function QFileDialog.getOpenFileName is static, meaning that it creates its own QFileDialog object, shows the window, waits for the user to select a file and returns the choosen filename.
You should only need that line:
filepath = str(QFileDialog.getOpenFileName())
If you set the style at the application level (with QApplication.setStyle), it might be applied to the window if you use the non-native dialog:
filepath = str(QFileDialog.getOpenFileName(options=QFileDialog.DontUseNativeDialog)))
getOpenFileName is a convenience function that "creates a modal file dialog". That's why you're getting the second dialog.
Use filedialog.exec() to show the dialog and fileDialog.selectedFiles() to get the filename.
exec is a reserved word in python, you must use exec_().
dialog = QFileDialog(self)
dialog.exec_()
for file in dialog.selectedFiles():
print file
Related
I made a PyQt5 application on Windows and now I want to use the application on a Mac. The app prompts the user to select a couple different files. I used the title of the QFileDialog window to let the user know which files like so:
instrument_file_raw=QFileDialog().getOpenFileName(self, "Select Instrument File","","Excel (*.xlsx)")
instrument_file_raw=str(instrument_file_raw[0])
if instrument_file_raw=="":
error_dialog = QErrorMessage(self)
error_dialog.showMessage('No filename entered')
return
run_list_file=QFileDialog().getOpenFileName(self, "Select Run List File","","Excel (*.xlsx)")
run_list_file=str(run_list_file[0])
if run_list_file=="":
error_dialog = QErrorMessage(self)
error_dialog.showMessage('No filename entered')
return
However when I run the same code on Mac there is no window title shown when the file explorer opens. Even if I manually set the window title by
instrument_file_window=QFileDialog()
instrument_file_window.setWindowTitle("Select Instrument File")
instrument_file_raw=instrument_file_window.getOpenFileName(self,"Select Instrument File","","Excel (*.xlsx)")
Is there a way to show the window title on Mac? How can I indicate to the user what to input?
This is a known problem that has not been fixed yet (see QTBUG-59805) and related to a change to macOS starting from version 10.11 (El Capitan).
If you do need to display the caption, the only solution is to use the non native file dialog option.
path, filter = QtWidgets.QFileDialog.getOpenFileName(
self, "Select Instrument File", "", "Excel (*.xlsx)",
options=QtWidgets.QFileDialog.DontUseNativeDialog
)
Note that getOpenFileName, like other similar functions, is a static function: it constructs and configure a new file dialog instance and then returns it. In fact, if you closely look at my code above, I didn't use any parentheses after QFileDialog.
Besides the options in the arguments, there's no way to access the created dialog if it's native, and there is only limited access for non native dialogs, but only by using complex systems (like a timer that checks for the top level widget) which are also not always reliable.
The above also means that:
you don't need to create a new instance, since it won't be used;
for the same reason, setting any property (like the window title) has absolutely no effect;
I am trying to make a copy of Notepad. Here, I want to get the name of the title of the tkinter window.
I need it because if the title of the window is Untitled - Notepad then I want to quit the program directly but if the title name is not Untitled - Notepad then I want to display message if you want to really quit the program.
How can I do so?
You can just use:
if root.title() == "Untitled - Notepad":
# do something
But that might not be the best way to do it.
#tobias_k put it well:
Don't read the title of your window to determine whether the file you are currently editing is "unnamed", or has already been saved, or has been changed since the last save. Instead, keep this information in some dedicated attributes of your editor class, and use those to determine the title of the editor window. Otherwise, it will be a mess if you ever decide to change the format of the title. Also, what if the file is literally named "Untitled"?
I am new in tkinter please help me out .
I have implemented a module(PDF2Text.Py) that its class has a function (convert_pdf_to_txt(path)) that takes a path of a pdf file and converts the pdf file into text.
I also implemented another module(TopicModeling.py) that its class has a function (creat_LDA_model(text)) that takes a text and do topic modeling on the text.
Now, I want the tkinter GUI that is, upon clicking the "Browse" button it browses the path with filedialog.askopenfilename and its command function send the given path to convert_pdf_to_txt(path) function of PDF2Text.Py.
Then by clicking the "Model" button, its command function returned text should be sent to creat_LDA_model(text) function in TopicModeling.py and show the result in an Entry widget or any other widget types .
I would like to know the structure of the GUI module;
how to call or get and set the parameters to other modules/functions from the GUI module in command functions of the buttons.
thanks
Seems like you have multiple questions here. I believe one of them is how to start askopenfilename in a particular folder. Once the file name is returned, i can be passed to another function.
fname = askopenfilename(initialdir = r'c:\somepath', filetypes=(("Statement files", "*.pdf"),))
To call other functions you have written, import the module, let's cal it ReadPdf.py, use something like this.
import ReadPdf
PdfOut = ReadPdf.ReadPDFData(fname)
CCStmtTxns = ReadPdf.ReadPDFData(CreditCardPDFDataPathandFile)
I'm attempting to create a dialog which contains two child widgets: on the left side a QFileDialog instance so users can select files, and on the right side a separate widget which will be used to show a preview of the selected file if it is of a certain type.
The problem is that the dialog opens up and I can see the "preview" widget just fine, but the QFileDialog is not showing up at all.
This short example demonstrates my problem:
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
app = QApplication([])
main_dialog = QDialog()
main_dialog.setWindowTitle('My Dialog')
layout = QHBoxLayout(main_dialog)
file_dialog = QFileDialog(main_dialog, Qt.Widget)
file_dialog.setOption(QFileDialog.DontUseNativeDialog)
layout.addWidget(file_dialog)
preview = QLabel('Preview', main_dialog)
layout.addWidget(preview)
main_dialog.show()
app.exec_()
Some things that I've tried:
Add file_dialog.show() before/after main_dialog.show(): this shows up the QFileDialog, but in a different window; I want the file dialog to appear inside main_dialog, not as a separate window;
Do not pass Qt.Widget to the QFileDialog constructor, to no effect;
Do not pass main_dialog as parent to QFileDialog, again no effect;
Change main_dialog to a QWidget just to see if it changed anything, it did not;
I've searched the docs but did not find a suitable solution.
Any hints? Also, suggestions on how to accomplish the task of allowing the user to select a file and display a preview of the file in the same window are welcome.
Context: this is a port of an old application written for Qt3. Qt3's QFileSystem dialog had this "preview" functionality built-in; I'm trying to reproduce the same functionality in Qt5.
Versions
Python 2.7
PyQt 5.5.1
I've also tried with Python 3.6 (from conda-forge) but obtained the same behavior.
You need to turn off the Qt.Dialog flag in the file dialog's windowFlags...
file_dialog.setWindowFlags(file_dialog.windowFlags() & ~Qt.Dialog)
Otherwise the QFileDialog will always be created as a top level window. Works for me anyway.
I have just now begun with GUI programming in Python 2.7 with Tkinter.
I want to have a button Browse, which when clicked opens the Windows File Explorer and returns the path of file selected to a variable. I wish to use that path later.
I am following the code given here. It outputs a window displaying 5 buttons, but the buttons do nothing. On clicking the first button, it doesn't open the selected file.
Likewise, on clicking the second button, the askopenfilename(self) function is called and it should return a filename. Like I mentioned, I need that filename later.
How to I get the value returned by the function into some variable for future use?
There is no point in using return inside a callback to a button. It won't return to anywhere. The way to make a callback save data is to store it in a global variable, or an instance variable if you use classes.
def fetchpath():
global filename
filename = tkFileDialog.askopenfilename(initialdir = 'E:')
FWIW (and unrelated to the question): you're making a very common mistake. In python, when you do foo=bar().baz(), foo takes the value in baz(). Thus, when you do this:
button = Button(...).pack()
button will take the value of pack() which always returns None. You should separate widget creation from widget layout if you expect to save an actual reference to the widget being created. Even if you're not, it's a good practice to separate the two.