I am having trouble searching for the method to assign to a Push Button the ability to choose a directory. I found this how to have a directory dialog in Pyqt, but I am still unsure about the method.
For example, I have a push button called new_directory and I have this code self.new_directory.clicked.connect(self.pick_new). What do I need to put into the function pick_new so that when new directory is clicked I can choose a new directory and have this stored in a variable?
Thanks!
I think this might help you.
With this you can get the directory.
def pick_new():
dialog = QtGui.QFileDialog()
folder_path = dialog.getExistingDirectory(None, "Select Folder")
return folder_path
Related
My scrip ist currently using QtWidgets.QFileDialog.getOpenFileNames() to let the user select files within Windows explorer. Now I´m wondering if there is a way to let them select also folders, not just files. There are some similar posts, but none of them provides a working solution. I really dont want to use the QFileDialog file explorer to get around this.
QFileDialog doesn't allow that natively. The only solution is to create your own instance, do some small "patching".
Note that in order to achieve this, you cannot use the native dialogs of your OS, as Qt has almost no control over them; that's the reason of the dialog.DontUseNativeDialog flag, which is mandatory.
The following code works as much as static methods do, and returns the selected items (or none, if the dialog is cancelled).
def getOpenFilesAndDirs(parent=None, caption='', directory='',
filter='', initialFilter='', options=None):
def updateText():
# update the contents of the line edit widget with the selected files
selected = []
for index in view.selectionModel().selectedRows():
selected.append('"{}"'.format(index.data()))
lineEdit.setText(' '.join(selected))
dialog = QtWidgets.QFileDialog(parent, windowTitle=caption)
dialog.setFileMode(dialog.ExistingFiles)
if options:
dialog.setOptions(options)
dialog.setOption(dialog.DontUseNativeDialog, True)
if directory:
dialog.setDirectory(directory)
if filter:
dialog.setNameFilter(filter)
if initialFilter:
dialog.selectNameFilter(initialFilter)
# by default, if a directory is opened in file listing mode,
# QFileDialog.accept() shows the contents of that directory, but we
# need to be able to "open" directories as we can do with files, so we
# just override accept() with the default QDialog implementation which
# will just return exec_()
dialog.accept = lambda: QtWidgets.QDialog.accept(dialog)
# there are many item views in a non-native dialog, but the ones displaying
# the actual contents are created inside a QStackedWidget; they are a
# QTreeView and a QListView, and the tree is only used when the
# viewMode is set to QFileDialog.Details, which is not this case
stackedWidget = dialog.findChild(QtWidgets.QStackedWidget)
view = stackedWidget.findChild(QtWidgets.QListView)
view.selectionModel().selectionChanged.connect(updateText)
lineEdit = dialog.findChild(QtWidgets.QLineEdit)
# clear the line edit contents whenever the current directory changes
dialog.directoryEntered.connect(lambda: lineEdit.setText(''))
dialog.exec_()
return dialog.selectedFiles()
I would like to open a new browser by clicking Button from python tkinker GUI and new directory need to be saved and display on GUI.
I am able to open current directory with command below;
import os
subprocess.Popen('explorer "C:\temp"')
cur_path = os.path.dirname(__file__)
my question is how to save the active browser dir and display on GUI after Step A/B above?
First of all, the imports needed for this answer:
import os
import tkinter as tk # if using Python 3
import Tkinter as tk # if using Python 2
Let's say that your button has been defined.
Here is some sample code which will get the current directory:
curr_directory = os.getcwd() # will get current working directory
If you're looking to set up a GUI to ask the user to select a file, use:
name = tkinter.tkFileDialog.askopenfilename(initialdir = curr_directory,title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
print(name)
Which will store the file that they have chosen, with the directory they start at set to curr_directory which is the current directory.
If you are instead looking to set up a GUI in which the user chooses a directory, you can use:
dir_name = tk.tkFileDialog.askdirectory()
This will store the name of the directory they have chosen in the dir_name variable.
For more information, check out this link on how to use the file dialog. Alternatively, you can check the general tkinter documentation here (for Python 2) and here (for Python 3). If you need a reference to the file dialog, this is a good source.
I am making a program to manage a database and i need a nice way of choosing the save locations of files within the program. I was wondering if it is possible to open windows explore from my program, select a folder to save a file in, enter the file name and return the file path as a string to the main program.
Look up the Tkinter options in tkFileDialog
I don't think you necessarily need to put together a fully working GUI, you can simply call the method and select a folder location and then use that selected location in your code.
A simplistic example would be:
import Tkinter, tkFileDialog
root = Tkinter.Tk()
x = tkFileDialog.askopenfilename() # Can pass optional arguments for this...
root.destroy()
I am trying to figure out how to walk a tree and then display the output in a window that a user can navigate through much like that on the left hand side of my computer. Eventually I plan to have a fully browsable window just like you have on the right hand side. Here is what I have so far, I guess it is a mix of pseudo and actual code. This is for use on a Linux machine using python. I'm not looking for any code but mainly help as to how I can accomplish this with tkinter. Perhaps it is just me but I cannot find much help that helps me solve my problem - most just tell me how to display the directories etc. Any help would be greatly appreciated.
I want this window to look like this
My Documents <--------starting directory
My pictures<------subdirectory
picture1.jpg<-inside of subdirectoy
picture2.jpg
1234.exe<---------random file inside of my documents
I want to have a small folder picture next to a directory or a subdirectory also.
start at root
create window with tk
for dirname,subdirList,filelist in os.walk(root)
create new item(dirname)
for i in subdirList: #not sure what I would have to do to only
have subdirs showing once the directory was
clicked once
append i to item 1
for fname in fileList:
append fname to item 1
else:
item +=1
You can do it using the widget ttk.Treeview, there is a demo dirbrowser.py that does that. So all I can do here is give a stripped version of it and explain how it works. First, here is the short version:
import os
import sys
import Tkinter
import ttk
def fill_tree(treeview, node):
if treeview.set(node, "type") != 'directory':
return
path = treeview.set(node, "fullpath")
# Delete the possibly 'dummy' node present.
treeview.delete(*treeview.get_children(node))
parent = treeview.parent(node)
for p in os.listdir(path):
p = os.path.join(path, p)
ptype = None
if os.path.isdir(p):
ptype = 'directory'
fname = os.path.split(p)[1]
oid = treeview.insert(node, 'end', text=fname, values=[p, ptype])
if ptype == 'directory':
treeview.insert(oid, 0, text='dummy')
def update_tree(event):
treeview = event.widget
fill_tree(treeview, treeview.focus())
def create_root(treeview, startpath):
dfpath = os.path.abspath(startpath)
node = treeview.insert('', 'end', text=dfpath,
values=[dfpath, "directory"], open=True)
fill_tree(treeview, node)
root = Tkinter.Tk()
treeview = ttk.Treeview(columns=("fullpath", "type"), displaycolumns='')
treeview.pack(fill='both', expand=True)
create_root(treeview, sys.argv[1])
treeview.bind('<<TreeviewOpen>>', update_tree)
root.mainloop()
It starts by listing the files and directories present in the path given by sys.argv[1]. You don't want to use os.walk here as you show only the contents directly available in the given path, without going into deeper levels. The code then proceeds to show such contents, and for directories it creates a dummy children so this Treeview entry will be displayed as something that can be further expanded. Then, as you may notice, there is a binding to the virtual event <<TreeviewOpen>> which is fired whenever the user clicks an item in the Treeview that can be further expanded (in this case, the entries that represent directories). When the event is fired, the code ends up removing the dummy node that was created earlier and now populates the node with the contents present in the specified directory. The rest of the code is composed of details about storing additional info in the Treeview to make everything work.
I think tkinter would be a bad choice for this. Other libraries like wxPython, PyQt or GTK does have GUI components which will help you achieve this with minimum effort.
I'm writing a python script that takes a file one at a time or recursively through folders and moves them to a new location. The script takes one parameter (the current path of the file). I want to be able to use the selected item in an explorer window as the variable.
I am making a contextual menu through the regedit files that is labeled "Send to Server". I currently have the appropriate regedit files created and pointed to the location of the command python.exe "path\to\python\file.py
long story short, I want a contextual menu to pop up that says "Send to Server" when a file is right clicked and when executed uses the selected file's or folder's path as the only variable I need. So far I have come across tkFileDialog (not quite what I want) ctypes and win32 modules but I can't quite figure out the last three modules or whether or not they will help
As a side note. I have created a python script that does this exact thing on mac osx. Much easier with macs 'services' feature.
If you put a shortcut to this script (written for Python 3) in the user's "SendTo" folder (%USERPROFILE%\SendTo), it will pop up a directory dialog when selected from the right-click SendTo menu. The dialog works for network locations as well. When the script runs, the full path to the selected file/folder is in sys.argv[1]. Currently it just shows the selected destination path in a message box. You can change the extension to pyw if you don't want a console.
import os, sys
from tkinter import Tk, filedialog
from tkinter.messagebox import showinfo
class Dialog:
def __init__(self, path):
self.path = path
self.dst_path = ''
self.root = root = Tk()
root.iconify()
root.after_idle(self.askdirectory)
root.mainloop()
def askdirectory(self):
self.dst_path = filedialog.askdirectory(initialdir=self.path)
showinfo('Selected Path', self.dst_path)
self.root.destroy()
if __name__ == '__main__':
if len(sys.argv) > 1:
path = sys.argv[1]
if os.path.isfile(path):
path = os.path.dirname(path)
dialog = Dialog(path)
#if dialog.dst_path: do_something(dialog.dst_path)