def close_tab(self,*event):
        """
"for_save" does not close the tab at all but asks to save it
"already_saved" immediately closes the tab even if unsaved
"already_saved_self_managed" same but does not open a blank tab if 0 tab
anything else would be a combination of the two above
"""
        def kill_tab(self,tab_index, open_at_least_one=True):
            del self.model.tabs_html[tab_index]
            del self.text_fields[tab_index]
            self.html_text_tabs.forget(tab_index)
            if len(self.model.tabs_html) > 0:
                self.html_text_tabs.select(0)
                self.model.selected_tab = 0
            elif open_at_least_one:
                self.model.start_mod = "blank"
                self.model._start_new_session()
        
        tab_index = self.model.selected_tab
        current_object = self.model.tabs_html[tab_index]
        if event[0] == "for_save":
            if not current_object.saved:
                answer = messagebox.askyesnocancel(
                    title=_("Attention"),
                    message=_("Voulez vous sauvegarder avant de fermer l'onglet %s?" %
                              (self.html_text_tabs.tab(tab_index,option='text')))
                    ) # True False or None 
                if answer and not self.model.save_html_file():
                        return "cancel"
                elif answer is None: # Cancel or X pressed
                    return "cancel"
            return "no_cancel"
        elif event[0] == "already_saved":
            kill_tab(self,tab_index)
        elif event[0] == "already_saved_self_managed":
            kill_tab(self,tab_index, False)
        else: # manual tab_closing
            if not current_object.saved:
                answer = messagebox.askyesnocancel(
                    title=_("Attention"),
                    message=_("Voulez vous sauvegarder avant de fermer cet onglet ?"))
                if answer: # Yes
                    if self.model.save_html_file():
                        kill_tab(self,tab_index)
                elif answer is None: pass # Cancel or X pressed
                else :
                    kill_tab(self,tab_index) # No
            else:
                kill_tab(self,tab_index)
 def ensure_saved (self):
     """
         ensures modified project will be saved before next step;
         returns True when all is OK, False if dialog has been
         cancelled or any other trouble fired up;
     """
     # inits
     response = self.YES
     # got to save first?
     if self.project_modified:
         # ask for saving
         response = MB.askyesnocancel(
             _("Question"),
             _("Project has been modified. Save it?")
         )
         # user answered 'yes'
         if response == self.YES:
             # save project
             response = self.slot_save()
         # end if
     # end if
     # CANCEL=None, NO=False, YES=True
     return (
         response and self.is_good_file_format(self.project_path)
     )
示例#3
0
def main():
    top = tix.Tk()

    nb = tix.NoteBook(top, width=300, height=200)
    nb.pack(expand=True, fill="both")

    nb.add("page1", label="text")
    f1 = tix.Frame(nb.subwidget("page1"))
    st = tix.ScrolledText(f1)
    st.subwidget("text").insert("1.0", "Here is where the text goes...")
    st.pack(expand=True)
    f1.pack()

    nb.add("page2", label="Message Boxes")
    f2 = tix.Frame(nb.subwidget("page2"))
    # 通过联合使用expand,fill和anchor,在窗口大小改变时,可以精确地控制小部件的行为
    tix.Button(f2, text="error", bg="lightblue", command=lambda t="error", m="This is bad!": mb.showerror(t, m)).pack(fill="x",
                                                                                                                      expand=True)
    tix.Button(f2, text="info", bg="pink", command=lambda t="info", m="Information": mb.showinfo(t, m)).pack(fill="x", expand=True)
    tix.Button(f2, text="warning", bg="yellow", command=lambda t="warning", m="Don't do it!": mb.showwarning(t, m)).pack(fill="x",
                                                                                                                         expand=True)
    tix.Button(f2, text="question", bg="green", command=lambda t="question", m="Will I?": mb.askquestion(t, m)).pack(fill="x",
                                                                                                                     expand=True)
    tix.Button(f2, text="yes - no", bg="lightgrey", command=lambda t="yes - no", m="Are you sure?": mb.askyesno(t, m)).pack(
            fill="x", expand=True)
    tix.Button(f2, text="yes - no - cancel", bg="black", fg="white",
               command=lambda t="yes - not - cancel", m="Last chance...": mb.askyesnocancel(t, m)).pack(fill="x", expand=True)

    f2.pack(side="top", fill="x")
    top.mainloop()
 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
示例#5
0
 def prompt_save(self, editor):
     fname = editor.fpathname or editor.fname
     msg = "Save '%s' before closing?" % fname
     ans = askyesnocancel(message=msg)
     if ans:
         # return cancel if selected save and then not saved
         return True if self.save(editor) else None
     return ans
示例#6
0
def main():
    # 为了不让空窗口出现,必须导入主Tkinter模块并实例化顶层Tk对象.然后通过调用withdraw()让对象不可见
    tk = tkinter.Tk()
    tk.withdraw()  # 去掉空窗口

    print(dir(mb))

    # 注意,一些函数返回字符串,比如ok,而其他函数则返回布尔结果.最好在交互式提示符上实验它们,以便知道返回值的类型.
    # 注意,当出现Cancel时,单击它会返回None
    mb.showinfo("Title", "Your message here")
    mb.showerror("An Error", "Oops!")
    mb.showwarning("Title", "This may not work...")
    mb.askyesno("Title", "Do you love me?")
    mb.askokcancel("Title", "Are you well?")
    mb.askquestion("Title", "How are you?")
    mb.askretrycancel("Title", "Go again?")
    mb.askyesnocancel("Title", "Are you well?")
示例#7
0
 def messages(self):
     print("info", showinfo("Spam", "Egg Information"))
     print("warning", showwarning("Spam", "Egg Warning"))
     print("error", showerror("Spam", "Egg Alert"))
     print("question", askquestion("Spam", "Question?"))
     print("proceed", askokcancel("Spam", "Proceed?"))
     print("yes/no", askyesno("Spam", "Got it?"))
     print("yes/no/cancel", askyesnocancel("Spam", "Want it?"))
     print("try again", askretrycancel("Spam", "try again?"))
示例#8
0
 def beforeleave(self):
     if self.unsaved:
         henji = messagebox.askyesnocancel('还未保存','真的要退出吗?修改已生效,但若不保存'
                                           ',重启程序后将恢复。\n保存?不保存?返回?')
         if henji is True: self.mem_save()
         elif henji is False: pass
         elif henji is None: return
         else: raise RuntimeError
     self.maintop.flashMemberCheckbox()
     self.top.destroy()
示例#9
0
文件: apa.py 项目: flytape8490/apa
def save():
	state=messagebox.askyesnocancel(message='Do you want to create a new version?', icon='question', title='CAUTION!')
	if state: # dupe
		dupeFile()
		saveActn()
	elif state==False: # don't dupe
		if messagebox.askyesno(message='Are you sure you want to overwrite the existing files?', icon='question', title='CAUTION!'):
			saveActn()
		else:
			dupeFile()
			saveActn()
示例#10
0
 def okayToContinue(self):
     reply = messagebox.askyesnocancel(
                "Saída",
                "Deseja salvar as alterações antes de sair?", parent=self)
     if reply is None:
         return False
     elif reply and len(self.nome.get()) > 0:
         self.salvar(self)
         return True
     else:
         return True
示例#11
0
 def load_game(self):
     if self.active_profile is not None:
         a = messagebox.askyesnocancel(
             "Game is loaded",
             "Do you wish to save your current game?",
         )
         if a is None:
             return
         elif a is True:
             self.save_game()
     MyDialog(self.tkRoot, "What if your fighter's name?", self, "recreate_player")
示例#12
0
	def onCmdChooseFile(self,extra=None):
		'''文件选择'''
##		oldstat=self.stat
##		if self.stat==const.StatPlaying and self.timerid:
##			self.pauseShow(const.StatPaused)
		f=tkFileDialog.askopenfilenames(parent=self.root,title='Choose file(s) to show',
			initialdir=self.c.recent_dir,
			filetypes=[('Text','*.txt *.log'),('Python', '*.py *.pyw'), ('All files', '*')] )
		if f:
			flist=self.root.tk.splitlist(f) # http://psf.upfronthosting.co.za/roundup/tracker/issue5712 workaround: http://code.activestate.com/lists/python-tkinter-discuss/2016/
			if len(flist)>5:
				self.logger.info('一次最多添加5个文件,多余的会被丢弃,你选择了 %d个',len(flist))
				flist=flist[:5]
			for i,onefile in enumerate(flist):
				self.logger.debug('multi file %02d/%d: %s',i,len(flist),onefile)

			addorreplace=tkMessageBox.askyesnocancel('Add or replace','add the file(s) to your file list? (press "no" will replace current file list)',default=tkMessageBox.YES)
			self.logger.debug('addorreplace=%s',addorreplace)
			self.c.recent_dir=os.path.split(flist[0])[0]
			if addorreplace==None:
				self.logger.debug('do nothing')
			elif addorreplace==True: # add
				self.c.file.extend([i,0] for i in flist)
				# 更新filelist菜单
				for i in flist:
					self.cur_list_menu.add_radiobutton(label=os.path.basename(i),command=self.onCmdSwitchFile,
						value=i,variable=self.vFile)
				# 从recent中删除当前文件列表中存在的
				self.c.recent=[i for i in self.c.recent if i[0] not in (j[0] for j in self.c.file)]
				self.logger.debug('add done. new file list: %s',self.c.file)

			elif addorreplace==False: # replace
				if self.stat==const.StatPlaying:
					self.pausePanel(const.StatPaused4Switch)

				# 从recent中删除当前文件列表中存在的
				self.c.recent=[i for i in self.c.recent if i[0] not in (j[0] for j in self.c.file)]
				self.cur_list_menu.delete(0,len(self.c.file)-1) # 删掉filelist菜单
				# 当前文件列表入recent
				for t in reversed(self.c.file):
					self.c.recent.insert(0,t)
				del self.c.file[:]
				# 新文件入当前文件列表
				self.c.file.extend([[i,0] for i in flist])
				# 从recent中删除当前文件列表中存在的
				self.c.recent=[i for i in self.c.recent if i[0] not in (j[0] for j in self.c.file)]
				# 构造新filelist菜单
				self.c.cur=0
				for idx,i in enumerate(self.c.file):
					self.cur_list_menu.add_radiobutton(label=os.path.split(i[0])[1],command=self.onCmdSwitchFile,
						value=i[0],variable=self.vFile)
					if idx==self.c.cur:
						self.cur_list_menu.invoke(idx)
				self.logger.debug('replace done. new file list: %s\nnew recent: %s',self.c.file,self.c.recent)
示例#13
0
    def onClosing(self):
        if self._modified:
            _choice = messagebox.askyesnocancel("Speichern/Beenden",
                                                "Vor dem Beenden speichern?")
            if _choice is False:
                pass
            elif _choice is True:
                self._saveAll()
            else:
                return False

        self._master.destroy()
示例#14
0
 def Clear_Program (self, event = None):
     save = messagebox.askyesnocancel (title = "Save?", message = "Do you want to save this file?")
     #cancel
     if save == None:
         return
     #save file
     elif save == True:
         self.Save_Program()
     #don't save
     self.document_name = None
     self.root.title("Webpage")
     self.HTML_box.replace("1.0", "end", "")
示例#15
0
 def quit(self):
     if self.settings_dirty.get() or self.project_dirty.get():
         savechanges = messagebox.askyesnocancel("Save changes", "You have unsaved project changes. Do you want to save them before quitting?")
         if savechanges is None:
             return
         elif savechanges:
             self.noask_save_project()
         self.master.destroy()
     else:
         # write gui settings and destroy
         self.write_gconfig()
         self.master.destroy()
示例#16
0
    def close_tab(self,*event):
        def kill_tab(self,tab_index):
            del self.model.tabs_html[tab_index]
            del self.text_fields[tab_index]
            self.html_text_tabs.forget(tab_index)
            if len(self.model.tabs_html)>0:
                self.html_text_tabs.select(0)
                self.model.selected_tab = 0
            else:
#here is the way to let open at least 1 tab instead of closing the app
                self.model.start_mod = 2
                self.model._start_new_session()#open with a different name than last name used
        
        tab_index = self.model.selected_tab
        current_object = self.model.tabs_html[tab_index]
        if event[0] == "for_save":
            if not current_object.saved:
                answer = messagebox.askyesnocancel(title=_("Attention"), message=_("Voulez vous sauvegarder avant de fermer l'onglet %s?" % (self.html_text_tabs.tab(tab_index,option='text'))))#True False ou None 
                if answer and not self.model.save_html_file():
                        return "cancel"
                elif answer is None:                                      # Cancel or X pressed
                    return "cancel"
            return "no_cancel"
        elif event[0]=="for_save_no_warning":
            if not current_object.saved and not self.model.save_html_file():
                return "cancel"
            return "no_cancel"
        elif event[0]=="already_saved":
            kill_tab(self,tab_index,)
        else:#manual tab_closing
            if not current_object.saved:
                answer = messagebox.askyesnocancel(title=_("Attention"), message=_("Voulez vous sauvegarder avant de fermer cet onglet ?"))#True False ou None 
                if answer:                                                      # Yes
                    if self.model.save_html_file():
                        kill_tab(self,tab_index)
                elif answer is None: pass                                  # Cancel or X pressed
                else :
                    kill_tab(self,tab_index)                             # No
            else:
                kill_tab(self,tab_index)
示例#17
0
 def close(self, *discard):
     logger.info("Closing")
     if self.text.edit_modified():
         logger.info("File has been modified and not saved")
         save = messagebox.askyesnocancel(title="Close file",
                                          message="File {} has unsaved changes. Save?".format(self.fname))
         if save is None:
             return False
         elif save is True:
             self.save()
         else:
             logger.warning("Changes not saved")
     return True
示例#18
0
 def on_closing():
     if Pianokey.boo:
         answer = messagebox.askyesnocancel("Quit", "You're still recording! Do you want to save?")
         if answer == None:
             master.destroy()                
             return None
         elif answer:
             filewriter()
             master.destroy()
         else:
             master.destroy()
     else:
         master.destroy()
示例#19
0
 def check(self, master):
     if not self.view.changed():
         return True
     choice = messagebox.askyesnocancel(
         "I'm helping you",
         "Looks like you have changed things and not saved, do you want to now?",
         default=messagebox.CANCEL,
         icon=messagebox.QUESTION,
         parent=master)
     if choice == True:
         return self.save(master)
     else:
         return (choice == False) # If cancelled then will be None
示例#20
0
    def wclose(self, event=0):
        if self.parent.title()[0] == "*":
            save = messagebox.askyesnocancel("Save file", "You have unsaved changes.\nDo you want to save before closing?")

            if save == True:
                self.save_file()
                if self.parent.title()[0] == "*":
                    self.wclose()
                else:
                    root.destroy()

            elif save == False:
                root.destroy()
        else:
            root.destroy()
示例#21
0
def askInternetLogon(parent, url, quotedUrl, dialogCaption, dialogText, untilDoneEvent, result):
    # received Html suggests url may require web page logon (due to receivedHtml)
    r = messagebox.askyesnocancel(dialogCaption, dialogText)
    if r is None:
        result.append("cancel")
    elif r == False:
        result.append("no")
    else:
        import webbrowser
        webbrowser.open(quotedUrl, new=1, autoraise=True)
        r = messagebox.askretrycancel(dialogCaption,
                                      _("After logging on (by web browser, if applicable) click 'retry' to reload web file"))
        if r:
            result.append("retry")
        else:
            result.append("cancel")
    untilDoneEvent.set()
示例#22
0
def fileOpen(fvpTree):

    global curFilePath, curFileName,fileOptions, unsavedChanges
    newFilePath =()
    newCal = []
    visibleComps = []
    #1. Unsaved Changes
    if (unsavedChanges == 1):
        yN = messagebox.askyesnocancel(title = "Unsaved Changes",message = "You have Unsaved Changes. Would you like to save?")
        if(yN == None):
            return
        elif (yN == True):
            fileSave()

    
    #2. Open file
    fileOptions['title'] = 'Open'
    newFilePath = filedialog.askopenfilename(**fileOptions)
    if (len(newFilePath) != 0):

        newFileName = newFilePath[newFilePath.rfind('/')+1:]
        
        
        #3. Run Wrapper for readCalFile
        status = readAndDisplayComp(str(newFilePath),fvpTree)
        if (status == "OK"):
   
            callCalInfo(fvpTree.cal.pointer,fvpTree.cal.visibleComps)

            #Make menu options, fvp buttons and Change title bar
            fileMenu.entryconfigure('Save',state = NORMAL)
            fileMenu.entryconfigure('Save as...',state = NORMAL)
            fileMenu.entryconfigure('Combine...',state = NORMAL)
            fileMenu.entryconfigure('Filter...',state = NORMAL)
            toDoMenu.entryconfigure('To-do List...',state = NORMAL)
            exEvBut.configure(state = NORMAL)
            exXBut.configure(state = NORMAL)
            showSelBut.configure(stat = DISABLED)

            curFilePath = newFilePath
            curFileName = newFileName
            updateTitlebar("xcal - "+curFileName)
        else:
            status = "Failed to open \""+newFileName+"\"\n" + status
            writeToTextLog(textLog,"&SEP&")
            writeToTextLog(textLog,status)
示例#23
0
 def maybesave(self):
     if self.get_saved():
         return "yes"
     message = "Do you want to save %s before closing?" % (self.filename or "this untitled document")
     confirm = tkMessageBox.askyesnocancel(
         title="Save On Close", message=message, default=tkMessageBox.YES, parent=self.text
     )
     if confirm:
         reply = "yes"
         self.save(None)
         if not self.get_saved():
             reply = "cancel"
     elif confirm is None:
         reply = "cancel"
     else:
         reply = "no"
     self.text.focus_set()
     return reply
示例#24
0
def checkNewVersion(version):
    "checks whether there is a new version available"
    newVersion = returnSiteContent("http://www.cmmanagerweb.appspot.com/version").split(".")
    try:
        from optionget import optionGet
        from version import version as currentVersion
        versionSeen = optionGet("DontShowVersion", currentVersion(), "list")
    except Exception:
        versionSeen = version
    for i in range(3):
        if int(newVersion[i]) > int(versionSeen[i]):
            code = returnSiteContent("http://www.cmmanagerweb.appspot.com/code")
            curl = "https://raw.github.com/bahniks/CM_Manager_{}_{}_{}/master/Stuff/code.txt"
            curl = urlopen(curl.format(*newVersion))
            ghcode = curl.read().strip()
            if int(code) != int(ghcode):
                return            
            message = "New version of Carousel Maze Manager ({}.{}.{}) is available.\n".format(
                *newVersion) + "Do you want to download and install the new version?"
            root = makeRoot()
            answ = messagebox.askyesnocancel(message = message, icon = "question",
                                             title = "New version available", default = "yes",
                                             detail = "Select 'No' to not be asked again.")
            if answ is None:
                pass
            elif answ:
                root.config(cursor = "wait")
                try:
                    download(newVersion)
                    if "version" in sys.modules:
                        imp.reload(sys.modules["version"])
                except Exception as e:
                    messagebox.showinfo(title = "Error", icon = "error", detail = e,
                                        message = "Some problem with updating occured.")
                finally:
                    root.config(cursor = "")
            else:
                try:
                    from optionwrite import optionWrite
                    optionWrite("DontShowVersion", newVersion)
                except Exception:
                    pass
            root.destroy()
            break
示例#25
0
def call_back():
    if messagebox.askyesno('Hi', 'Hi Ljian'):
        print("Clicked Yes")
    else:
        print("Clicked No")

    if messagebox.askyesnocancel('Hi', 'Hi Ljian'):
        print("Clicked Yes")
    else:
        print("Clicked No")

    if messagebox.askokcancel('Hi', 'Hi Ljian'):
        print("Clicked Yes")
    else:
        print("Clicked No")

    if messagebox.askquestion('Hi', 'Hi Ljian'):
        print("Clicked Yes")
    else:
        print("Clicked No")
示例#26
0
def rename_file(source, new_name):
    global RUNNING_OPERATIONS
    src_path = os.path.sep.join(source.split(os.path.sep)[:-1])
    new_file = os.path.join(src_path, new_name)
    if os.path.exists(new_file):
        replace = messagebox.askyesnocancel(
            "Destination already exists",
            "The {} you are trying to paste already exists in the target"
            " destination.\n Would you like to replace the file that already exists?".format(
                "file" if os.path.isfile(source) else "folder"
            )
        )
        if replace is None:  # Cancel Operation
            return
        elif replace is True:  # Replace existing file
            os = get_os_type()
            if os == "Windows":
                RUNNING_OPERATIONS.append(DeleteOperation(new_file))
        else:  # Auto-Rename File
            new_file = rename_copy(source, new_file)
    RUNNING_OPERATIONS.append(MoveOperation(source, new_file))
示例#27
0
    def closeProject(self):
        """Close"""

        if self.projopen == False:
            w = False
        else:
            w = messagebox.askyesnocancel("Close Project",
                                        "Save this project?",
                                        parent=self.master)
        if w==None:
            return
        elif w==True:
            self.saveProject()
        else:
            pass
        for n in self.nb.tabs():
            self.nb.forget(n)
        self.filename = None
        self.projopen = False
        self.main.title('DataExplore')
        return w
示例#28
0
    def revert_file_event(self, event):
        fname = self.io.filename
        if fname is None:
            # No file associated.
            return

        if not self.io.get_saved():
            msg = "Do you want to save a copy of %s before reverting?" % fname
            res = tkMessageBox.askyesnocancel(
                    master=self.text,
                    title="Save a copy",
                    message=msg)
            if res is None:
                # Canceled.
                return
            elif res:
                self.io.save_a_copy(event)
                # XXX Maybe it would be better to not revert the file when
                # user cancels the dialog that saves a copy of the current
                # file.

        self.io.loadfile(fname)
 def action_0_1(self):
     ##
     ## run the action
     entriless = actions.PrintNotInDirectory([self.directory, self.roster])
     ##
     ## print some of the counts to the screen for the user to review
     message = 'Found ' + str(
         len(entriless
             )) + ' people on the roster who were not in the directory.\n'
     message += '\nThe results will be shown on the screen.  Would you like to save them in a file as well?'
     message += '\n\n(Click "Cancel" to do neither)'
     ##
     ## prompt user whether to show on screen
     action = messagebox.askyesnocancel(title='Next Steps', message=message)
     if action is None:
         print('Not showing or storing results')
     else:
         for entry in entriless:
             print(
                 "Did not find this family from the roster in the directory: "
             )
             entry.Print()
         if action == True:
             import_file_tools.CreateFileFromFamily(entriless)
示例#30
0
 def exit(self, event=None):
     try:
         if self.statusbar.text_changed:  # text_changed = True -> text changed/modified then ask for save the changes or not
             mbox = messagebox.askyesnocancel(
                 'Warning', 'Do you want to save the file?'
             )  # Options -> Yes/No/Cancel
             # no option forked for -> CANCEL, only for -> YES, NO
             #if user select -> YES
             if mbox is True:  #we want to change the file
                 if self.url:  # file exist in text editor
                     content = self.text_write.text_editor.get(
                         1.0, tk.END)  # get from begining to last
                     with open(self.url, 'w',
                               encoding='utf-8') as fw:  #filewriter
                         fw.write(content)
                         self.root.destroy()  # to cancel window
                 else:  #file not exist in text editor
                     content2 = str(
                         self.text_write.text_editor.get(1.0, tk.END))
                     #path to save file-> filedialog.asksaveasfilename(file mode, default extension, file types to write)
                     self.url = filedialog.asksaveasfile(
                         mode='w',
                         defaultextension='.txt',
                         filetypes=(('Text File', '*.txt'), ('All files',
                                                             '*.*')))
                     self.url.write(content2)
                     self.url.close()
                     self.root.destroy()
                 # If User select -> No  , text in  editor and we destroyed it
             elif mbox is False:
                 self.root.destroy()
             # If text_change = False -> editor has no text
         else:
             self.root.destroy()
     except:
         return
示例#31
0
def paste_file(target, cb_func=None):
    global CURRENT_COPY_OP, RUNNING_OPERATIONS
    if CURRENT_COPY_OP is None:
        return
    source = CURRENT_COPY_OP.src
    src = source.split(os.path.sep)[-1]
    dst = os.path.join(target, src)
    if os.path.exists(dst):
        replace = messagebox.askyesnocancel(
            "Destination already exists",
            "The {} you are trying to paste already exists in the target"
            " destination.\n Would you like to replace the file that already exists?".format(
                "file" if os.path.isfile(source) else "folder"
            )
        )
        if replace is None:
            return
        elif replace is True:
            func = paste_replace(source, dst)
        else:
            dst, func = paste_rename(source, dst)
    else:
        func = paste_to_existing(source)
    RUNNING_OPERATIONS.append(PasteOperation(func, source, dst, cb_func))
示例#32
0
 def save(self, move=False):
     dic = self.meta()
     assert self.openF.files != [], "Must pick file(s) to associate!"
     dic['files'] = self.openF.files
     dic['i'] = dt.datetime.now()
     dic['broken_link'] = '0'
     dic['faulty'] = '0'
     directory = self.openF.dir.get()
     dic['directory'] = directory
     fp = os.path.join(directory, "header.json")
     if os.path.isfile(fp):
         r = messagebox.askyesnocancel(
             "Header File Exists!",
             "Overwrite existing json file?\nThis will destroy previous header file and overwrite previous database entry."
         )
         print(r)
         if r == None:
             return None
         elif r:
             f = open(fp)
             dicOld = json.load(f, cls=dtDecoder)
             f.close()
             self.db.removeIndex(dicOld['i'])
         else:
             fp = fp[:-5] + "{}.json".format(
                 len(glob.glob(os.path.join(directory, "header*.json"))))
     f = open(fp, "w")
     json.dump(dic, f, indent=4, cls=dtEncoder)
     f.close()
     self.db.push(dic)
     if move:
         for f in self.openF.files:
             copy(f, directory)
         dic['files'] = [os.path.join(directory,os.path.basename(f))\
                         for f in self.openF.files]
     return None
示例#33
0
    def exit(self, event=None):
        '''When user wants to exit the program'''

        if self.is_file_changed():
            choice = messagebox.askyesnocancel(
                'ZPAD', 'Do you really want to quit without saving?')

            if choice is True:
                self.delete_zoom()
                self.master.destroy()

            elif choice is False:
                self.save()

                if not self.is_file_changed():
                    self.delete_zoom()
                    self.master.destroy()

            else:
                return

        else:
            self.delete_zoom()
            self.master.destroy()
示例#34
0
 def check_allow_closing(self):
     modified_editors = [e for e in self.winfo_children() if e.is_modified()]
     
     if len(modified_editors) == 0:
         return True
     
     confirm = tkMessageBox.askyesnocancel(
               title="Save On Close",
               message="Do you want to save files before closing?",
               default=tkMessageBox.YES,
               master=self)
     
     if confirm:
         for editor in modified_editors:
             if editor.get_filename(True):
                 editor._cmd_save_file()
             else:
                 return False
         return True
     
     elif confirm is None:
         return False
     else:
         return True
示例#35
0
def exit_func(event=None):
    global url, text_changed
    try:
        if text_changed:
            mbox = messagebox.askyesnocancel('Warning', 'Do you want to save the file ?')
            if mbox is True:
                if url:
                    content = text_editor.get(1.0, tk.END)
                    with open(url, 'w', encoding='utf-8') as fw:
                        fw.write(content)
                        main_application.destroy()
                else:
                    content2 = str(text_editor.get(1.0, tk.END))
                    url = filedialog.asksaveasfile(mode='w', defaultextension='.txt',
                                                   filetypes=(('Text File', '*.txt'), ('All files', '*.*')))
                    url.write(content2)
                    url.close()
                    main_application.destroy()
            elif mbox is False:
                main_application.destroy()
        else:
            main_application.destroy()
    except:
        return
示例#36
0
 def saveGame(self):
     result = messagebox.askyesnocancel("Save", \
                             "Do you want to save game?")
     return result
示例#37
0
def yes_no():
    answer = messagebox.askokcancel("Question","Do you want to open this file?")
    answer = messagebox.askretrycancel("Question", "Do you want to try that again?")
    answer = messagebox.askyesno("Question","Do you like Python?")
    answer = messagebox.askyesnocancel("Question", "Continue playing?")
def Exit():
     res=messagebox.askyesnocancel("Notification","Do you want to exit")
     if res==True:
         root.destroy()
示例#39
0
文件: tkeasy.py 项目: lenskikh/tkeasy
def msg_box_ask(name,title,message): 
    memory[name] = messagebox.askyesnocancel(title=title, message=message)
示例#40
0
def edf_file_deidentify():
    # Load the file
    root.filenames = filedialog.askopenfilenames(
        initialdir="~/",
        title="Select EDF file(s)",
        filetypes=(("EDF files", "*.edf"), ("All files", "*.*")))
    # Handle file cancel
    if root.filenames == '':
        root.destroy()
        sys.exit("Closing executable...")

    # Check if user wants to overwrite data
    copy_file = messagebox.askyesnocancel(
        title="EDF Deidentifier",
        message="Would you like to save the a copy of the data?")

    # Exit if cancel
    if copy_file is None:
        root.destroy()
        sys.exit("Closing executable...")

    # Double check!
    if not copy_file:
        result = messagebox.askyesno(
            title="EDF Deidentifier",
            message="Are you sure you want to overwrite all edf files with the "
            + "deidentified files?")
        if not result:
            root.destroy()
            sys.exit("Closing executable...")

    # Loop through all file names
    for path in root.filenames:

        # Skip if bad file
        if not (os.path.isfile(path)):
            print("Invalid file: " + path)
            continue

        # Copy file to new name
        if copy_file:
            os.chdir(os.path.split(path)[0])
            file_savedir = filedialog.askdirectory()
            path_new = file_savedir + '/' + os.path.basename(
                path)[0:-4] + '_deidentified.edf'
            shutil.copy(path, path_new)
            path = path_new

        # Open file(s) and deidentify
        f = open(path, "r+", encoding="iso-8859-1")  # 'r' = read
        try:
            f.write('%-8s' % "0")
            f.write('%-80s' % "X X X X")  # Remove patient info
            f.write('%-80s' % "Startdate X X X X")  # Remove recording info
            f.write('01.01.01')  # Set date as 01.01.01
        except UnicodeDecodeError:
            f.close()
            f = open(path, "r+", encoding="iso-8859-2")  # 'r' = read
            try:
                f.write('%-8s' % "0")
                f.write('%-80s' % "X X X X")  # Remove patient info
                f.write('%-80s' % "Startdate X X X X")  # Remove recording info
                f.write('01.01.01')  # Set date as 01.01.01
            except UnicodeDecodeError:
                f.close()
                f = open(path, "r+", encoding="utf-8")  # 'r' = read
                try:
                    f.write('%-8s' % "0")
                    f.write('%-80s' % "X X X X")  # Remove patient info
                    f.write('%-80s' %
                            "Startdate X X X X")  # Remove recording info
                    f.write('01.01.01')  # Set date as 01.01.01
                    f.close()
                finally:
                    print('No valid encoding format found')

    txt = Label(root, text="File(s) Saved")
    txt.place(relx=0.48, rely=0.95, anchor=CENTER)
示例#41
0
def prompt_save():
    return askyesnocancel("Save",
                          "Do you want to save the current competition?")
示例#42
0
def _msgBox_yn():
    answer = msg.askyesnocancel('Quit', 'Are you sure you want to quit?')
    if answer == True:
        quit()
def event7():
    res = messagebox.askyesnocancel('Notification', 'Do you want to exit?')
    if (res == True):
        base.destroy()
示例#44
0
def ask_bool_parameter(label: str):
    return messagebox.askyesnocancel(label, label)
示例#45
0
def confirm_close():
    return messagebox.askyesnocancel(
        message="You have unsaved changes. Are you sure you want to close?",
        icon="question",
        title="Unsaved Changes")
示例#46
0
文件: gui.py 项目: bigzero95/no-sleep
def yesnocancel():
    msgbox.askyesnocancel(title=None, message="sd" "예/아니오")
示例#47
0
def yes():
    messagebox.askyesnocancel("edit","do you really")
示例#48
0
info_button = Button(root, text="Info Box", command=info_box)
info_button.grid(column=0, row=0)

error_button = Button(root, text="Error Box", command=error_box)
error_button.grid(column=1, row=0)

warning_button = Button(root, text="Warning Box", command=warning_box)
warning_button.grid(column=2, row=0)

root.mainloop()

# There are other types of message boxes as well.

root = Tk()
root.title("Buttons")
root.geometry("300x300")
root.iconbitmap("assets/favicon.ico")
answer = messagebox.askyesno("Yes or No Box", "Do you like Blue?")
if answer:
    print("\nYou like blue!!")
else:
    print("\nOh, guess not everyone likes blue.")

temp = messagebox.askokcancel("Okay,Cancel Box", "This is another message box!")
temp = messagebox.askretrycancel("Retry, Cancel Box", "What do you want to do?")
temp = messagebox.askyesnocancel("Yes,No,Cancel Box", "Do you like PYTHON!????")
if temp:
    print("\nNice")
else:
    print("\nOh, guess not everyone likes Python xD")
示例#49
0
def end():
    ask = m_box.askyesnocancel('Notification','Do you want to exit')
    if ask:win.destroy()
示例#50
0
def askConfirmation():
    res = messagebox.askyesnocancel(
        "Are you sure?", "Are you sure want to send this message to all your customers?")
    return res
示例#51
0
文件: 2.08.py 项目: leonardowolf/tk
fr1 = Frame(root)
fr2 = Frame(root)
opt = {'fill': BOTH, 'side': LEFT, 'padx': 2, 'pady': 3}


# Demo of tkinter.messagebox
Label(fr1, text="Demo of tkinter.messagebox").pack()
Button(fr1, text='info', command=lambda: tmb.showinfo(
    "Show Info", "This is FYI")).pack(opt)
Button(fr1, text='warning', command=lambda: tmb.showwarning(
    "Show Warning", "Don't be silly")).pack(opt)
Button(fr1, text='error', command=lambda: tmb.showerror(
    "Show Error", "It leaked")).pack(opt)
Button(fr1, text='question', command=lambda: tmb.askquestion(
    "Ask Question", "Can you read this ?")).pack(opt)
Button(fr2, text='okcancel', command=lambda: tmb.askokcancel(
    "Ask OK Cancel", "Say Ok or Cancel?")).pack(opt)
Button(fr2, text='yesno', command=lambda: tmb.askyesno(
    "Ask Yes-No", "Say yes or no?")).pack(opt)
Button(fr2, text='yesnocancel', command=lambda: tmb.askyesnocancel(
    "Yes-No-Cancel", "Say yes no cancel")).pack(opt)
Button(fr2, text='retrycancel', command=lambda: tmb.askretrycancel(
    "Ask Retry Cancel", "Retry or what?")).pack(opt)


fr1.pack()
fr2.pack()

root.mainloop()
示例#52
0
def parse_command(s, rownum):
    global driver
    tokens = s.split()
    if len(tokens) < 1 or driver is None:
        return
    try:
        if tokens[0] == 'click':
            global selected, selector
            selector = user_vars[tokens[1]]
            elem = query_selector(selector, 3)
            selected = elem
            driver.execute_script("document.querySelector('" + selector +
                                  "').click();")
            return
        if tokens[0] == "type":
            selected.send_keys(expand_boi(user_vars[tokens[1]]))
            return
        if tokens[0] == "put":
            totype = expand_boi(user_vars[tokens[1]]).replace("\n",
                                                              "\\n").replace(
                                                                  '"', '\\"')
            scriptyboi = 'document.querySelector("' + selector + '").value = "' + totype + '";'
            driver.execute_script(scriptyboi)
            return
        if tokens[0] == "clear":
            selected.send_keys(Keys.CONTROL + "a")
            selected.send_keys(Keys.DELETE)
            return
        if tokens[0] == "log":
            global logging
            if not logging:
                logging = True
            csvdat[rownum][tokens[1]] = user_vars[tokens[1]]
        if tokens[0] == "enter":
            selected.send_keys(Keys.RETURN)
            return
        if tokens[0] == 'goto':
            driver.get(user_vars[tokens[1]])
            return
        if tokens[0] == 'set':
            quotes = all_indices(s, "'")
            user_vars[tokens[1]] = s[quotes[0] + 1:quotes[1]]
            return
        if tokens[0] == 'get':
            elem = query_selector(user_vars[tokens[2]], 3, friendly=True)
            if elem is None:
                user_vars[tokens[1]] = ""
                return
            if elem.tag_name == 'input' or elem.tag_name == 'textarea':
                user_vars[tokens[1]] = elem.get_attribute("value")
            else:
                user_vars[tokens[1]] = elem.text
            return
        if tokens[0] == 'paste' and len(tokens) == 4:
            user_vars[tokens[1]] = user_vars[tokens[2]] + user_vars[tokens[3]]
            return
        if tokens[0] == 'cut':
            tokens = [
                len(user_vars[tokens[2]])
                if t == 'END' else int(t) if t.isdigit() else t for t in tokens
            ]
            if len(tokens) == 4:
                user_vars[tokens[1]] = user_vars[tokens[2]][:tokens[3]]
            elif len(tokens) == 5:
                user_vars[tokens[1]] = user_vars[
                    tokens[2]][tokens[3]:tokens[4]]
            return
        if tokens[0] == 'confirm':
            ok = askyesnocancel("Confirmation", "Does this look right?")
            if ok is None:
                raise TypeError("Abort mission")
            if not ok:
                raise LookupError()
            return
    except (NoSuchWindowException, AttributeError):
        driver.quit()
        driver = None
        raise ValueError("Some webdriver related exception occurred.")
    except IndexError:
        raise IndexError("Error in command: '" + s + "'. ")
示例#53
0
 def _quit():
     ans = msg.askyesnocancel('Quit Window', 'Do You Want to Quit ?')
     if (ans):
         # main_window.quit()
         #main_window.destroy()
         main_window.after(2000, main_window.destroy)
示例#54
0
    def extract_minecraft_jar(self):
        minecraft_version = self.widget_combobox_version.get()
        minecraft_jar_path = self.minecraft_versions + "/" + minecraft_version + "/" + minecraft_version + ".jar"
        self.pack_location = self.minecraft_resource_packs + "/" + self.variable_string_name.get(
        )

        amount = functions.zip_files(minecraft_jar_path)
        for item in self.included_mods:
            amount += functions.zip_files(item)

        progress = dialog.ProgressWindow(self.parent,
                                         title="Extracting Pack",
                                         maximum=amount)

        count = 0

        if os.path.isdir(self.pack_location):
            messagebox.showwarning(
                "Warning", "The pack '{}' already exists.".format(
                    self.variable_string_name.get()))
            delete = messagebox.askyesnocancel(
                "Delete Pack", "Would you like to delete the pack?")
            if delete:
                threading.Thread(target=self.remove_previous_pack).start()
            elif not delete:
                return
        elif not os.path.exists(self.pack_location):
            os.makedirs(self.pack_location)

        with zipfile.ZipFile(minecraft_jar_path, "r") as z:
            # z.extractall(self.widget_directory_location.get() + "/" + self.variable_string_name.get())
            for file in z.namelist():
                if file.startswith("assets/") or file == "pack.png":
                    # print("{} | Extracting: {}".format(datetime.now().strftime("%H:%M:%S"), file))
                    z.extract(file, self.pack_location)

                    count += 1
                    progress.variable_name.set("Current File: " + file)
                    progress.variable_percent.set("{}% Complete".format(
                        round(100 * float(count) / float(amount))))
                    progress.variable_progress.set(
                        progress.variable_progress.get() + 1)

        with open(self.pack_location + "/" + "pack.mcmeta", "w+") as file:
            file.write(
                json.dumps(
                    {
                        "pack": {
                            "pack_format":
                            2,
                            "description":
                            self.widget_text_description.get(
                                1.0, "end").strip("\n") +
                            " - Made with Quiver."
                        }
                    },
                    sort_keys=False,
                    indent=2))

            count += 1
            progress.variable_name.set("Current File: " + file.name)
            progress.variable_percent.set("{}% Complete".format(
                round(100 * float(count) / float(amount))))
            progress.variable_progress.set(progress.variable_progress.get() +
                                           1)

        for item in self.included_mods:
            # print(item)
            with zipfile.ZipFile(" ".join(item["tags"])) as z:
                for file in z.namelist():
                    if file.startswith("assets/"):
                        print("{} | Extracting: {}".format(
                            datetime.now().strftime("%H:%M:%S"), file))
                        z.extract(file, self.pack_location)

                        count += 1
                        progress.variable_name.set("Current File: " + file)
                        progress.variable_percent.set("{}% Complete".format(
                            round(100 * float(count) / float(amount))))
                        progress.variable_progress.set(
                            progress.variable_progress.get() + 1)

        progress.destroy()
        messagebox.showinfo(title="Information",
                            message="Extracting complete.")

        self.parent.directory = self.pack_location
        self.parent.cmd.tree_refresh()
        self.destroy()
示例#55
0
 def exitCommand(self):
     a = messagebox.askyesnocancel(title="Exiting...",
                                   message='Are you sure want to exit')
     if a:
         self.root.quit()
示例#56
0
    def __open_file(self, text_area, window, filename, status_bar):
        """
        Allows for opening existing .txt files
        """

        try:
            # If the file is untitled and there is text in the text area, prompts the user to save
            if filename.get() == "Untitled" and len(
                    text_area.get("1.0", "end-1c")) > 0:
                response = messagebox.askyesnocancel(
                    "TextEditor",
                    f"Do you want to save changes to {filename.get()}?")

                if response == 1:
                    # If the user response is yes, brings up the save as menu
                    file = self.__save_as(text_area, window, filename)

                    if file:
                        # After saving prompts user to pick which file to open
                        file = askopenfilename(filetypes=self.__file_types)
                        filename.set(file)
                        window.title(
                            f"{os.path.basename(filename.get())} - TextEditor")
                        file = open(file, "r")
                        text_from_file = file.read()
                        text_area.delete("1.0", "end")
                        text_area.insert(tk.END, text_from_file)
                        file.close()
                        text_area.edit_modified(False)
                        self.__file_saved.set(False)
                        status_bar.update_word_and_character_count(
                            None, text_area)
                    else:
                        pass
                elif response == 0:
                    # If the user response is no, opens a new file without prompting to save
                    file = askopenfilename(filetypes=self.__file_types)
                    filename.set(file)
                    window.title(
                        f"{os.path.basename(filename.get())} - TextEditor")
                    file = open(file, "r")
                    text_from_file = file.read()
                    text_area.delete("1.0", "end")
                    text_area.insert(tk.END, text_from_file)
                    file.close()
                    text_area.edit_modified(False)
                    self.__file_saved.set(False)
                    status_bar.update_word_and_character_count(None, text_area)
                else:
                    # If the user response is cancel nothing happens
                    pass
            # If the file is an existing file and the file has been modified, prompts the user to save
            elif filename.get() != "Untitled" and text_area.edit_modified(
            ) and not self.__file_saved.get():
                response = messagebox.askyesnocancel(
                    "TextEditor",
                    f"Do you want to save changes to {filename.get()}?")

                if response == 1:
                    # If the user response is yes, saves the file
                    self.__save(text_area, window, filename)

                    # After saving, prompts the user to pick a file to open
                    file = askopenfilename(filetypes=self.__file_types)
                    filename.set(file)
                    window.title(
                        f"{os.path.basename(filename.get())} - TextEditor")
                    file = open(file, "r")
                    text_from_file = file.read()
                    text_area.delete("1.0", "end")
                    text_area.insert(tk.END, text_from_file)
                    file.close()
                    text_area.edit_modified(False)
                    self.__file_saved.set(False)
                    status_bar.update_word_and_character_count(None, text_area)
                elif response == 0:
                    # If the user response is no, prompts the user to pick a file to open without prompting to save
                    file = askopenfilename(filetypes=self.__file_types)
                    filename.set(file)
                    window.title(
                        f"{os.path.basename(filename.get())} - TextEditor")
                    file = open(file, "r")
                    text_from_file = file.read()
                    text_area.delete("1.0", "end")
                    text_area.insert(tk.END, text_from_file)
                    file.close()
                    text_area.edit_modified(False)
                    self.__file_saved.set(False)
                    status_bar.update_word_and_character_count(None, text_area)
                else:
                    # If the user response is cancel nothing happens
                    pass
            else:
                # If the file is an untitled file or existing file and the file has not been modified, prompts user
                # to open a file without first prompting to save
                file = askopenfilename(filetypes=self.__file_types)

                if file:
                    filename.set(file)
                    window.title(
                        f"{os.path.basename(filename.get())} - TextEditor")

                file = open(file, "r")
                text_from_file = file.read()
                text_area.delete("1.0", "end")
                text_area.insert(tk.END, text_from_file)
                file.close()
                text_area.edit_modified(False)
                self.__file_saved.set(False)
                status_bar.update_word_and_character_count(None, text_area)
        # Catches the FileNotFoundError is user clicks cancel on the Open File pop up
        except FileNotFoundError:
            pass
示例#57
0
 def chk_on(self):
     if (self.proc.is_alive()):
         try:
             self.txt_qu = qu.get(0)
             if self.lst_chk == 1 and self.txt_qu == "Enter your name:" or self.lst_chk == 1 and self.txt_qu == "Find your name from the list and type:":
                 self.lst_chk = 0
             if self.lst_chk == 1:
                 self.txt_conv.insert('end', self.txt_qu + "\n", 'lst')
                 self.txt_conv.insert('end', "\n", 'g')
             else:
                 if "PDFPG" in self.txt_qu:
                     self.USER_INP = simpledialog.askinteger(
                         title="Page Number",
                         prompt="Enter Page Number:")
                     qu.put(self.USER_INP)
                     self.txt_conv.insert(
                         'end',
                         "Page Number: " + (str(self.USER_INP)) + "\n")
                     self.txt_conv.insert('end', "\n", 'g')
                     sleep(1)
                 elif "REG1PER2" in self.txt_qu:
                     self.USER_INP = simpledialog.askstring(
                         title="Name", prompt="Enter Your Name:")
                     sleep(0.5)
                     if self.USER_INP == None:
                         qu.put(self.USER_INP)
                         self.txt_conv.insert('end', "CANCEL\n")
                         self.txt_conv.insert('end', "\n", 'g')
                     elif self.USER_INP == "":
                         qu.put(self.USER_INP)
                     else:
                         self.txt_conv.insert('end',
                                              self.USER_INP + "\n")
                         self.txt_conv.insert('end', "\n", 'g')
                         qu.put(self.USER_INP.lower())
                     sleep(0.5)
                 elif "CON1FAC2" in self.txt_qu:
                     self.txt_conv.insert(
                         'end', "Do I identifying you correctly?\n",
                         'va')
                     self.txt_conv.insert('end', "\n", 'g')
                     self.USER_INP = messagebox.askyesnocancel(
                         "Answer", "Do I identifying you correctly?")
                     if self.USER_INP == True:
                         self.txt_conv.insert('end', "YES\n")
                         self.txt_conv.insert('end', "\n", 'g')
                     elif self.USER_INP == False:
                         self.txt_conv.insert('end', "NO\n")
                         self.txt_conv.insert('end', "\n", 'g')
                     else:
                         self.txt_conv.insert('end', "CANCEL\n")
                         self.txt_conv.insert('end', "\n", 'g')
                     qu.put(self.USER_INP)
                     sleep(1)
                 elif "ADD1FAC2" in self.txt_qu:
                     self.USER_INP = simpledialog.askstring(
                         title="Name", prompt="Enter Your Name:")
                     sleep(0.5)
                     if self.USER_INP == None:
                         qu.put(self.USER_INP)
                         self.txt_conv.insert('end', "CANCEL\n")
                         self.txt_conv.insert('end', "\n", 'g')
                     elif self.USER_INP == "":
                         qu.put(self.USER_INP)
                     else:
                         self.txt_conv.insert('end',
                                              self.USER_INP + "\n")
                         self.txt_conv.insert('end', "\n", 'g')
                         qu.put(self.USER_INP.lower())
                     sleep(0.5)
                 else:
                     if "You said" in (self.txt_qu.split(':')[0]):
                         self.txt_conv.insert('end', self.txt_qu + "\n",
                                              'human')
                         self.txt_conv.insert('end', "\n", 'g')
                     else:
                         if self.txt_qu == "These names are already registered:":
                             self.lst_chk = 1
                         self.txt_conv.insert('end', self.txt_qu + "\n",
                                              'va')
                         self.txt_conv.insert('end', "\n", 'g')
         except:
             pass
         self.txt_conv.see(tkinter.END)
     else:
         self.btn_st.config(state=NORMAL)
         self.stat.chk_stp()
示例#58
0
    def __new(self, text_area, window, filename, status_bar):
        """
        Allows for creating a new file
        """

        # If the file is untitled and the text area has been modified, prompts the user user to save
        if filename.get() == "Untitled" and len(text_area.get("1.0",
                                                              "end-1c")) > 0:
            response = messagebox.askyesnocancel(
                "TextEditor",
                f"Do you want to save changes to {filename.get()}")

            # If the response is yes, brings up the save as menu and then clears the text area
            if response == 1:
                file = self.__save_as(text_area, window, filename)

                if file:
                    text_area.delete("1.0", "end")
                    filename.set("Untitled")
                    window.title(f"{filename.get()} - TextEditor")
                    text_area.edit_modified(False)
                    self.__file_saved.set(False)
                    status_bar.update_word_and_character_count(None, text_area)
                else:
                    pass
            # If the response is no, clears the text area without saving
            elif response == 0:
                text_area.delete("1.0", "end")
                filename.set("Untitled")
                window.title(f"{filename.get()} - TextEditor")
                text_area.edit_modified(False)
                self.__file_saved.set(False)
                status_bar.update_word_and_character_count(None, text_area)
            # If the response is cancel nothing happens
            else:
                pass
        # If the file is an existing file and the text area has been modified and the file was not saved,
        # prompts the user to save
        elif filename.get() != "Untitled" and text_area.edit_modified(
        ) and not self.__file_saved.get():
            response = messagebox.askyesnocancel(
                "TextEditor",
                f"Do you want to save changes to {filename.get()}")

            # If the response is yes, saves any modifications made before starting a new file
            if response == 1:
                self.__save(text_area, window, filename)

                text_area.delete("1.0", "end")
                filename.set("Untitled")
                window.title(f"{filename.get()} - TextEditor")
                text_area.edit_modified(False)
                self.__file_saved.set(False)
                status_bar.update_word_and_character_count(None, text_area)
            # If the response is no, starts a new file without saving
            elif response == 0:
                text_area.delete("1.0", "end")
                filename.set("Untitled")
                window.title(f"{filename.get()} - TextEditor")
                text_area.edit_modified(False)
                self.__file_saved.set(False)
                status_bar.update_word_and_character_count(None, text_area)
            # If the response is cancel, nothing happens
            else:
                pass
        # If the file is untitled or an existing file and the file has not been modified, starts a new file without
        # prompting to save
        else:
            text_area.delete("1.0", "end")
            filename.set("Untitled")
            window.title(f"{filename.get()} - TextEditor")
            status_bar.update_word_and_character_count(None, text_area)
示例#59
0
文件: t6.py 项目: DK-afei/python
def clicked6():
    messagebox.askyesnocancel('Message title', 'Message content')
示例#60
0
from tkinter import messagebox
re = messagebox.askquestion('Thanks', 'Message content')
print(re)
re = messagebox.askyesno('Thanks', 'Message content')
print(re)
re = messagebox.askyesnocancel('Data Save..', 'Do you want to save the data')
print(re)
if re == True:
    print("You choosed to save the file")
elif re == false:
    print("You choosed NO")
else:
    print("None")
re = messagebox.askokcancel('Message title', 'Message Content')
print(re)
re = messagebox.askretrycancel('Welcome', 'last Dialog,Thanks')
print(re)