• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python filedialog.asksaveasfilename函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中tkinter.filedialog.asksaveasfilename函数的典型用法代码示例。如果您正苦于以下问题:Python asksaveasfilename函数的具体用法?Python asksaveasfilename怎么用?Python asksaveasfilename使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了asksaveasfilename函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: save_as

 def save_as(self):
     import tkinter.messagebox as messagebox
     import tkinter.filedialog as filedialog
     import my_constant
     import my_io
     import traceback
     try:
         if self.clan.h:
             path = filedialog.asksaveasfilename(**my_constant.history_opt)
             if path:
                 my_io.append_history(None, path, mode='clear')
                 for item in self.clan.hv:
                     my_io.append_history(item, path, check_exist=False)
                 messagebox.showinfo('保存成功!', '已保存至' + path)
         if self.clan.d:
             path = filedialog.asksaveasfilename(**my_constant.donate_opt)
             if path:
                 my_io.append_donate(None, path, mode='clear')
                 for item in self.clan.dv:
                     my_io.append_donate(item, path, check_exist=False)
                 messagebox.showinfo('保存成功!', '已保存至' + path)
     except Exception as e:
         traceback.print_exc()
         messagebox.showerror('出错了!', '保存失败')
     self.master.master.focus_force()
开发者ID:Ceilopty,项目名称:coc-war-manager,代码行数:25,代码来源:my_menu.py


示例2: convertLib

def convertLib():
	fileName=askopenfilename(title = "Input Library",filetypes=[('Eagle V6 Library', '.lbr'), ('all files', '.*')], defaultextension='.lbr') 
	modFileName=asksaveasfilename(title="Module Output Filename", filetypes=[('KiCad Module', '.mod'), ('all files', '.*')], defaultextension='.mod')
	symFileName=asksaveasfilename(title="Symbol Output Filename", filetypes=[('KiCad Symbol', '.lib'), ('all files', '.*')], defaultextension='.lib')
	
	logFile.write("*******************************************\n")
	logFile.write("Converting Lib: "+fileName+"\n")
	logFile.write("Module Output: "+modFileName+"\n")
	logFile.write("Symbol Output: "+symFileName+"\n")
	
	name=fileName.replace("/","\\")
	name=name.split("\\")[-1]
	name=name.split(".")[0]
	
	logFile.write("Lib name: "+name+"\n")
	
	try:
		node = getRootNode(fileName)
		node=node.find("drawing").find("library")	
		lib=Library(node,name)			
		modFile=open(modFileName,"a")
		symFile=open(symFileName,"a")			
		lib.writeLibrary(modFile,symFile)
	except Exception as e:
		showerror("Error",str(e)+"\nSee Log.txt for more info")		
		logFile.write("Conversion Failed\n\n")
		logFile.write(traceback.format_exc())
		logFile.write("*******************************************\n\n\n")
		return
	
	logFile.write("Conversion Successfull\n")
	logFile.write("*******************************************\n\n\n")		
	showinfo("Library Complete","The Modules and Symbols Have Finished Converting \n Check Console for Errors")
开发者ID:alejmrm,项目名称:Eagle2Kicad,代码行数:33,代码来源:Start.py


示例3: save_sol

def save_sol(save_choice):
    global location
    location=StringVar()
    check_block=True
    check_acc_clue=True
    check_dwn_clue=True
    for i in range(0,height):
        for j in range(0,width):
            if(cellblock[i][j]=="-"):
                check_block=False
                break
    for i in range(0,acc):
        if(across[i][1]==""):
            check_acc_clue=False
            break
    for i in range(0,dwn):
        if(down[i][1]==""):
            check_dwn_clue=False
            break
    if(check_block==False):
        messagebox.showinfo("Sorry!", "Solution grid has not been filled completely")
    if(check_acc_clue==False):
        messagebox.showinfo("Sorry!", "Across cluelist has not been filled completely")
    if(check_dwn_clue==False):
        messagebox.showinfo("Sorry!", "Down cluelist has not been filled completely")
    if(check_block==True and check_acc_clue==True and check_dwn_clue==True):
       file_opt=opt = {}
       if (save_choice==0):
           opt['filetypes'] = [('all files', '.*'), ('binary files', '.puz')]
           #options['initialfile'] = 'My_CW_File.puz'
           opt['parent'] = master
           fileloc = filedialog.asksaveasfilename(filetypes=opt['filetypes'])
       else:
           opt['filetypes'] = [('all files', '.*'), ('ipuz files', '.ipuz')]
           #options['initialfile'] = 'My_CW_File.ipuz'
           opt['parent'] = master
           fileloc = filedialog.asksaveasfilename(filetypes=opt['filetypes'])
       File.title=title
       File.author=author
       File.cpyrt=cpyrt
       File.notes=notes
       File.width=width
       File.height=height
       File.solnblock=cellblock
       File.acc=acc
       File.dwn=dwn
       File.across=across
       File.down=down
       File.cellno=cellno
       File.loc=fileloc
       if (save_choice==0):
           filewrite(File)
       else:
           write_ipuz(File)
       master.destroy()
       sys.exit(0)
开发者ID:LSowrabbi,项目名称:CWPuzzleReader,代码行数:56,代码来源:createCW_ipuz.py


示例4: exportEntry

 def exportEntry(self):
     self.selected = self.listbox.curselection()
     if self.selected:
         e = self.listitems[int(self.selected[0])]
         if hasattr(e, "filename"):
             fn = asksaveasfilename(initialfile=e.filename + ".mft")
         else:
             fn = asksaveasfilename()
         with open(fn, "wb") as mftfile:
             mftfile.write(e.dump())
开发者ID:hamptus,项目名称:mftpy,代码行数:10,代码来源:gui.py


示例5: writeFile

def writeFile(key, chunks, overwrite):
    failure = True
    filename = "{}.todo".format(key)
    while failure:
        try:
            with open(filename) as f:
                pass
        except OSError as e:
            try:
                with open(filename, "w") as f:
                    for chunk in chunks:
                        for line in chunk:
                            f.write(line)
                        f.write("\n")
            except OSError as f:
                print("""\
The file {} exists and the file system doesn't want me to touch it. Please
enter a different one.""".format(filename))
                filename = filedialog.asksaveasfilename()
                continue
            else:
                failure = False
        else:
            if overwrite:
                with open(filename, "w") as f:
                    for chunk in chunks:
                        for line in chunk:
                            f.write(line)
                        f.write("\n")
                failure = False
            else:   
                answer = input("""\
Yo, {} exists. Do you want to overwrite it? y/n
> """.format(filename))
                if answer in "yY":
                    print("""\
Okay, your funeral I guess.""")
                    with open(filename, "w") as f:
                        for chunk in chunks:
                            for line in chunk:
                                f.write(line)
                            f.write("\n")
                    failure = False
                elif answer in "nN":
                    print("""\
Okay, enter a new one.""")
                    filename = filedialog.asksaveasfilename()
                    continue
                else:
                    print("""\
Didn't get that, so I'm assuming "no." (Aren't you glad this is my default
behavior for garbled input?)""")
                    filename = filedialog.asksaveasfilename()
                    continue
开发者ID:maseaver,项目名称:todomaker,代码行数:54,代码来源:todomaker.py


示例6: on_key_pressed

    def on_key_pressed(self, key_pressed_event):
        key = key_pressed_event.keysym

        if "Shift" in key or "Control" in key:
            return

        print(key_pressed_event.keysym)

        self.pressed_keys.append(key)

        if self.pressed_keys == self.easteregg_keys:
            print('A winner is you!')
            filedialog.asksaveasfilename()
开发者ID:vomaufgang,项目名称:pythonstuff,代码行数:13,代码来源:downruplyb.py


示例7: save

 def save(self):
     self.paused = True
     try:
         if platform.system() == 'Windows':
             game = filedialog.asksaveasfilename(initialdir = "./saves",title = "choose your file",filetypes = (("all files","*.*"),("p files","*.p")))
         else:
             game = filedialog.asksaveasfilename(initialdir = "./saves",title = "choose your file",filetypes = (("p files","*.p"),("all files","*.*")))
         self.root.title('Warriors & Gatherers - '+shortString(game))
         # Copy logs
         for string in self.playerNames:
             shutil.copyfile(string+'.log',game[:-2]+'_'+string+'.log')
         pickle.dump(self.data, open(game, "wb" ) )
     except:
         return None
开发者ID:maikeloni,项目名称:Warriors-and-Gatherers,代码行数:14,代码来源:gui.py


示例8: export_to_csv

    def export_to_csv(self):
        """
        asksaveasfilename Dialog für den Export der Ansicht als CSV Datei.
        """        
        all_items = self.columntree.get_children()
        all_items = list(all_items)
        all_items.sort()
        data = [("Id", "Datum", "Projekt", "Startzeit", "Endzeit", "Protokoll",
                 "Bezahlt", "Stunden")]
        for item in all_items:
            t_id = self.columntree.set(item, column="id")
            datum = self.columntree.set(item, column="datum")
            projekt = self.columntree.set(item, column="projekt")
            startzeit = self.columntree.set(item, column="startzeit")
            endzeit = self.columntree.set(item, column="endzeit")
            protokoll = self.columntree.set(item, column="protokoll")
            bezahlt = self.columntree.set(item, column="bezahlt")
            stunden = self.columntree.set(item, column="stunden")
            stunden = stunden.replace('.', ',')

            data.append((t_id, datum, projekt, startzeit, endzeit, protokoll,
                        bezahlt, stunden))

        filename = filedialog.asksaveasfilename(
                                        defaultextension=".csv",
                                        initialdir=os.path.expanduser('~'),
                                        title="Export alle Daten als CSV Datei",
                                        initialfile="pystunden_alle_daten",
                                        filetypes=[("CSV Datei", ".csv"),
                                                   ("Alle Dateien", ".*")])        
        if filename:
            with open(filename, "w", newline='') as f:
                writer = csv.writer(f, delimiter=';')
                writer.writerows(data)
开发者ID:martinfischer,项目名称:pystunden,代码行数:34,代码来源:pystunden.py


示例9: __call__

 def __call__(self):
     filename = filedialog.asksaveasfilename(
         initialdir="/", title="ログの保存", filetypes=(("テキスト ファイル", "*.txt"), ("全ての ファイル", "*.*")))
     log = LogController.LogController().get()
     f = open(filename, 'w')
     f.write(log)
     f.close()
开发者ID:kinformation,项目名称:hachi,代码行数:7,代码来源:MenuController.py


示例10: write_refl

def write_refl(headers, q, refl, drefl, path):
    '''
    Open a file where the previous was located, and drop a refl with the same
    name as default.
    '''
    # we don't want a full GUI, so keep the root window from appearing
    Tk().withdraw()

    fullpath=asksaveasfilename(initialdir=path,
                initialfile=headers['title']+'.refl',
                defaultextension='.refl',
                filetypes=[('reflectivity','.refl')])

#    fullpath = re.findall('\{(.*?)\}', s)
    if len(fullpath)==0:
        print('Results not saved')
        return

    textlist = ['#pythonfootprintcorrect 1 1 2014-09-11']
    for header in headers:
        textlist.append('#'+header+' '+headers[header])
    textlist.append('#columns Qz R dR')

    for point in tuple(zip(q,refl,drefl)):
        textlist.append('{:.12g} {:.12g} {:.12g}'.format(*point))
#    print('\n'.join(textlist))
    with open(fullpath, 'w') as reflfile:
        reflfile.writelines('\n'.join(textlist))

    print('Saved successfully as:', fullpath)
开发者ID:richardsheridan,项目名称:fpc,代码行数:30,代码来源:fpc.py


示例11: start_window

def start_window():
	import import_from_xlsx

	if not hasattr(import_from_xlsx, 'load_state'):
		setattr(import_from_xlsx, 'load_state', True)
	else:
		reload(import_from_xlsx)
	
	''' tag library '''
	'''
	each tag library corresponds to sqlite table name
	each tag corresponds to sqlite database column name
	'''

	''' config file '''
	config = configparser.ConfigParser()
	config.read(controllers + 'config.ini', encoding='utf-8')

	def convert_to_db():
		source = import_from_xlsx.import_xlsx_path.get_()
		destination = import_from_xlsx.destination_path.get_()

		convert_xlsx_to_db.convert_database(source, destination)
		import_from_xlsx.import_from_xlsx.destroy()

	import_from_xlsx.import_browse_button.settings(\
		command=lambda: import_from_xlsx.import_xlsx_path.set(filedialog.askopenfile().name))
	import_from_xlsx.time_browse_button.settings(\
		command=lambda: import_from_xlsx.time_xlsx_path.set(filedialog.askopenfile().name))
	import_from_xlsx.destination_browse_button.settings(\
		command=lambda: import_from_xlsx.destination_path.set(filedialog.asksaveasfilename() + '.db'))
	import_from_xlsx.cancel_button.settings(command=import_from_xlsx.import_from_xlsx.destroy)
	import_from_xlsx.import_button.settings(command=convert_to_db)
开发者ID:wasifzaman,项目名称:Project-RYB,代码行数:33,代码来源:import_from_xlsx_.py


示例12: fileDialog

 def fileDialog(self, fileOptions=None, mode='r', openMode=True):
     defaultFileOptions = {}
     defaultFileOptions['defaultextension'] = ''
     defaultFileOptions['filetypes'] = []
     defaultFileOptions['initialdir'] = ''
     defaultFileOptions['initialfile'] = ''
     defaultFileOptions['parent'] = self.root
     defaultFileOptions['title'] = ''
     if fileOptions is not None:
         for key in fileOptions:
             defaultFileOptions[key] = fileOptions[key]
     if openMode is True:
         file = askopenfilename(**defaultFileOptions)
         if file is not None and file is not '':
             try :
                 self.compressionCore.openImage(file)
                 self.compressionCore.imageSquaring(self.NValue.get())
             except Exception:
                 messagebox.showerror(
                         _("Error"),
                         "It's impossible open the image.")
                 return 
             self.updateGUI(original=True)
     else:
         file = asksaveasfilename(**defaultFileOptions)
         if file is not None and file is not '':
             try:
                 self.compressionCore.compressedImage.save(fp=file, format="bmp")
             except Exception:
                 messagebox.showwarning(
                     _("Error"),
                     "Fail to save compressed image. Please try again.")
开发者ID:SilvioMessi,项目名称:CustomJPEGCompression,代码行数:32,代码来源:guiUtils.py


示例13: export

 def export(self, fullRes = True):
     """Exports the image with bounding boxes drawn on it.
     
     A save-file dialog will be shown to the user to select the target file name.
     
     fullRes - If this set to true and the DetectionFrame instance has been constructed
               with an image given by filename, a full-resolution image will be exported,
               otherwise just the thumbnail will be used.
     """
     
     filename = tkFileDialog.asksaveasfilename(parent = self, title = 'Export image', defaultextension = '.png',
                                               filetypes = [('Portable Network Graphics', '.png'), ('JPEG image', '.jpg .jpeg')])
     if filename:
         if not self._detectionFrame._filepath is None:
             img = Image.open(self._detectionFrame._filepath)
             if not fullRes:
                 img.thumbnail((180,512), Image.ANTIALIAS)
         else:
             img = self._detectionFrame.thumb.copy()
         # Draw bounding boxes of the detected objects
         for i, det in enumerate(self._detectionFrame.detections):
             img = det.scale(float(img.size[0]) / self._detectionFrame.thumb.orig_size[0]).drawToImage(img, gui_utils.getAnnotationColor(i), 2)
         # Save file
         try:
             options = {}
             ext = os.path.splitext(filename)[1].lower()
             if ext == '.jpg':
                 options['quality'] = 96
             elif ext == '.png':
                 options['compress'] = True
             img.save(filename, **options)
         except Exception as e:
             tkMessageBox.showerror(title = 'Export failed', message = 'Could not save image:\n{!r}'.format(e))
开发者ID:JD-accounts,项目名称:artos,代码行数:33,代码来源:BatchWindow.py


示例14: write_css

def write_css(*args):
    global item_list
    m = find("id", content)
    for match in m:
        item_list.append(clean(match, 'id', '#'))
 
    #find all classes, assign to variable
    m = find("class", content)
    for match in m:
        item_list.append(clean(match, 'class', '.'))
 
    #remove duplicate items in list
    items = set(item_list)
 
    #open file to write CSS to
    f = open(asksaveasfilename(), "w")
 
    #write tag selectorrs to CSS file
    for tag in tags:
        f.write(tag + "{\n\n}\n\n")

    #for each item in list, print item to CSS file
    for i in items:
        f.write(i)
 
    #close the opened file
    f.close()
开发者ID:bcgreen24,项目名称:css_create,代码行数:27,代码来源:CSSCreate.py


示例15: btn_save_command

    def btn_save_command(self):
        save_filename = asksaveasfilename(filetypes=(("Excel file", "*.xls"), ))
        if not save_filename:
            return
        filename, file_extension = os.path.splitext(save_filename)
        if file_extension == '':
            save_filename += '.xls'
        wb = xlwt.Workbook()
        ws = wb.add_sheet('Найденные телефоны')

        phone_style = xlwt.XFStyle()
        phone_style.num_format_str = '0000000000'

        ws.col(0).width = 256 * 11

        line = 0
        for k in Parser.phones.keys():
            if k not in Parser.source_excel.keys():
                try:
                    v = Parser.phones[k]
                except EOFError:
                    v = ''
                ws.write(line, 0, int(k), phone_style)
                ws.write(line, 1, v)
                line += 1

        wb.save(save_filename)
        os.startfile(save_filename, 'open')
开发者ID:vitalik-ventik,项目名称:PhoneParser,代码行数:28,代码来源:ParserGUI.py


示例16: save_session_dialog

 def save_session_dialog(self,*event):
     
     path_list = []
     for tab_not_closed_index in range(len(self.model.tabs_html)-1,-1,-1):
         if self.model.tabs_html[tab_not_closed_index].save_path:
             path_list.insert(0,self.model.tabs_html[tab_not_closed_index].save_path)
      # True False or None 
     answer = messagebox.askyesnocancel(
         title=_(u"Question"),
         message=_(u"Voulez vous sauvegarder la session dans un fichier spécifique ?")
     )
     if answer:
        file_path = filedialog.asksaveasfilename(defaultextension=JSON["defaultextension"],
                                              initialdir=self.model.guess_dir(),
                                              filetypes=JSON["filetypes"],
                                              initialfile="webspree_session.json")
        if file_path:
            session_object = {
                "webspree":"webspree_session",
                "version": "1.1.0",
                "path_list": path_list,
                "tab_index": self.model.selected_tab,
                "zoom": self.zoom_level,
                "edit_mod": self.mode.get()
            }
                
            JSON_TEXT = json.dumps(session_object,sort_keys=False, indent=4, separators=(',',':'))
            codecs.open(file_path, 'w', "utf-8").write(JSON_TEXT)
     elif not answer:
         self.model.set_option("previous_files_opened", path_list)
     elif answer is None:
         pass
开发者ID:GrosSacASac,项目名称:WebSpree,代码行数:32,代码来源:GraphicalUserInterfaceTk.py


示例17: generate_by_date_2

def generate_by_date_2():
	
	try:
		cur=dbconn.cursor()
		cur.execute("select distinct mc.ministry_county_name,c.course_name, r.first_name, r.middle_name, r.sur_name, r.personal_id, r.national_id, r.mobile_no, r.email_id,r.scheduled_from,r.scheduled_to,r.attended_from,r.attended_to from register r join ministry_county mc on mc.ministry_county_id = r.ministry_county_id join courses c on c.course_id = r.course_id where scheduled_from between  '%s' and '%s' order by scheduled_from;"%(fromentry.get(),toentry.get()))
		get_sch_report=cur.fetchall()
		
		if get_sch_report ==[]:
			messagebox.showwarning('Warning', "No data found from period '%s' to '%s'" %(fromentry.get(),toentry.get()))
		else: 
			file_format = [("CSV files","*.csv"),("Text files","*.txt"),("All files","*.*")] 
			all_trained_mdac_report = asksaveasfilename( title ="Save As='.csv'", initialdir="C:\\Users\\usrname", initialfile ='Generate by date All Trained MDAC Report', defaultextension=".csv", filetypes= file_format)
			outfile = open(all_trained_mdac_report, "w")
			writer = csv.writer(outfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL)
			writer.writerow( ['ministry_county_name','course_name','first_name','middle_name','sur_name','personal_id','national_id','mobile_no','email_id','scheduled_from','scheduled_to','attended_from','attended_to'])
			
			for i in get_sch_report:
				writer.writerows([i])
			outfile.close()
			gui.destroy()
			
	except psycopg2.InternalError:
		messagebox.showerror('Error', 'You need to input dates')
		messagebox.showerror('Error', 'Fatal Error occured')
		sys.exit(0)
			
	except:
		pass
开发者ID:paul-100,项目名称:attendance_system,代码行数:28,代码来源:reg_sched_attendance_win.py


示例18: getfilepath

def getfilepath():
    """Calls tk to create a file dialog that asks the user where they want to place the file."""
    # If root.withdraw() is added, window is only accessible by alt-tab.
    root = tk.Tk()
    return filedialog.asksaveasfilename(initialdir='C:/', defaultextension='.csv',
                                             initialfile='Inventory ' + str(datetime.date.today()),
                                             filetypes=(("Comma Separated Values",'*.csv'),("All Files", '*.*')))
开发者ID:aflavin,项目名称:Zabbix-API-Inventory,代码行数:7,代码来源:zabbix2.py


示例19: main

def main():
    # By default Tk shows an empty window, remove it
    tkinter.Tk().withdraw()

    input('Press enter to select the base file')
    baseFilePath = askopenfilename(title='Select the base file to read')
    print('Base file: ' + baseFilePath)

    input('Press enter to select the merge file')
    mergeFilePath = askopenfilename(title='Select the merge file to read')
    print('Merge file: ' + mergeFilePath)
    
    input('Press enter to select the save file')
    saveFilePath = asksaveasfilename()
    print('Save file: ' + saveFilePath)

    baseFile = csv.reader(open(baseFilePath, 'r', encoding='utf-8'))
    mergeFile = deque(csv.reader(open(mergeFilePath, 'r', encoding='utf-8')))
    saveFile = csv.writer(open(saveFilePath, 'w', encoding='utf-8'), delimiter=';', quoting=csv.QUOTE_NONE)

    mergeRow = mergeFile.popleft()
    for baseRow in baseFile:
        if mergeRow[0] == baseRow[0]:
            mergeCol = mergeRow[1]
            try:
                mergeRow = mergeFile.popleft()
            except:
                pass
        else:
            mergeCol = ''

        saveFile.writerow([baseRow[0], mergeCol, baseRow[1]])
开发者ID:sirrahd,项目名称:csv_merge,代码行数:32,代码来源:csv_merge.py


示例20: gravar

 def gravar(self):
     f = open('output.wav','w')
     path = f.name
     f.close()
     recorder.record(path)
     self.path = filedialog.asksaveasfilename(defaultextension='wav')
     os.rename(path, self.path)
开发者ID:alcapriles,项目名称:Music-Box,代码行数:7,代码来源:GUI.py



注:本文中的tkinter.filedialog.asksaveasfilename函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python font.nametofont函数代码示例发布时间:2022-05-27
下一篇:
Python filedialog.asksaveasfile函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap