def quitButton():
    if tkMessageBox.askokcancel("Verify Quit", "Really quit?"):
    if tkMessageBox.askokcancel("Verify Quit", "Really quit?"):
        root.destroy()

def helpButton(helpMessage):
    tkMessageBox.showinfo(title="Help!", message=helpMessage)
        root.destroy()
Ejemplo n.º 2
0
Archivo: 123.py Proyecto: filaPro/my
def die():
  tkMessageBox.showinfo("Window", "Information")
  tkMessageBox.showwarning("Window","Warning")
  tkMessageBox.showerror("Window","Error")
  tkMessageBox.askokcancel("Window", "noob?")
  tkMessageBox.askretrycancel("Window", "retry?")
  
  exit()
Ejemplo n.º 3
0
def obtenerSpinbox():
	#print(valor.get())
	tkMessageBox.showinfo("Mensaje","Tu seleccionaste " + valor.get())
	tkMessageBox.showwarning("Advertencia","Esto es un mensaje de Advertencia")
	tkMessageBox.askquestion("Pregunta 1", "Cualquier cosa")
	tkMessageBox.askokcancel("Pregunta 2", "Cualquier cosa")
	tkMessageBox.askyesno("Pregunta 3", "Cualquier cosa") #Responde en boleano a diferencia del question
	tkMessageBox.askretrycancel("Pregunta 1", "Cualquier cosa")
Ejemplo n.º 4
0
	def open_list_file(self):           #Opens a list file and gets each ID
		"""Opens a prompt that allows the user to select a text file containing a list of PDB IDs, which is then used to download the PDB files if the do not already exist."""
		if len(self.display_list)>0:
			answer = tkMessageBox.askokcancel(message = "Are you sure you want to load new PDB files? Current workspace will be lost.")
			if answer is False:
				return
			else: 
				del files_list[:]
				print "####   Started a new project    ####"
		self.display_list=[]
		list_filename_path = tkFileDialog.askopenfilename(	title="Select a list of PDB IDs.", filetypes=[("Text files","*.txt"),("Text files","*.tbl"),("Text files","*.tsv"),("Text files","*.csv"),("All files","*")] )
		if list_filename_path=="":
			return	
		
		self.display_list = []	
		just_path=os.path.dirname(list_filename_path)
		new_dir_name=os.path.join(just_path,os.path.basename(list_filename_path)+"_pdb_files")
		if not os.path.exists(new_dir_name):
			os.makedirs(os.path.join(just_path,os.path.basename(list_filename_path)+"_pdb_files"))
	
		#open list and parse PDB IDs
		handle = open(list_filename_path,"r")
		entire_file=''
		print >> sys.stderr, "Fetching PDB files..."
		for line in handle:
			entire_file+=line
		if "," in entire_file:
			pdb_id_list=[x.strip() for x in entire_file.split(',')]
		elif ";" in entire_file:
			pdb_id_list=[x.strip() for x in entire_file.split(';')]
		else:
			pdb_id_list=[x.strip() for x in entire_file.split()]
	
		for pdb_id in pdb_id_list:
			if pdb_id[:4].upper() not in self.display_list:
				self.display_list.append(pdb_id[:4].upper())
		self.display_list.sort(key=lambda x: x)
	
		#Add the identifiers to the list
		
		self.pdb_id_listbox.delete(0, Tkinter.END)
		index = 1
		answer = tkMessageBox.askokcancel(message = "Download %d PDB files? This will probably take between %0.2f and %0.2f minutes. This window will close when process has completed." % (len(self.display_list), len(self.display_list)*0.03,len(self.display_list)*0.07))
		if answer is False:
			return
		from pdb_getter import get_pdb_structure
		for record in self.display_list:
			self.pdb_id_listbox.insert(index, record.upper())
			files_list.append(get_pdb_structure(record,new_dir_name))
			index+=1
		handle.close()
		print "Loaded %d PDB files." % (len(self.display_list))
		self.current_SeqRecord = None
		print  >> sys.stderr, "Locations of PDB files:"
		 
		for fils in files_list:
			print  >> sys.stderr, fils
		print "You may now run an analysis with 'File' >> 'Run Analysis'."
Ejemplo n.º 5
0
 def add_ext(self):
     if self.subreddit is None:
         tkMessageBox.askokcancel("", "Please select a subreddit first.")
     else:
         s = tkSimpleDialog.askstring("Add an extension", "Enter the extension:")
         if not s:
             return
         s = s.upper().strip('.')
         self.subreddit.add_file_type(s)
Ejemplo n.º 6
0
 def add_subreddit(self):
     if self.grouping is None:
         tkMessageBox.askokcancel("", "Please select a directory first.")
     else:
         s = tkSimpleDialog.askstring("Add a Subreddit", "Enter the name of the subreddit: /r/")
         if not s:
             return
         if s.startswith('/r/'):
             s = s[len('/r/'):]
         self.grouping.add_subreddit(s)
Ejemplo n.º 7
0
def do_calculate():
   global FILEOPENED
   if FILEOPENED:
      if len(myBoard.referencePoints)==3:
         compute_matrix()
         new_gcode()
      else:
         mbox.askokcancel(message='Please select three holes for matrix computation')
   else:
      mbox.showwarning(message='Please open a file first')
Ejemplo n.º 8
0
 def updateDownloadProgressText(self, value):
     """
     Updates progress in downloadProgressbar
     Arguments: value: digit between 0-100
     """
     value = value + 1
     self.downloadProgressEntry.delete(0, tk.END)
     self.downloadProgressEntry.insert(0, chr(8) * (int(value)*57/100))
     if int(value) is 100:
         self.downloadProgressEntry.delete(0, tk.END)
         tkMessageBox.askokcancel(self.app.windowTitle, "Downloading completed!")
Ejemplo n.º 9
0
 def load(self, explicit=True):
     try:
         self.settings.load(explicit)
     except ValueError:
         reset = tkMessageBox.askokcancel("", "Cannot read your config file. Reset?")
         if reset:
             self.settings.reset()
     except NameError:
         reset = tkMessageBox.askokcancel("", "No config file found. Create a new one?")
         if reset:
             self.settings.reset()
     self.state = GUIState()
Ejemplo n.º 10
0
    def saveContact(self,saveOrEdit):

        first = self.firstEntry.get()
        last = self.lastEntry.get()
        add1 = self.add1Entry.get()
        add2 = self.add2Entry.get()
        city = self.cityEntry.get()
        state = self.stateEntry.get()
        zip = self.zipEntry.get()
        phone = self.phoneEntry.get()

        # VALIDATION on entries
        valid, errorMsgs = VALIDATION.validateSaveEntry(first=first, last=last, add1=add1, add2=add2, city=city,
                                                        state=state, zip=zip, phone=phone)
        zipVal = VALIDATION.validateZip(zip)

        #adds new contact to book
        if saveOrEdit == 'save':
            if valid is False:
                tkMessageBox.showwarning("Warning","Please provide a first or last name and one other field")
                return
            elif zipVal is False:
                if tkMessageBox.askokcancel("Warning","Zip code does not match postal standards! Do you want to continue anyway?"):
                    self.book.addContact(first, last, add1, add2, city, state, zip, phone)
                    print "Saved Contact"
                else:
                    return
            else:
                self.book.addContact(first, last, add1, add2, city, state, zip, phone)
                print "Saved Contact"

        #edits existing contact
        elif saveOrEdit == 'edit':
            if self.editID == '':
                tkMessageBox.showwarning("Select Contact","Please select a contact to edit or create a new contact!")
                return
            else:
                if valid is False:
                    tkMessageBox.showwarning("Warning","Please provide a first or last name and one other field")
                    return
                elif zipVal is False:
                     if tkMessageBox.askokcancel("Warning","Zip code does not match postal standards! Do you want to continue anyway?"):
                        self.book.edit(self.editID,first,last,add1,add2,city,state,zip,phone)
                        print "Saved Contact"
                     else:
                        return
                else:
                    self.book.edit(self.editID,first,last,add1,add2,city,state,zip,phone)
                    print "Contact Updated"

        self.refresh(self.book.viewContacts())
        self.clearBoxes()
        self.editID = ''
Ejemplo n.º 11
0
 def del_subreddit(self):
     if self.subreddit:
         current_items = list(self.subreddit_listbox.get(0, Tkinter.END))
         current_idx = current_items.index(self.subreddit.name)
         del self.grouping[self.subreddit.name]
         del current_items[current_idx]
         if current_items:
             new_idx = max(0, min(len(current_items)-1, current_idx))
             self.state.subreddit = current_items[new_idx]
         else:
             self.state.subreddit = None
     else:
         tkMessageBox.askokcancel("", "Please select a subreddit to remove.")
Ejemplo n.º 12
0
 def add_grouping(self, dirname):
     existing_dirnames = set([d.name for d in self.groupings])
     if dirname in existing_dirnames:
         tkMessageBox.askokcancel("", "You have already entered that directory.")
         return None
     existing_shortnames = set([d.shortname for d in self.groupings])
     parts = dirname.split(os.path.sep)
     shortname = None
     for i in xrange(len(parts)):
         shortname = os.path.sep.join(parts[-1 - i :])
         if shortname not in existing_shortnames:
             break
     self.data["groupings"][dirname] = Grouping({"directory_name": dirname, "shortname": shortname})
Ejemplo n.º 13
0
    def _popup(self, title, text, style=None):
        """
        create a popup!

        :param title: title of the popup-window
        :param text: the text in the popup-window
        :param style: the icon-style of the popup. default is 'warning'
        """
        if style:
            if style == "error":
                return tkMessageBox.showerror(title, text)
            return tkMessageBox.askokcancel(title, text, icon=style)
        return tkMessageBox.askokcancel(title, text)
Ejemplo n.º 14
0
 def del_ext(self):
     if self.filetype:
         current_items = list(self.file_types_listbox.get(0, Tkinter.END))
         current_idx = current_items.index(self.filetype)
         self.subreddit.rm_filetype(self.filetype)
         del current_items[current_idx]
         if current_items:
             new_idx = max(0, min(len(current_items)-1, current_idx))
             self.filetype = current_items[new_idx]
         else:
             self.filetype = None
     else:
         tkMessageBox.askokcancel("", "Please select an extension to remove.")
Ejemplo n.º 15
0
    def open_root_notice(self):

        load_root = False

        if self.root_notice is not None:
            message = "You already have a root notice loaded. If you load " + \
            "another root notice, your current set of notices will be replaced. " + \
            "Are you sure you want to do this?"
            result = tkMessageBox.askokcancel('Replace root?', message)
            if result:
                load_root = True
        else:
            load_root = True

        if load_root:
            self.notices = []
            self.root_notice = None
            self.current_notice = None
            self.trees = {}
            for child in self.element_tree.get_children():
                self.element_tree.delete(child)

            notice_file = tkFileDialog.askopenfilename()
            if notice_file:
                notice = Notice(notice_file)
                self.current_notice = notice.document_number
                self.notices.append(notice.document_number)
                self.root_notice = notice
                self.root_notice_file = notice_file
                self.add_element_to_tree(notice.tree, None)
                self.update_notices_list()
                self.trees[notice.document_number] = self.root_notice
                self.populate_definitions()

                cfr_section = notice.tree.find('{eregs}preamble').find('.//{eregs}section').text
                all_notice_files = find_all(cfr_section, is_notice=True)

                message = "There are {} additional notices associated with this root version. ".format(len(all_notice_files)) + \
                    "Would you like to load all of them? This can take some time if the notices " + \
                    "are very large."
                result = tkMessageBox.askokcancel('Load all notices?', message)
                if result:
                    self.notices_files = all_notice_files
                    all_notices = [Notice(notice_file) for notice_file in all_notice_files]
                    all_notices.sort(key=lambda n: n.effective_date)
                    for notice in all_notices:
                        self.notices.append(notice.document_number)
                        self.trees[notice.document_number] = notice

                    self.update_notices_list()
                    self.populate_definitions()
def radius_time(p_m, p_g, k, L):
    root.geometry('280x385')
    global struct
    height = L
    struct = []
    next_ = True
    go = True
    Lb1 = Listbox(root, height=10, width=50)
    for i in range(k):
        r = random.uniform(2, 3)
        r/=2
        r*=(height/0.5)
        print("Radius:", r)
        if(r<=2/2):
            t = random.uniform(7, 7.5)
        elif(r<=2.5/2):
            t = random.uniform(6, 7)
        elif(r<3/2):
            t = random.uniform(4.5, 6)
        elif(r>=3/2):
            t = random.uniform(3.75, 4.25)
        t*=(height/0.5)
        print("Time:", t)
        print()
        string = ""
        string = str(i+1) +"   Time:"+str(t)+ "  Radius:"+str( r)
        Lb1.insert(i+1, string)
        Lb1.pack()
        Lb1.place(x = 5, y = 235, height = 120, width = 265)
        minus = p_m-p_g
        q = 2*minus*r*r*(10**-6)*9.8*t/9/L
        if next_:
            if go :
                s = tkMessageBox.askokcancel(title = "Quesions", message = "Do work GIF?")
            if not s:
                next_ = False
                go = False
            else:
                gift()
                next_op = tkMessageBox.askokcancel(title = "Quesions", message = "Do visible next?")
                if not next_op:
                    s = False
                go = False
        struct.append([t, r, q])
    #Lb1.pack()
    #Lb1.place(x = 5, y = 235, height = 120, width = 265)
    str_dn = "dn = "+str(dn())
    label_dn = Label( root, text=str_dn)
    label_dn.pack()
    label_dn.place(x = 5, y = 360, height = 20, width = 265)
    print_main()
Ejemplo n.º 17
0
 def del_directory(self):
     if self.grouping:
         current_items = list(self.grouping_listbox.get(0, Tkinter.END))
         current_idx = current_items.index(self.grouping.shortname)
         del self.settings[self.state.grouping]
         del current_items[current_idx]
         if current_items:
             new_idx = max(0, min(len(current_items)-1, current_idx))
             self.state.grouping = current_items[new_idx]
         else:
             self.state.grouping = None
         
     else:
         tkMessageBox.askokcancel("", "Please select a directory to remove.")
Ejemplo n.º 18
0
 def _scrapes(self, include_sub, include_dir, expose=True, alert_when_done=True):
     try:
         count = 0
         for x in scrape.scrape(self.settings, include_sub=include_sub, include_dir=include_dir):
             if isinstance(x, int):
                 count += x
                 continue
             if expose:
                 reveal(x)
     except requests.ConnectionError:
         tkMessageBox.askokcancel("Connection Error",
                                  "Could not connect to Reddit. Check your internet settings, "
                                  "and make sure Reddit isn't down.")
     else:
         tkMessageBox.askokcancel("", "Scrape Complete! %d files downloaded." % count)
Ejemplo n.º 19
0
 def newAsDlg(self):
   if tkMessageBox.askokcancel('Quit','Want a New Image'):  
     k='me.jpg'
     im = Image.open(k)
     im=im.resize((self.size2[0],self.size2[1]),Image.ANTIALIAS)
     self.im=im
     self.tkimage.paste(im)
Ejemplo n.º 20
0
 def handler(self):
     """Handler on explicitly closing the GUI window."""
     self.pauseMovie()
     if tkMessageBox.askokcancel("Quit?", "Are you sure you want to quit?"):
         self.exitClient()
     else: # When the user presses cancel, resume playing.
         self.playMovie()
Ejemplo n.º 21
0
 def cmdSave( self):
     filename = self.filename.get()
     if path.isfile( filename): 
         if not tkMessageBox.askokcancel('Save', 'File %s already exist!\n Overwrite?'% filename):            
             return            
     base, ext = path.splitext( filename)
     if ext == '': ext = '.c'
     if ext != '.c':
         tkMessageBox.showinfo( 'Error', 'Only .c files can be generated!', icon='warning')
         return
     filename = base + ext
     try:
         with open( filename, "wt") as f:
             f.write( '/*\n')
             f.write( ' *  OLED display image \n')
             f.write( ' *  %s x %s \n' % ( self.wx, self.wy))
             f.write( ' */ \n')
             f.write( '#include "mcc_generated_files/mcc.h"\n\n')
             f.write( 'const uint8_t %s[]={ \n' % base)
             for x in xrange( 0, self.wx * self.wy/8, 16):
                 for k in xrange( 16):
                     f.write( '0x%02x, '% self.array[ x + k])
                 f.write( '\n')
             f.write( '};\n')
             self.modified = False
     except IOError: print 'Cannot write file:', filename
Ejemplo n.º 22
0
 def cmdLoad( self):
     if self.modified:
         if not tkMessageBox.askokcancel( 'Load', 'Unsaved changes will be lost,\n are you sure?', icon='warning'):            
             return
     i = 0
     last = (self.wx * self.wy/8) 
     try:
         with open( self.filename.get()) as f:
             ch = f.read( 1)
             while ch != '{': ch = f.read(1)
             while i < last:
                 ch = f.read(1)
                 while ch < '0' : ch = f.read( 1)
                 if ch != '0': break  
                 s = f.read( 3)
                 try: self.array[i] = int( '0'+s, base=16)
                 except ValueError: break
                 i += 1 
             else: 
                 print 'File loaded successfully'
                 self.drawPicture()
                 self.modified = False
                 return 
             print 'File format could not be recognized!'
     except IOError: print 'File %s not found' % self.filename.get()
Ejemplo n.º 23
0
    def clear_list(self):

        if tkMessageBox.askokcancel("Clear Playlist","Clear Playlist"):
                    self.track_titles_display.delete(0,self.track_titles_display.size())
                    self.playlist.clear()
                    self.blank_selected_track()
                    self.display_time.set("")
Ejemplo n.º 24
0
 def remove_show(self):
     if  self.current_showlist<>None and self.current_showlist.length()>0 and self.current_showlist.show_is_selected():
         if tkMessageBox.askokcancel("Delete Show","Delete Show"):
             index= self.current_showlist.selected_show_index()
             self.current_showlist.remove(index)
             self.save_showlist(self.pp_profile_dir)
             self.refresh_shows_display()
Ejemplo n.º 25
0
 def __confirmationCallBack(self):
     if tkMessageBox.askokcancel(":)", "Do you really wish to Continue?"):
         print "pop-up confirmed, here we go..."
         self.__disableConfirmationButton()
         self.__gui_not_cb(CMD.RESUME)
     else:
         print "pop-up canceled, do nothing"
Ejemplo n.º 26
0
 def remove_track(self):
     if  self.current_medialist<>None and self.current_medialist.length()>0 and self.current_medialist.track_is_selected():
         if tkMessageBox.askokcancel("Delete Track","Delete Track"):
             index= self.current_medialist.selected_track_index()
             self.current_medialist.remove(index)
             self.save_medialist()
             self.refresh_tracks_display()
Ejemplo n.º 27
0
 def _clear_all(self):
     '''erases all text'''
     
     isok = askokcancel('Clear All', 'Erase all text?', parent=self,
                        default='ok')
     if isok:
         self.delete('1.0', 'end')
Ejemplo n.º 28
0
    def press_eat(master, eat):
        """Срабатывает при нажатии на кнопку выбора собственно блюда.
        Добавляет блюдо в список, или возвращается к выбору категории,
        если нажата кнопка с eat=''."""

        if eat:
            count = panel()
            if count:
                rest = queries.items_in_storage(eat)
                if rest and (count > int(rest)):
                    if tkMessageBox.askokcancel('Внимание!',
                       'Вы хотите списать больше, чем есть на складе!\n\n'+
                       'В настоящий момент на складе %s единиц\n' % rest +
                       'А вы хотите списать %d!\n\n' % count +
                       'Желаете списать все со склада, что там осталось?\n'):
                        if int(rest):
                            lostList.add_eat(eat, int(rest))
                        else:
                            tkMessageBox.showwarning('ОДнако!',
                                                  'А там ничего не осталось...')
                else:
                    lostList.add_eat(eat, count)
        else:
            parent_name = master.winfo_parent()
            parent = master._nametowidget(parent_name)
            master.destroy()
            lostBottomFrame = Canvas(MasterFrame, highlightthickness=0)

            show_lost.master = lostBottomFrame

            if USE_BACKGROUND:
                lostBottomFrame.create_image(0,0, anchor='nw', image=data.photo)
            lostBottomFrame.pack(side=LEFT, fill=BOTH, expand=YES)
            show_lost_cathegory(lostBottomFrame)
Ejemplo n.º 29
0
 def remove_medialist(self):
     if self.current_medialist<>None:
         if tkMessageBox.askokcancel("Delete Medialist","Delete Medialist"):
             os.remove(self.pp_profile_dir+ os.sep + self.medialists[self.current_medialists_index])
             self.open_medialists(self.pp_profile_dir)
             self.refresh_medialists_display()
             self.refresh_tracks_display()
Ejemplo n.º 30
0
    def createRunset(self):
        """
        Call the controller with the correct arguments and then lockdown
        """
        import os

        path = os.path.join(self.str_folder.get(), self.str_name.get())
        if os.path.isdir(path):
            import tkMessageBox

            if tkMessageBox.askokcancel("Already exists", "A run with this name is already saved here. Overwrite?"):
                import shutil

                shutil.rmtree(path)
                tkMessageBox.Message(type="ok", message=("Folder " + path + " was removed")).show()
            else:
                return

        self.controller.createRunset(
            self.str_folder.get(),
            self.str_name.get(),
            float(self.str_m.get()),
            float(self.str_l.get()),
            float(self.str_omega.get()),
            float(self.str_A.get()),
            float(self.str_viscosity.get()),
            float(self.str_phi0.get()),
            float(self.str_v0.get()),
            float(self.str_tend.get()),
        )
        self.lockdown()
Ejemplo n.º 31
0
 def del_inven(self):
     """
     Deletes all entries in database.
     """
     # popup window
     ans = askokcancel(
         "Verify Delete Action",
         "Are you 'REALLY' sure you want to clear your 'WHOLE' inventory ?",
         parent=self.master)
     if ans:
         sql.session.delete_all_stock()
         self.get_inven()
         showinfo(title="Inventory cleared",
                  message="Your inventory database has been deleted.",
                  parent=self.master)
Ejemplo n.º 32
0
def handler():
    result = tkMessageBox.askokcancel(
        "Exit Flagship?",
        "Do you really want to use the escape pod?",
        icon='warning')
    print result
    if result == True:
        log.write("Left chat at " + time.strftime("%Y-%m-%d %H:%M:%S") + '\n')
        log.close()
        QUIT.set()
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.sendto("Terminate", ("127.0.0.1", UDP_PORT))
        sock.close()
        base.quit()
        sys.exit()
Ejemplo n.º 33
0
 def removeCurrentTask(self):
     if self.currentTask:
         name = self.currentTask.name
         ok = 1
         if ((name == 'dataLoop') or (name == 'resetPrevTransform')
                 or (name == 'tkLoop') or (name == 'eventManager')
                 or (name == 'igLoop')):
             from tkMessageBox import askokcancel
             ok = askokcancel('TaskManagerControls',
                              'Remove: %s?' % name,
                              parent=self.parent,
                              default='cancel')
         if ok:
             self.taskMgr.remove(self.currentTask)
             self.updateTaskListBox()
Ejemplo n.º 34
0
 def reset(self):
     rest = tkMessageBox.askokcancel("ADMIN RESET",
                                     "OK=COMPLETE  CANCEL=CHAIN RESET")
     if (rest == True):
         os.system('iptables -F')
         os.system('iptables -X')
         os.system('iptables -t nat -F')
         os.system('iptables -t nat -X')
     elif (rest == False):
         os.system('iptables -F')
         os.system('iptables -X')
     else:
         print 'Something is going wrong contact ADMINISTRATOR MANOHAR SINGH'
     print 'NOW ALL THE PROTOCOL IS FORWARDED THROUGH MANOHAR SINGH'
     print 'NOW YOU ARE FREE OF USE'
Ejemplo n.º 35
0
 def exit(self, event=None):
     self.win.destroy()
     # если были сделаны изменения, просим перезапустить программу
     if self.reload:
         s = box.askokcancel(
             title='Настройки',
             message=
             'После изменения настроек,\nтребуется перезапуск программы.\nПерезапустить?'
         )
         if s:
             self.app.app.root.destroy()
             try:
                 subprocess.Popen(sys.argv[0])
             except WindowsError, x:
                 subprocess.Popen('pythonw ' + sys.argv[0])
Ejemplo n.º 36
0
def on_closing():
    """Asking the closure of the coverage window. If "Quit" the files in the list "temp_files" are deleted.
          ***Improving with tempfile module***"""

    if tkMessageBox.askokcancel("Quit", "Do you want to quit?"):
        try:
            temp_files = [
                "GWsky_entries", "GWsky_query_items", "GWsky_fov.vot",
                "GWsky_config", "GWsky_coords", "obs_airmass_"
            ]
            for temp_file in temp_files:
                os.remove(temp_file)
        except OSError:
            pass
        mainWin.destroy()
Ejemplo n.º 37
0
 def Delete(self):
     index = self.mlb1.Select_index
     if index == None or index > self.mlb1.size():
         return showinfo('Select Error',
                         'Noting Is Selected',
                         parent=self.master)
     tup = self.mlb1.get(index)
     s = askokcancel('Confirm',
                     'Are You Sure You Want To Delete %s ?' % tup[0],
                     parent=self.master)
     if s == True:
         self.db.deletecategory(tup[0])
     return self.Refresh(), showinfo('Successful',
                                     'Successfully Deleted',
                                     parent=self.master)
Ejemplo n.º 38
0
 def create_dir(self):
     self.myset = SettingsGroup(rootp + "user_settings.ini")
     self.desktop = "C:\\Users\\Administrator\\Desktop\\" or self.myset.main.desktop
     self.py_path = os.path.dirname(
         sys.executable) + os.sep or self.myset.main.py_path
     for i, j, k in [(self.py_path, 'python.exe', 'py_path'),
                     (self.desktop, '桌面', 'desktop')]:
         if not os.path.exists(i) and not getattr(self.myset.main, k, 0):
             res = askokcancel(i, "无法找到{}目录,需手动设置".format(j))
             val = askdirectory()
             if not (res or val): self.close()
             if k == 'desktop':
                 self.myset.main.desktop = self.desktop = val
             else:
                 self.myset.main.py_path = self.py_path = val
             self.myset.save()
Ejemplo n.º 39
0
 def removeMatchingTasks(self):
     name = self.taskListBox.getcurselection()[0]
     ok = 1
     if ((name == 'dataLoop') or
         (name == 'resetPrevTransform') or
         (name == 'tkLoop') or
         (name == 'eventManager') or
         (name == 'igLoop')):
         from tkMessageBox import askokcancel
         ok = askokcancel('TaskManagerControls',
                          'Remove tasks named: %s?' % name,
                          parent = self.parent,
                          default = 'cancel')
     if ok:
         self.taskMgr.remove(name)
         self.updateTaskListBox()
Ejemplo n.º 40
0
 def onkey_tree_delete(self, evt):
     # keep treeview items intact when downloading, because jobs are in queue.
     if self._running:
         return
     #
     selected = self._segments.selection()
     num = len(selected)
     if num == 0:
         return
     if num == 1:
         msg = 'Are you sure to delete\n\n%s\n\n?' % selected[0]
     else:
         msg = 'Are you sure to delete %d jobs?' % num
     if not tkMessageBox.askokcancel(Main.WND_TITLE, msg):
         return
     self._segments.delete(*selected)
Ejemplo n.º 41
0
    def show_ok_cancel_dialog(master,
                              dialog_title,
                              dialog_message,
                              default_button=None):
        '''
        Show an info message dialog.
        "master": The tk instance that owns the dialog.
        "dialog_title": Title of the dialog.
        "dialog_message": Message to display in dialog.
        "default_button": Default button to be selected when dialog appears.
        '''

        return tkMessageBox.askokcancel(dialog_title,
                                        dialog_message,
                                        parent=master,
                                        default=default_button)
Ejemplo n.º 42
0
 def addnew(self):
     cursor = self.db.cursor()
     newentry = self.tx.get()
     if askokcancel("Confirm",
                    "Do you want to insert - {0}".format(newentry),
                    parent=self.master):
         cursor.execute("select * from " + self.table + " where " +
                        self.field + "='" + newentry + "'")
         if cursor.rowcount == 0:
             cursor.execute("insert into " + self.table + "(" + self.field +
                            ") values('" + self.tx.get() + "');")
             self.db.commit()
             showinfo("Done", newentry + " inserted!", parent=self.master)
     self.refreshlist()
     self.tx.set("")
     self.en.focus()
Ejemplo n.º 43
0
 def ctrldelete(self, event):
     title_sample = self.get_text().split('\n', 1)[0]
     if len(title_sample) > 20:
         title_sample = title_sample[:20] + '...'
     # delete the card
     if tkMessageBox.askokcancel(
             "Delete?",
             "Delete card \"%s\" and all its edges?" % title_sample):
         for handle in self.edge_handles:
             self.canvas.delete(handle)
         self.deletion_slot.signal()
         self.viewport.remove_card(self)
         self.card.delete()
         self.window.destroy()
         self.gpfile.commit()
     return "break"
Ejemplo n.º 44
0
 def routeon(self):
     route = tkMessageBox.askokcancel(
         "ROUTE TRAFFIC",
         "Would you like to route all traffic to LOCATION:%s and PORT:%s" %
         (self.inputloca.get(), self.inputpor.get()))
     if (route == True):
         os.system(
             "iptables -t nat -I PREROUTING 1 -p tcp -j DNAT --to-destination %s:%s"
             % (self.inputloca.get(), self.inputpor.get()))
         os.system("iptables -t nat -A POSTROUTING -j MASQUERADE")
         print 'THE SYSTEM HAS SET RULE TO FIREWALL SUCCESSFULLY TO ROUTE TRAFFIC TO %s:%s' % (
             self.inputloca.get(), self.inputpor.get())
     elif (route == False):
         print 'You choose CANCEL please try again Sorry ! :)'
     else:
         print 'CONTACT TO ADMINISTRATOR MANOHAR SINGH'
Ejemplo n.º 45
0
 def close(self):
     "Extend EditorWindow.close()"
     if self.executing:
         response = tkMessageBox.askokcancel(
             "Kill?",
             "The program is still running!\n Do you want to kill it?",
             default="ok",
             parent=self.text)
         if response == False:
             return "cancel"
     if self.reading:
         self.top.quit()
     self.canceled = True
     self.closing = True
     # Wait for poll_subprocess() rescheduling to stop
     self.text.after(2 * self.pollinterval, self.close2)
Ejemplo n.º 46
0
def install_examples():  # pragma: no cover
    """
    Pops up windows to allow the user to choose a directory for installation
    of sfc_models examples.

    Uses tkinter, which is installed in base Python (modern versions).
    :return:
    """
    if not mbox.askokcancel(title='sfc_models Example Installation',
                            message=validate_str):
        return
    target = fdog.askdirectory(
        title='Choose directory to for sfc_models examples installation')
    if target == () or target == '':
        return
    install_example_scripts.install(target)
Ejemplo n.º 47
0
def send_str(e=0): #обработка строкового ответа
    global rsp_text,responses_str
    global result,i

    if rsp_text.get()=='':
        if tkMessageBox.askokcancel("Тест","Вы ввели пустую строку, продолжить?"):
            pass
        else:
            clear_frame()
            show_form_str()
            return
    if rsp_text.get().lower()==responses_str[i].decode('utf8'):
        result.update({i:True})
    else:
        result.update({i:False})
    select_form()
Ejemplo n.º 48
0
 def file_window(self):
     file_name = askopenfilename(parent=self.root, title='选择文件', \
                                 filetypes=[('FEN Records', '*.fen'), ('Text Files', '*.txt'), ('All Files', '*.*')],
                                 initialdir='Resourses/', \
                                 initialfile='example.fen')
     # self.file = open(file_name, 'r')
     # self.play()
     # '''
     try:
         self.file = open(file_name, 'r')
         self.play()
     except IOError:
         if askokcancel('错误的路径', '是否重新选择?'):
             self.file_window()
         else:
             self.root.destroy()
Ejemplo n.º 49
0
    def submit_click(self, value=""):
        if self.emailEntry.get().strip()[-13:] != "@lakeheadu.ca":
            tkMessageBox.showerror(
                "Email format error",
                "Please make sure to use a valid @lakeheadu.ca email address")
            return

        self.save_data()

        selection = self.timeOptionList.curselection()
        if selection == ():
            return
        if len(selection) > 4 and self.overrideVal.get() != 1:
            tkMessageBox.showerror("2hr Limit",
                                   "Sorry, you can only book 2hrs per day")
            return
        if self.confirmVal.get() == 1:
            outputTimes = ""
            lineBreak = '-' * (len(self.chosenDate.get()) + 2)
            for index in selection:
                pIndex = self.roomTimeList[self.roomIndex][int(index)]
                outputTimes += self.availTimes[pIndex] + "\n"
            if not tkMessageBox.askokcancel(
                    "Please confirm the following times",
                    self.chosenDate.get() + "\n" + lineBreak + "\n" +
                    self.availRooms[self.roomIndex] + "\n" + outputTimes):
                return

        # if output, get times
        self.outputTimeArray = []
        for index in selection:
            pIndex = self.roomTimeList[self.roomIndex][int(index)]
            self.outputTimeArray.append(self.availTimes[pIndex])

        # book rooms
        self.book_times()

        # check if any rooms were unavailable
        if len(self.outputTimeArray) > 0:
            outputText = "The following times were unavailable to book\n----------------------------------------\n"
            for item in self.outputTimeArray:
                outputText += item + "\n"
            tkMessageBox.showerror("Unavailable", outputText)

        # clear booked room time slots,
        self.roomTimeList[self.roomIndex] = [0]
        self.room_click()
Ejemplo n.º 50
0
def allocate(infile,
             outfile,
             do_central=False,
             do_object=True,
             do_sky=True,
             do_guide=True,
             zero_rotations=False,
             blank_rotations=False):
    """Main function for interactive allocations.
    Typically called from command line."""
    if not tkinter_available:
        print("Tkinter isn't installed on this computer!")
        print("You can't run the allocation script here!")
        return
    # Set up Tkinter
    root = Tkinter.Tk()
    # Withdraw the Tk window while potential error messages are resolved
    root.withdraw()
    try:
        csvfile = CSV(infile)
    except IOError:
        tkMessageBox.showerror('Error', 'Input file not found!')
        return
    if os.path.isfile(outfile):
        cont = tkMessageBox.askokcancel(
            'Warning', 'Output file already exists. Overwrite?')
        if not cont:
            return
    # Bring the Tk window back again
    root.deiconify()
    # Run the interactive allocator
    csvfile.update_allocation_interactive(do_central=do_central,
                                          do_object=do_object,
                                          do_sky=do_sky,
                                          do_guide=do_guide,
                                          root=root)
    # Done with the interactive part, so destroy the Tkinter interface
    root.destroy()
    # Final tweak to CSV file contents, set the rotations correctly
    if zero_rotations:
        csvfile.zero_rotations()
    elif not blank_rotations:
        csvfile.flip_hexabundles()
    # Make the new CSV file, unless it was cancelled
    if csvfile.ok:
        csvfile.print_contents(outfile)
    return
Ejemplo n.º 51
0
    def backup_rom(self):
        try:
            rom_list = sd_card.rom_list
        except:
            raise Exception("Please open a disk before attempting to dump a rom.")

        index = view.tree_rom_table.focus()
        if index:
            item = view.tree_rom_table.item(index)

            tree_slot = item['values'][0]

            delete_list = []
            delete_list.append(rom_list[tree_slot])

            rom_info = controller.get_rom_info(delete_list)[0]

            title = rom_info[5]
            rom_code = rom_info[4]
            index = rom_info[0] # Instead of relying on the treeview and sd_card to be identical I just pull all of the info out of the sd_card
            slot = rom_list[index][0]
            rom_size = rom_list[index][2]

        else:
            raise Exception("Please select a rom to dump.")

        destination_folder = tkFileDialog.askdirectory( initialdir = os.path.expanduser('~/Desktop'), mustexist = True)

        message = "Dump rom %s, %s to %s?" % (slot, title, destination_folder)

        if destination_folder:
            confirm = tkMessageBox.askokcancel("Confirm Rom Dump", message)
        else:
            return

        if confirm == True:
            destination_file = destination_folder + "/" + rom_code + ".3ds"

            message = "Dumping %s to %s" % (rom_code, destination_folder)
            task_text = "%s backup" % title

            progress_bar = progress_bar_window("Dumping Rom", message, mode = "determinate", maximum = rom_size, task = task_text)
            root.wait_visibility(progress_bar.window)

            sd_card.dump_rom( slot, destination_file, progress=progress_bar)
        else:
            return
 def saveData(self):
     #save to csv
     self.textboxvar.set("Saving data?")
     try:
       self.loggedData
     except AttributeError:
         self.textboxvar.set("No recorded data.")
     else:
         if messagebox.askokcancel("Save", "This will overwrite any data.csv file in the directory. Save anyways?"):
             l = self.loggedData
             with open('data.csv', 'wb'):
                 pass
             with open('data.csv', 'a') as f:
                wtr = csv.writer(f, delimiter= ',')
                wtr.writerows( l )
             self.parent.after(2)
             self.textboxvar.set("Data saved!")
Ejemplo n.º 53
0
    def format_confirm(self):
        sd = self.disk_choice.get()
        sd = tuple([x for x in sd[1:-1].split("'")]) #super ugly way to make string into tuple
        sd = sd[1]

        message = "Formatting %s will permanently erase all data and partitions on %s. \nPlease confirm that you have chosen the correct disk to format. \n \nFormatting can take several minutes to complete, please be patient." % (sd, sd)

        self.window.grab_release()
        self.window.wm_attributes("-topmost", 0)
        confirm = tkMessageBox.askokcancel("Confirm Format", message)
        self.window.wm_attributes("-topmost", 1)
        self.window.grab_set()

        if confirm == True:
            self.format_disk(sd)
        else:
            return
Ejemplo n.º 54
0
    def detect_bemoss(self):
        ui_path = self.project_path+'/Web_Server'
        cassandra_path = self.project_path + '/cassandra/bin'
        env_path = self.project_path + '/env/bin'
        bemoss_is_installed = os.path.isdir(ui_path) and os.path.isdir(cassandra_path) and os.path.isdir(env_path)

        if bemoss_is_installed is False:
            tmp = tkMessageBox.askokcancel(title='Please install BEMOSS at first',
                                           message='You computer does not have BEMOSS installed, do you want to install BEMOSS right now?',
                                           parent=root)
            if tmp is True:
                self.install_bemoss()
                return
            else:
                return False
        else:
            return True
Ejemplo n.º 55
0
 def Delete(self):
     index = self.mlb1.Select_index
     if index == None or index > self.mlb1.size():
         return showinfo('Select Error',
                         'Noting Is Selected',
                         parent=self.master)
     tup = self.mlb1.get(index)
     s = askokcancel('Confirm',
                     'Are You Sure You Want To Delete Invoice Number %s ?' %
                     tup[0],
                     parent=self.master)
     if s == True:
         self.db.deleteinvoice(tup[0])
     self.Refresh()
     return showinfo("Info",
                     "Invoice delete successfully",
                     parent=self.master)
Ejemplo n.º 56
0
    def select_cell(self, state):

        if state == True:
            self.cells[self.cell_ids[self.current_index]].selection_state = 1

        else:
            self.cells[self.cell_ids[self.current_index]].selection_state = 0

        if self.current_index < len(self.cell_ids) - 1:
            self.current_index += 1
            self.show_image()

        else:
            if tkMessageBox.askokcancel("Quit", "Last cell, generate report?"):
                self.main_window.destroy()
            else:
                self.show_image()
Ejemplo n.º 57
0
    def execAction(self):
        if not self.action is None:
            action = getattr(self.controller, self.action)
            location = self.current_dir

            selection = self.getSelection()
            if len(selection) > 0:
                location = selection[0]
            if len(self.items_selected) > 0:
                if tkMessageBox.askokcancel(
                        self.action.capitalize(),
                        "Are you sure? This action can be permanent"):
                    if action(self.items_selected, location):
                        self.action = None
                    else:
                        tkMessageBox.showerror("Ops", "An error occurred :(")
                    self.reloadMainList()
Ejemplo n.º 58
0
 def deleteExpEvent(self):
     
     if self.selectedExpIndex == -1:
         return
     
     session = dbConn.session()
     
     code = self.grdExps.get(self.selectedExpIndex)[0]
     
     if (tkMessageBox.askokcancel("Confirm experiment deletion", "Do you really want to remove experiment " + code)):
         try:
             deleteExperimentByCode(session, code)
         except Exception as e:
             tkMessageBox.showerror("Error", e)
         
     session.close()
     self.updateExpListbox()
Ejemplo n.º 59
0
    def Quitter(self):

        reponse = tkMessageBox.askokcancel(
            _(u"Quitter"),
            _(u"Voulez-vous quitter ? Les paramètres modifiés seront perdus."))
        if reponse == 1:
            reponse = True
        elif reponse == 0:
            reponse = False
        if not reponse:
            return

        self.nouveau_para = None
        #    self.bulle['state'] = 'none'
        #    self.bulle.destroy()
        self.fenetre2.quit()
        self.fenetre2.destroy()
Ejemplo n.º 60
0
def ok(args, arg_name, **kwargs):
    """
    Prompts the user for confirmation.

    :param args: arguments supplied by the user
    :type  args: namespace
    :param arg_name: name of the argument to prompt for
    :type  arg_name: basestring
    :return: confirmation given by the user
    :rtype: bool
    """
    arg = getattr(args, arg_name)
    if arg is None:
        tk.Tk().withdraw()
        arg = tkMessageBox.askokcancel(**kwargs)

    return arg