def directoryBox(self, title=None, dirName=None):
self.topLevel.update_idletasks()
options = {}
options['initialdir'] = dirName
options['title'] = title
options['mustexist'] = False
fileName = filedialog.askdirectory(**options)
if fileName == "":
return None
else:
return fileName
python类askdirectory()的实例源码
def chooseDialogFiles(self):
filenames = filedialog.askopenfilenames(
defaultextension = '.SPE',
filetypes = [('WinViewer Documents', '.SPE'), ('all files', '.*'),],
parent = self,
title = "Select .SPE files",
multiple = True,
)
print(filenames)
if len(filenames) == 0:
return
self.chooseFilePath = os.path.dirname(
os.path.realpath(filenames[0])
)
print("select:", self.chooseFilePath)
self.chooseFileOutDir = filedialog.askdirectory(
initialdir = self.chooseFilePath,
parent = self,
title = "Select output Directory",
mustexist = False,
)
print("out:", self.chooseFileOutDir)
if not self.checkDir(self.chooseFileOutDir):
return
self.convertFiles(filenames, self.chooseFileOutDir)
def get_dirname():
Tk().withdraw()
print("Initializing Dialogue...\nPlease select a directory.")
dirname = askdirectory(initialdir=os.getcwd(),title='Please select a directory')
if len(dirname) > 0:
print ("You chose %s" % dirname)
return dirname
else:
dirname = os.getcwd()
print ("\nNo directory selected - initializing with %s \n" % os.getcwd())
return dirname
def chooseDialogDir(self):
self.chooseDirPath = filedialog.askdirectory(
initialdir = self.chooseDirPath,
parent = self,
title = "Select Directory contains .SPE files",
)
print("select:", self.chooseDirPath)
if len(self.chooseDirPath) == 0:
return
self.chooseDirOutDir = filedialog.askdirectory(
initialdir = self.chooseDirPath,
parent = self,
title = "Select output Directory",
mustexist = False,
)
# TODO check wirte permission first
if not self.checkDir(self.chooseDirOutDir):
return
filenames = yieldFilesUnderDirectory(self.chooseDirPath,
match = "*.SPE")
if filenames is None:
messagebox.showinfo("Convert result", "No .SPE files under this directory")
return
self.convertFiles(filenames, self.chooseDirOutDir,
oldPrefix = self.chooseDirPath)
def __init__(self, response=str, text="", title=None, accept=0, **options):
if response is bool:
self.dialog = [askyesno, askokcancel, askretrycancel][accept]
else: self.dialog = {None:showinfo, str:askstring, int:askinteger, float:askfloat,
0:askopenfilename, 1:asksaveasfilename, 2:askdirectory}[response]
self.options = options.copy()
if "initialdir" in options:
self.options["initialdir"] = abspath(options["initialdir"])
if type(response) is int:
self.args = tuple()
if title: self.options["title"] = title
else:
if title is None:
title = "Info" if response is None else "Confirm" if response is bool else "Input"
self.args = title, text
def open_pack(self):
pack = filedialog.askdirectory(initialdir=self.resourcepack_location)
if os.path.isfile(pack + "/pack.mcmeta"):
# messagebox.showinfo("Information", "Found 'pack.mcmeta'.")
self.parent.directory = pack
self.parent.cmd.tree_refresh()
self.destroy()
else:
messagebox.showerror("Error", "Could not find 'pack.mcmeta'.")
def install_pack(self):
pack = filedialog.askdirectory()
if os.path.isfile(pack + "/pack.mcmeta"):
# messagebox.showinfo("Information", "Found 'pack.mcmeta'.")
try:
shutil.move(pack, self.resourcepack_location)
except shutil.Error:
messagebox.showerror("Error", "This pack is already installed.")
else:
messagebox.showerror("Error", "Could not find 'pack.mcmeta'.")
def select_folder():
from tkinter import filedialog
selected = filedialog.askdirectory(initialdir=getcwd(),
title='Select IVS Data Folder')
_folderVar.set(selected)
print('Selected data folder: {}'.format(_folderVar.get()))
def select_export():
selected = filedialog.askdirectory(initialdir=getcwd(),
title='Select Export Tables Folder')
_tableFolderVar.set(selected)
print('Selected export table folder: {}'.format(_tableFolderVar.get()))
def get_save_path():
Data.save_path = askdirectory()
chosen_save_path_label["text"] = Data.save_path
return Data.save_path
def addListenDir(self):
listenDirPath = filedialog.askdirectory(
parent = self,
title = "Auto convert (listen) .spe under this directory",
initialdir = self.listenDirPath.get(),
)
if not self.checkDir(listenDirPath, autocreate = False, poperror = False):
return
print("listen:", listenDirPath)
if os.path.abspath(listenDirPath) != self.listenDirPath.get():
self.listenDirPath.set(os.path.abspath(listenDirPath))
self.checkListenTask()
def bindListenDir(self):
newOutDir = filedialog.askdirectory(
parent = self,
title = "Auto convert .spe into this directory",
initialdir = self.listenDirPath.get(),
)
if not self.checkDir(newOutDir, autocreate = False, poperror = False):
return
print("bind to:", newOutDir)
self.listenDirOutputPath.set(os.path.abspath(newOutDir))
def _browse(self):
"""Opens a directory browser."""
directory = filedialog.askdirectory(initialdir=self._directory)
self._variable.set(directory)
def on_select_plugins_folder(self, *args):
_plugin_folder = filedialog.askdirectory(title="Choose plugin folder (usually in the ")
if _plugin_folder is not None or _plugin_folder != "":
self.plugins_folder.set(_plugin_folder)
def on_select_install_folder(self, *args):
_install_folder = filedialog.askdirectory(title="Choose install folder (usually in the \"~of\"-folder)")
if _install_folder is not None or _install_folder != "":
self.install_location.set(_install_folder)
def on_select_installation(self, *args):
_install_folder = filedialog.askdirectory(title="Select existing installation")
if _install_folder is not None or _install_folder != "":
self.install_location.set(_install_folder)
self.setup.load_install(_install_folder=_install_folder)
self.setup_to_gui()
def diropenbox(msg=None
, title=None
, default=None
):
"""
A dialog to get a directory name.
Note that the msg argument, if specified, is ignored.
Returns the name of a directory, or None if user chose to cancel.
If the "default" argument specifies a directory name, and that
directory exists, then the dialog box will start with that directory.
"""
title=getFileDialogTitle(msg,title)
boxRoot = Tk()
boxRoot.withdraw()
if not default: default = None
f = tk_FileDialog.askdirectory(
parent=boxRoot
, title=title
, initialdir=default
, initialfile=None
)
boxRoot.destroy()
if not f: return None
return os.path.normpath(f)
#-------------------------------------------------------------------
# getFileDialogTitle
#-------------------------------------------------------------------
def get_output_directory(self):
out_dir=filedialog.askdirectory()
self.out_dir_box.delete('0',tk.END)
self.out_dir_box.insert('end',out_dir)
def directoryBox(self, title=None, dirName=None):
self.topLevel.update_idletasks()
options = {}
options['initialdir'] = dirName
options['title'] = title
options['mustexist'] = False
fileName = filedialog.askdirectory(**options)
if fileName == "":
return None
else:
return fileName
def select_path(self):
file_path = askdirectory()
self.file_path_var.set(file_path)
def asksaveasfilename(self):
if not self.parent.filename:
self.parent.set_info_box(message='Error: No figure has been created yet.')
else:
file_options = {}
file_options['initialdir'] = self.parent.par.run.out_dir
file_options['initialfile'] = re.sub('/.+/', '', self.parent.filename)
file_options['filetypes'] = [('pdf files', '.pdf')]
file_options['parent'] = self.parent
file_options['title'] = 'save figure as'
filename = tkFileDialog.askdirectory(**file_options)
if filename:
copyfile(self.parent.filename, filename)
def set_plot_all_dir(self):
dir_options = {}
dir_options['initialdir'] = self.par.run.out_dir
dir_options['parent'] = self
dir_options['title'] = 'select existing or type new directory'
dir_options['mustexist'] = False
path = tkFileDialog.askdirectory(**dir_options)
if path == '':
return None
else:
return path
def browse(self):
filename= askdirectory()
#print (filename)
for exe in os.listdir(filename):
if exe.endswith(".exe"):
executabile=exe
print (executabile)
command='netsh advfirewall firewall add rule name="Block {}" dir=in action=block program="{}" enable=yes'.format(executabile,executabile)
subprocess.call(command,shell=True)
def main():
user_folder = os.getenv("USERPROFILE")
nier_automata_folder = path.join(user_folder, "Documents", "My Games", "NieR_Automata")
if not path.isdir(nier_automata_folder):
messagebox.showerror("Error", "Could not find Nier;Automata's save folder location. Please select the save folder location")
nier_automata_folder = filedialog.askdirectory()
gamedata_path = path.join(nier_automata_folder, "GameData.dat")
if not path.isfile(gamedata_path):
raise Exception("Could not find NieR_Automata/GameData.dat. Please run Nier;Automata at least once before using this tool.")
# read the gamedata header.
with open(gamedata_path, "rb") as f:
gamedata_header = f.read(12)
locations = ("SlotData_0.dat", "SlotData_1.dat", "SlotData_2.dat")
import collections
saves = collections.OrderedDict()
for location in locations:
savedata_path = path.join(nier_automata_folder, location)
if path.isfile(savedata_path):
saves[location] = SaveGame(savedata_path)
interface = Interface(saves, gamedata_header)
interface.master.title("NieR;Automata Save Editor")
interface.mainloop()
def ask_for_directory(self):
path=tkFileDialog.askdirectory(title='Select Directory For Playlist')
if path:
self.directory.set(path)
print (path)
return self.update_list_box_songs(dirs=path)
def set_directory(self, variable):
"""Return a selected directory name.
ARGS:
variable (tk.Variable): The tkinter variable to save selection as.
"""
selection = filedialog.askdirectory(**self.directory_options)
variable.set(selection)
def install_examples(): # pragma: no cover
"""
Pops up windows to allow the user to choose a directory for installation
of sfc_models examples.
Uses tkinter, which is installed in base Python (modern versions).
:return:
"""
if not mbox.askokcancel(title='sfc_models Example Installation',
message=validate_str):
return
target = fdog.askdirectory(title='Choose directory to for sfc_models examples installation')
if target == () or target == '':
return
install_example_scripts.install(target)
def _show_diag(self, text):
dir_ = filedialog.askdirectory()
if dir_:
if text == 'source':
self.source_entry.delete(0, END)
self.source_entry.insert(0, dir_)
if text == 'destination':
self.dst_entry.delete(0, END)
self.dst_entry.config(state='normal')
self.dst_entry.insert(0, dir_)
def bit_dir_open(self, gs):
"""Open filedialog when Select Location of Files button selected."""
self.bit_dir_path = filedialog.askdirectory()
gs.bit_path = self.bit_dir_path
self.bit_dir_var.set(self.bit_dir_path)
def archive_dir_open(self, gs):
"""Open filedialog when Select Archive Destination button selected."""
self.archive_dir_path = filedialog.askdirectory()
gs.archive_path = self.archive_dir_path
self.archive_dir_var.set(self.archive_dir_path)