Python tkinter.filedialog.askopenfilename() Examples

The following are 30 code examples of tkinter.filedialog.askopenfilename(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tkinter.filedialog , or try the search function .
Example #1
Source File: 5.visualize.py    From paper.io.sessdsa with GNU General Public License v3.0 8 votes vote down vote up
def load_ai(self):
            path = askopenfilename(filetypes=[('AI脚本', '*.py')])
            if not path:
                return
            name, ext = os.path.splitext(os.path.basename(path))

            try:
                if ext != '.py':
                    raise TypeError('不支持类型:%s' % ext)

                class load:
                    with open(path, encoding='utf-8', errors='ignore') as f:
                        exec(f.read())

                load.play
                self.AI_MODULE = load
                self.AI_NAME = name
                self.AI_info.set(name)
                clear_storage()
            except Exception as e:
                showerror('%s: %s' % (self.name, type(e).__name__), str(e))

    # 定义合法输入类 
Example #2
Source File: 5.visualize.py    From paper.io.sessdsa with GNU General Public License v3.0 7 votes vote down vote up
def load_log():
        log_path = askopenfilename(filetypes=[('对战记录文件', '*.zlog'), ('全部文件',
                                                                     '*.*')])
        if not log_path: return
        try:
            with open(log_path, 'rb') as file:
                log = pickle.loads(zlib.decompress(file.read()))
            global MATCH_LOG
            MATCH_LOG = log
            tk.title('Log: %s' % os.path.basename(log_path))
            display.load_match_result(log)
        except Exception as e:
            showerror('%s: %s' % (os.path.split(log_path)[1],
                                  type(e).__name__), str(e))

    # 保存记录 
Example #3
Source File: 3.09.py    From Tkinter-GUI-Application-Development-Blueprints-Second-Edition with MIT License 6 votes vote down vote up
def load_project(self):
        file_path = filedialog.askopenfilename(
            filetypes=[('Explosion Beat File', '*.ebt')], title='Load Project')
        if not file_path:
            return
        pickled_file_object = open(file_path, "rb")
        try:
            self.all_patterns = pickle.load(pickled_file_object)
        except EOFError:
            messagebox.showerror("Error",
                                 "Explosion Beat file seems corrupted or invalid !")
        pickled_file_object.close()
        try:
            self.change_pattern()
            self.root.title(os.path.basename(file_path) + PROGRAM_NAME)
        except:
            messagebox.showerror("Error",
                                 "An unexpected error occurred trying to process the beat file") 
Example #4
Source File: MainUI.py    From AI_Sudoku with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
def open_img(self):
        try:
            filename = filedialog.askopenfilename(title='open')
        except:
            return
        try:
            img = Image.open(filename)
        except:
            messagebox.showerror("ERROR", "Non Image File selected")
            return
        self.selectedimagepath = filename
        self.imagepathdisplay.configure(fg="black")
        self.imagepathdisplay.delete(0, END)
        self.imagepathdisplay.insert(0, filename)
        img = img.resize((490, 450), Image.ANTIALIAS)
        img = ImageTk.PhotoImage(img)
        self.imgpanel.configure(image=img)
        self.img = img
        self.nextbut.configure(fg="black") 
Example #5
Source File: 6.glory_of_mankind.py    From paper.io.sessdsa with GNU General Public License v3.0 6 votes vote down vote up
def load_ai(self):
            path = askopenfilename(filetypes=[('AI脚本', '*.py')])
            if not path:
                return
            name, ext = os.path.splitext(os.path.basename(path))

            try:
                if ext != '.py':
                    raise TypeError('不支持类型:%s' % ext)

                class load:
                    with open(path, encoding='utf-8', errors='ignore') as f:
                        exec(f.read())

                load.play
                self.AI_MODULE = load
                self.AI_NAME = name
                self.AI_info.set(name)
                clear_storage()
            except Exception as e:
                showerror('%s: %s' % (self.name, type(e).__name__), str(e))

    # 定义合法输入类 
Example #6
Source File: manual_poser.py    From talking-head-anime-demo with MIT License 6 votes vote down vote up
def load_image(self):
        file_name = filedialog.askopenfilename(
            filetypes=[("PNG", '*.png')],
            initialdir="data/illust")
        if len(file_name) > 0:
            image = PhotoImage(file=file_name)
            if image.width() != self.poser.image_size() or image.height() != self.poser.image_size():
                message = "The loaded image has size %dx%d, but we require %dx%d." \
                          % (image.width(), image.height(), self.poser.image_size(), self.poser.image_size())
                messagebox.showerror("Wrong image size!", message)
            self.source_image_label.configure(image=image, text="")
            self.source_image_label.image = image
            self.source_image_label.pack()

            self.source_image = extract_pytorch_image_from_filelike(file_name).to(self.torch_device).unsqueeze(dim=0)
            self.needs_update = True 
Example #7
Source File: visualize.py    From paper.io.sessdsa with GNU General Public License v3.0 6 votes vote down vote up
def load_ai(self):
            path = askopenfilename(filetypes=[('AI脚本', '*.py')])
            if not path:
                return
            name, ext = os.path.splitext(os.path.basename(path))

            try:
                if ext != '.py':
                    raise TypeError('不支持类型:%s' % ext)

                class load:
                    with open(path, encoding='utf-8', errors='ignore') as f:
                        exec(f.read())

                load.play
                self.AI_MODULE = load
                self.AI_NAME = name
                self.AI_info.set(name)
                clear_storage()
            except Exception as e:
                showerror('%s: %s' % (self.name, type(e).__name__), str(e))

    # 定义合法输入类 
Example #8
Source File: visualize.py    From paper.io.sessdsa with GNU General Public License v3.0 6 votes vote down vote up
def load_log():
        log_path = askopenfilename(filetypes=[('对战记录文件', '*.clog;*.zlog'), ('全部文件',
                                                                     '*.*')])
        if not log_path: return
        try:
            if log_path.endswith('.zlog'):
                log = match_interface.load_match_log(log_path)
            elif log_path.endswith('.clog'):
                log = match_interface.load_compact_log(log_path)
            else:
                raise ValueError('后缀名非法')
            global MATCH_LOG
            MATCH_LOG = log
            tk.title('Log: %s' % os.path.basename(log_path))
            display.load_match_result(log)
        except Exception as e:
            raise
            showerror('%s: %s' % (os.path.split(log_path)[1],
                                  type(e).__name__), str(e))

    # 保存记录 
Example #9
Source File: DeviceManager.py    From python-dvr with MIT License 6 votes vote down vote up
def flash(self):
        self.fl_state.set("Processing...")
        filename = askopenfilename(
            filetypes=((_("Flash"), "*.bin"), (_("All files"), "*.*"))
        )
        if filename == "":
            return
        if len(self.table.selection()) == 0:
            _mac = "all"
        else:
            _mac = self.table.item(self.table.selection()[0], option="values")[4]
        result = ProcessCMD(
            ["flash", _mac, self.passw.get(), filename, self.fl_state.set]
        )
        if (
            hasattr(result, "keys")
            and "Ret" in result.keys()
            and result["Ret"] in CODES.keys()
        ):
            showerror(_("Error"), CODES[result["Ret"]]) 
Example #10
Source File: view.py    From ms_deisotope with Apache License 2.0 6 votes vote down vote up
def main():
    base = Tk()
    base.title("ms_deisotope Spectrum Viewer")
    tk.Grid.rowconfigure(base, 0, weight=1)
    tk.Grid.columnconfigure(base, 0, weight=1)
    app = SpectrumViewer(base)
    app.do_layout()

    try:
        fname = sys.argv[1]
    except IndexError:
        fname = None
        # fname = tkfiledialog.askopenfilename()
    print("initial value", fname)
    app.ms_file_name = fname

    app.mainloop() 
Example #11
Source File: avatarwindow.py    From Tkinter-GUI-Programming-by-Example with MIT License 6 votes vote down vote up
def choose_image(self):
        image_file = filedialog.askopenfilename(filetypes=self.image_file_types)

        if image_file:
            avatar = Image.open(image_file)
            avatar.thumbnail((128, 128))
            avatar.save(avatar_file_path, "PNG")

            img_contents = ""
            img_b64 = ""
            with open(avatar_file_path, "rb") as img:
                img_contents = img.read()
                img_b64 = base64.urlsafe_b64encode(img_contents)

            self.master.requester.update_avatar(self.master.username, img_b64)

            self.current_avatar_image = tk.PhotoImage(file=avatar_file_path)
            self.current_avatar.configure(image=self.current_avatar_image) 
Example #12
Source File: chartparser_app.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def load_chart(self, *args):
        "Load a chart from a pickle file"
        filename = askopenfilename(filetypes=self.CHART_FILE_TYPES,
                                   defaultextension='.pickle')
        if not filename: return
        try:
            with open(filename, 'rb') as infile:
                chart = pickle.load(infile)
            self._chart = chart
            self._cv.update(chart)
            if self._matrix: self._matrix.set_chart(chart)
            if self._matrix: self._matrix.deselect_cell()
            if self._results: self._results.set_chart(chart)
            self._cp.set_chart(chart)
        except Exception as e:
            raise
            tkinter.messagebox.showerror('Error Loading Chart',
                                   'Unable to open file: %r' % filename) 
Example #13
Source File: chartparser_app.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def load_grammar(self, *args):
        "Load a grammar from a pickle file"
        filename = askopenfilename(filetypes=self.GRAMMAR_FILE_TYPES,
                                   defaultextension='.cfg')
        if not filename: return
        try:
            if filename.endswith('.pickle'):
                with open(filename, 'rb') as infile:
                    grammar = pickle.load(infile)
            else:
                with open(filename, 'r') as infile:
                    grammar = CFG.fromstring(infile.read())
            self.set_grammar(grammar)
        except Exception as e:
            tkinter.messagebox.showerror('Error Loading Grammar',
                                   'Unable to open file: %r' % filename) 
Example #14
Source File: 3.12.py    From Tkinter-GUI-Application-Development-Blueprints-Second-Edition with MIT License 6 votes vote down vote up
def load_project(self):
        file_path = filedialog.askopenfilename(
            filetypes=[('Explosion Beat File', '*.ebt')], title='Load Project')
        if not file_path:
            return
        pickled_file_object = open(file_path, "rb")
        try:
            self.all_patterns = pickle.load(pickled_file_object)
        except EOFError:
            messagebox.showerror("Error",
                                 "Explosion Beat file seems corrupted or invalid !")
        pickled_file_object.close()
        try:
            self.change_pattern()
            self.root.title(os.path.basename(file_path) + PROGRAM_NAME)
        except:
            messagebox.showerror("Error",
                                 "An unexpected error occurred trying to process the beat file") 
Example #15
Source File: ui_input.py    From Andromeda with MIT License 6 votes vote down vote up
def __click_select(self, entry, tag):

        if tag == 1:
            path = filedialog.askopenfilename()
            if len(path) > 0:
                t = '/'
                list = path.split('/')
                pro = list.pop()
                path = t.join(list)
                self.is_workspace.set('.xcworkspace' in pro)
                tag = pro.split('.')[0]
                self.project_path.set(path)
                self.target.set(tag)
        else:
            path = filedialog.askopenfilename()
            if len(path) > 0:
                t = '/'
                self.plist_path.set(path)
                list = path.split('/')
                pro = list.pop()
                self.is_release.set('AppStore' in pro) 
Example #16
Source File: tabs.py    From vy with MIT License 6 votes vote down vote up
def load_tab():
    """
    It pops a askopenfilename window to drop
    the contents of a file into another tab's text area.
    """

    filename = askopenfilename()

    # If i don't check it ends up cleaning up
    # the text area when one presses cancel.

    if not filename: 
        return 'break'

    try:
        root.note.load([ [filename] ])
    except Exception:
        root.status.set_msg('It failed to load.')
    else:
        root.status.set_msg('File loaded.')
    return 'break' 
Example #17
Source File: io.py    From vy with MIT License 6 votes vote down vote up
def ask_and_load(self, event):
        """
        It pops a askopenfilename to find a file to drop
        the contents in the focused text area.
        """
    
        filename = askopenfilename()
    
        # If i don't check it ends up cleaning up
        # the text area when one presses cancel.
    
        if not filename: 
            return
    
        try:
            self.area.load_data(filename)
        except Exception:
            root.status.set_msg('It failed to load.')
        else:
            root.status.set_msg('File loaded.') 
Example #18
Source File: scdiff_gui.py    From scdiff with MIT License 5 votes vote down vote up
def readTF(self):
		self.TFName=''
		self.TFName=tkFileDialog.askopenfilename()
		self.vtf1.set(self.TFName.split('/')[-1]) 
Example #19
Source File: scdiff_gui.py    From scdiff with MIT License 5 votes vote down vote up
def readEx(self):
		self.fileName=''
		self.fileName=tkFileDialog.askopenfilename()
		self.vex1.set(self.fileName.split('/')[-1]) 
Example #20
Source File: scdiff_gui.py    From scdiff with MIT License 5 votes vote down vote up
def readK(self):
		self.KName=''
		self.KName=tkFileDialog.askopenfilename() 
Example #21
Source File: wb_runner.py    From WhiteboxTools-ArcGIS with MIT License 5 votes vote down vote up
def select_exe(self):
        try:
            filename = filedialog.askopenfilename(initialdir=self.exe_path)
            self.exe_path = path.dirname(path.abspath(filename))
            wbt.set_whitebox_dir(self.exe_path)
            self.refresh_tools()
        except:
            messagebox.showinfo(
                "Warning", "Could not find WhiteboxTools executable file.") 
Example #22
Source File: gui.py    From baldr with GNU General Public License v2.0 5 votes vote down vote up
def open_clicked(self):
		self.open_filename = filedialog.askopenfilename(initialdir=self.get_save_dir())
		if self.open_filename:
			self.change_state()
			datafile = open(self.open_filename, 'rb')
			custom = pickle.load(datafile)
			self.custom_tmax = custom.k
			datafile.close()
			print('Custom piecewise polynomial trajectory data file loaded.\nPath:', self.open_filename, '\nTrajectory length:', round(custom.k, 2), 's', end='\n\n') 
Example #23
Source File: tkconch.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def getIdentityFile(self):
        r = tkFileDialog.askopenfilename()
        if r:
            self.identity.delete(0, Tkinter.END)
            self.identity.insert(Tkinter.END, r) 
Example #24
Source File: gui.py    From SneakyEXE with MIT License 5 votes vote down vote up
def BrowsingFile(self):
		self.FIrstFile = False
		global VarDone,EntryA
		self.File = OpenUpPromptSelect.askopenfilename(
			initialdir="C:\\Users\\"+os.getenv("USERNAME"),
			title="Choosing file...",
			filetypes=(("Executables", "*.exe"),("All files", "*"))
		)
		if not self.File:
			self.File = ""
			return None
		self.Selection.configure(state=tkinter.NORMAL)
		try:
			open(self.File, "rb")
		except PermissionError:
			self.File = ""
			self.StatusCodeIndex = 9
			if VarDone==2 or self.FileChosen:
				self.ReSetInputName()
				VarDone -= 1
			self.FileChosen = False
			self.Selection.configure(fg="#7C8179")
			self.Selection.delete("1.0",tkinter.END)
			self.Selection.insert(tkinter.END,self.LanguagesEncoding[str(self.L[-1])][0])
			self.Selection.configure(state=tkinter.DISABLED)
			self.MessageBox("error",self.File+self.LanguagesEncoding[str(self.L[-1])][11])
			return None
		self.FileChosen = True
		if VarDone<2 and self.Selection.get("1.0",tkinter.END).split("\n")[0]==self.LanguagesEncoding[str(self.L[-1])][0]:
			VarDone += 1
		self.Selection.configure(fg='black')
		self.Selection.delete("1.0",tkinter.END)
		self.Selection.insert(tkinter.END,self.File)
		self.Selection.configure(state=tkinter.DISABLED)
		EntryA += 1
		if VarDone==2:
			self.Change = False 
Example #25
Source File: TSEBIPythonInterface.py    From pyTSEB with GNU General Public License v3.0 5 votes vote down vote up
def _setup_tkinter(self):
        '''Creates a Tkinter input file dialog'''

        # Import Tkinter GUI widgets
        if sys.version_info.major == 2:
            from tkFileDialog import askopenfilename, asksaveasfilename
            import Tkinter as tk
        else:
            from tkinter.filedialog import askopenfilename, asksaveasfilename
            import tkinter as tk

        # Code below is to make sure the file dialog appears above the
        # terminal/browser
        # Based on
        # http://stackoverflow.com/questions/3375227/how-to-give-tkinter-file-dialog-focus

        # Make a top-level instance and hide since it is ugly and big.
        root = tk.Tk()
        root.withdraw()

        # Make it almost invisible - no decorations, 0 size, top left corner.
        root.overrideredirect(True)
        root.geometry('0x0+0+0')

        # Show window again and lift it to top so it can get focus,
        # otherwise dialogs will end up behind the terminal.
        root.deiconify()
        root.lift()
        root.focus_force()

        return root, askopenfilename, asksaveasfilename 
Example #26
Source File: pyjsonviewer.py    From PyJSONViewer with MIT License 5 votes vote down vote up
def select_json_file(self):
        file_path = filedialog.askopenfilename(
            initialdir=self.initial_dir, filetypes=[("JSON files", "*.json")])
        self.set_table_data_from_json(file_path) 
Example #27
Source File: editor.py    From Python-Prolog-Interpreter with MIT License 5 votes vote down vote up
def open_file(self, file_path=None):

        # Open a a new file dialog which allows the user to select a file to open
        if file_path is None:
            file_path = filedialog.askopenfilename()

        if is_file_path_selected(file_path):
            file_contents = get_file_contents(file_path)

            # Set the rule editor text to contain the selected file contents
            self.set_rule_editor_text(file_contents)
            self.file_path = file_path 
Example #28
Source File: TSEBIPythonInterface.py    From pyTSEB with GNU General Public License v3.0 5 votes vote down vote up
def _get_input_filename(self, title='Select Input File'):
        root, askopenfilename, _ = self._setup_tkinter()
        # show an "Open" dialog box and return the path to the selected file
        input_file = askopenfilename(parent=root, title=title)
        root.destroy()  # Destroy the GUI
        return input_file 
Example #29
Source File: imagesmake.py    From pythonprojects with MIT License 5 votes vote down vote up
def setOrign(self):
        orign = askopenfilename(title='选择输出源', filetypes=[('jpg', '*.jpg'), ('jpeg', '*.jpeg'), ('png', '*.png')])

        self.output.set(orign)

        self.orign = ImageManager(orign) 
Example #30
Source File: tmy.py    From pvlib-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _interactive_load():
    import tkinter
    from tkinter.filedialog import askopenfilename
    tkinter.Tk().withdraw()  # Start interactive file input
    return askopenfilename()