Пример #1
0
 def destroy(self):
     registry.delete(self)
     Toplevel.destroy(self)
     # If this is Idle's last window then quit the mainloop
     # (Needed for clean exit on Windows 98)
     if not registry.dict:
         self.quit()
class MailListWindow:
    def __init__(self, title, after_close):
        self.win = Toplevel()
        self.win.title(title)
        self.win.geometry('400x200')
        self.win.wm_attributes('-toolwindow', True)
        self.win.protocol("WM_DELETE_WINDOW", after_close)
        
        inner_frame = tk.Frame(self.win)#inner_frame = tk.Frame(canvas)
        inner_frame.pack(side='left', fill='both', expand = 1)
        scrollbar = tk.Scrollbar(self.win,orient="vertical",command=self.scrolly)
        scrollbar.pack(side='right', fill='y')
        
        self.btn_count = 0
        self.btns = []
        self.texts = []
        self.callbacks = []
        self.frame = inner_frame
        self.scrollbar = scrollbar
        self.btn_per_page = 4
        self.first_btn = 0
        self.scrolly('', '0.0')
        
    def scrolly(self, cmd, pos, what=''):
        if self.btn_per_page <= self.btn_count:
            bar_len = self.btn_per_page/self.btn_count
        else:
            bar_len=1
        self.first_btn = int(float(pos)*self.btn_count)
        pos = str(self.getScrollPos())
        self.scrollbar.set(pos, str(float(pos)+bar_len))
        for i in range(len(self.btns)):
            mail_index = i+self.first_btn
            self.btns[i].config(text=self.texts[mail_index], command=self.callbacks[mail_index])
    
    def insertButton(self, text, callback):
        if self.btn_count < self.btn_per_page:
            btn = tk.Button(self.frame, bg='#fafafa',text=text, command=callback)
            btn.pack(fill='both', expand=1)
            self.btns.append(btn)
            
        self.btn_count += 1
        self.texts.append(text) 
        self.callbacks.append(callback)
        self.scrolly('', self.getScrollPos())
        
    def getScrollPos(self):
        if self.btn_per_page >= self.btn_count:
            return 0.0
        if self.btn_count == 0:
            return 0.0
        return self.first_btn/self.btn_count
        
    def callback(self):
        print('click')
        
    def destroy(self):
        self.win.destroy()
Пример #3
0
class ListDialog(object):
    def __init__ (self, master, items, message, accept_func):
        self.accept_func = accept_func

        self.top = Toplevel(master)
        self.top.transient(master)
        self.top.rowconfigure(0, weight=1)
        self.top.rowconfigure(1, weight=3)
        self.top.rowconfigure(2, weight=0)
        self.top.columnconfigure(0, weight=1)
        self.top.columnconfigure(1, weight=1)
        self.top.resizable(width=True, height=True)

        self.frame = Frame(self.top)
        self.frame.rowconfigure(0, weight=1)
        self.frame.rowconfigure(1, weight=0)
        self.frame.columnconfigure(0, weight=1)
        self.frame.columnconfigure(1, weight=0)
        self.frame.grid(row=0, column=0, sticky=(N, S, W, E), columnspan=2)
        self.canvas = Canvas(self.frame)
        self.canvas.create_text(0, 0, text=message, anchor=NW)
        self.canvas.grid(row=0, column=0, sticky=(N, W, S, E))

        self.vscroll = Scrollbar(self.frame, command=self.canvas.yview)
        self.vscroll.grid(row=0, column=1, sticky=(N, S))
        self.canvas['yscrollcommand'] = self.vscroll.set

        self.hscroll = Scrollbar(self.frame, command=self.canvas.xview, orient=HORIZONTAL)
        self.hscroll.grid(row=1, column=0, sticky=(W, E), columnspan=2)
        self.canvas['xscrollcommand'] = self.hscroll.set

        self.canvas['scrollregion'] = self.canvas.bbox('all')
        self.canvas.bind('<Button-4>', self.scroll)
        self.canvas.bind('<Button-5>', self.scroll)
        self.canvas.bind('<MouseWheel>', self.scroll)

        self.view = NameView(self.top, sorted(items))
        self.view.widget.grid(row=1, column=0, columnspan=2, sticky=(N, W, E, S))

        self.delbutton = Button(self.top, text='Ok', command=self.accept )
        self.cancelbutton = Button(self.top, text='Cancel', command=self.cancel)
        self.delbutton.grid(row=2, column=0)
        self.cancelbutton.grid(row=2, column=1)
        self.view.widget.focus_set()

    def accept(self):
        self.accept_func(self.view.selection())
        self.top.destroy()

    def cancel(self):
        self.result = None
        self.top.destroy()

    def scroll(self, event):
        if event.num == 4 or event.delta > 0:
            self.canvas.yview(SCROLL, -1, UNITS)
        elif event.num == 5 or event.delta < 0:
            self.canvas.yview(SCROLL, 1, UNITS)
Пример #4
0
class TkWindowNode(BaseWindowNode):
    '''The base class of all the Window Node in the WaveSyn Object Model.
Properties:
    tk_object: The underlying Tk Toplevel object;
    node_path: The path of this node on the WaveSyn Object Model Tree.
Properties inherited from ModelNode:
    root_node: The root node of the WaveSyn Object Model Tree.
'''
    window_name = ''
    _xmlrpcexport_  = ['close']    
    
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__tk_object = Toplevel()
        self.__tk_object.title(f'{self.window_name} id={id(self)}')
        self.__tk_object.protocol('WM_DELETE_WINDOW', self.on_close)
    
            
    method_name_map   = {
        'update':'update', 
        'set_window_attributes':'wm_attributes'
    }
    
    for method_name in method_name_map:
        locals()[method_name] = MethodDelegator('tk_object', 
                                                method_name_map[method_name])


    def _close_callback(self):
        pass        

       
    @Scripting.printable
    def close(self):
        #Scripting.root_node.on_window_quit(self)
        if hasattr(self.parent_node, 'on_window_close'):
            self.parent_node.on_window_close(self)
        # For Toplevel objects, use destroy rather than quit.
        if not self._close_callback():
            self.__tk_object.destroy() 
        
        
    def on_close(self):
        with code_printer():
            self.close()
        
            
    @property
    def tk_object(self):
        return self.__tk_object
    
        
    def create_timer(self, interval=100, active=False):
        return TkTimer(self.__tk_object, interval, active)
Пример #5
0
 def fetchMifParams(self):
     mifTop = Toplevel()
     self.mifApp = MifUI(mifTop)
     self.mifApp.mainloop()
     mifParams = self.mifApp.getParameters()
     mifTop.destroy()
     self.depth = int(mifParams[0])
     self.width = int(mifParams[1])
     self.address_radix = int(mifParams[2])
     self.data_radix = int(mifParams[3])
     self.fillZeros = int(mifParams[4])
Пример #6
0
 def open_running(self, task):
     ''' Displays a message while running the simulation '''
     popup = Toplevel(self)
     x = self.winfo_x()
     y = self.winfo_y()
     popup.geometry("+%d+%d" % (x//2, y//2))
     popup.title("Running")
     msg = Message(popup, text="Running simulation. Please Wait.")
     msg.pack()
     while task.is_alive():
         popup.update()
     popup.destroy() # only when thread dies.
Пример #7
0
class NewProjectWindow:
    def __init__(self, parent, model):
        self.model = model
        self.parent = parent
        self.window = Toplevel(parent.window)
        self.window.title('Nowy projekt')
        self.window.geometry('600x90')
        self.window.rowconfigure(0, weight=1)
        self.window.rowconfigure(1, weight=1)
        self.window.columnconfigure(1, weight=1)
        Label(self.window,
              text='Nazwa projektu:').grid(row=0, sticky=tk.NW + tk.N + tk.S)
        self.name_entry = Entry(self.window)
        self.name_entry.grid(row=0,
                             column=1,
                             columnspan=2,
                             sticky=tk.NW + tk.N + tk.S + tk.E)
        Label(self.window,
              text='Ścieżka do projektu:').grid(row=1,
                                                column=0,
                                                sticky=tk.NW + tk.N + tk.S)
        self.path_label = Label(self.window, anchor=tk.W, bg='white', width=40)
        self.path_label.grid(row=1,
                             column=1,
                             sticky=tk.NW + tk.N + tk.S + tk.E)
        Button(self.window, text='Wybierz',
               command=self.pick_dir).grid(row=1,
                                           column=2,
                                           sticky=tk.NW + tk.N + tk.S)
        Button(self.window, text='Anuluj',
               command=self.destroy).grid(row=2,
                                          column=0,
                                          sticky=tk.NW + tk.N + tk.S + tk.E)
        Button(self.window, text='Stwórz',
               command=self.create).grid(row=2,
                                         column=2,
                                         sticky=tk.NW + tk.N + tk.S + tk.E)

    def pick_dir(self):
        options = {}
        options['defaultextension'] = '.afz'
        options['filetypes'] = [('Pliki projektu', '.afz'),
                                ('Wszystkie pliki', '.*')]
        options['title'] = 'Utwórz projekt'
        filename = filedialog.asksaveasfilename(**options)
        self.path_label.config(text=filename)

    def create(self):
        self.model.new_project(self.path_label['text'], self.name_entry.get())
        self.destroy()

    def destroy(self):
        self.window.destroy()
Пример #8
0
class SettingsCameraWindow:
    def __init__(self):
        self.root = Toplevel()
        self.checkbutton1 = IntVar()

    def getScreenSize(self):
        w = self.root.winfo_screenwidth()
        h = self.root.winfo_screenheight()
        return w, h

    def getWindowSize(self):
        w = self.root.winfo_screenmmwidth()
        h = self.root.winfo_screenmmheight()
        return w, h

    def setTitle(self):
        self.root.title("Settings Camera")

    def setBind(self):
        #---------- CTRL + Q (Quit) ----------#
        self.root.bind("<Control-q>", self.quit_callback)
        self.root.bind("<Control-Q>", self.quit_callback)

    def setup(self):
        width, height = self.getScreenSize()
        width = int(width / 2 - 100)
        height = int(height / 2 - 100)

        screensize = convert2geometry(width, height)

        self.root.geometry(screensize)
        self.setTitle()

    #---------- Destroy ----------#
    def quit_callback(self, event=None):
        self.root.destroy()

    def isChecked_callback(self):
        print(self.checkbutton1.get())

    def createButton(self):
        Label(self.root, text="Is URL: ", width=6).grid(row=1, column=0)

    def createCheckButton(self):
        Checkbutton(self.root,
                    text="Is URL",
                    variable=self.checkbutton1,
                    command=self.isChecked_callback,
                    onvalue=1,
                    offvalue=0).pack()

    def main(self):
        self.root.mainloop()
Пример #9
0
class EntryOptionsWindow:
    def __init__(self, ls: str, tk: Tk, select_path=False) -> None:
        self.select_path = select_path
        self.List = ls
        self.Tk = tk
        self.Root = Toplevel(self.Tk)
        self.Root.withdraw()
        self.Frame = Frame(self.Root)
        self.Box = Listbox(self.Frame, selectmode='extended', width=54, height=24)
        for i in globals()[self.List]:
            self.Box.insert(END, i)
        self.Scroll = Scrollbar(self.Frame, command=self.Box.yview)
        self.Entry = Entry(self.Frame)
        self.ButtonAdd = Button(self.Frame, text='Добавить', command=self.__add_item)
        self.ButtonDel = Button(self.Frame, text='Удалить', command=self.__del_item)
        self.ButtonDone = Button(self.Frame, text='Готово', command=self.__save_list)
        self.ButtonExit = Button(self.Frame, text='Отмена', command=self.Root.destroy)

    def __add_item(self) -> None:
        if self.select_path:
            text = filedialog.askdirectory()
        else:
            text = self.Entry.get()
        if text:
            self.Box.insert(END, text)
            self.Entry.delete(0, END)

    def __del_item(self) -> None:
        select = list(self.Box.curselection())
        select.reverse()
        for i in select:
            self.Box.delete(i)

    def __save_list(self) -> None:
        globals()[self.List] = list(self.Box.get(0, END))
        self.Root.destroy()

    def main(self) -> None:
        center_win(self.Root, '500x400')
        self.Root.deiconify()
        self.Root.title(f'Editing {self.List}')
        self.Box.pack(side='left', expand=True)
        self.Scroll.pack(side='left', fill='y')
        self.Box.config(yscrollcommand=self.Scroll.set)
        self.Frame.pack(side='left', padx=10)
        if not self.select_path:
            self.Entry.pack(anchor='n')
        self.ButtonAdd.pack(fill='x')
        self.ButtonDel.pack(fill='x')
        self.ButtonDone.pack(fill='x')
        self.ButtonExit.pack(fill='x')
        self.Root.mainloop()
Пример #10
0
class AddRestrictionDialog():
    
    def __init__(self, parent):
        self.parent = parent
        self.gui = Toplevel(parent.guiRoot)
        self.gui.grab_set()
        self.gui.focus()
        
        self.gui.columnconfigure(0, weight=1)
        self.gui.columnconfigure(1, weight=1)
        
        Label(self.gui, text="Enzyme:").grid(row=0, column=0, sticky="e", padx=5)
        self.entryEnzyme = Entry(self.gui)
        self.entryEnzyme.grid(row=0, column=1, sticky="w", padx=5, pady=10)
        self.frameButtonGroup = Frame(self.gui)
        self.frameButtonGroup.grid(row=1, column=0, columnspan=2, pady=10)
        self.buttonOK = Button(self.frameButtonGroup, text=" OK ")
        self.buttonCancel = Button(self.frameButtonGroup, text=" Cancel ")
        self.buttonOK.grid(row=0, column=1, sticky="w", padx=5)
        self.buttonCancel.grid(row=0, column=0, sticky="e", padx=5)
        
        # Set (minimum + max) Window size 
        self.gui.update()
        self.gui.minsize(self.gui.winfo_width(), self.gui.winfo_height())
        self.gui.maxsize(self.gui.winfo_width(), self.gui.winfo_height())
        
        self.entryEnzyme.focus()
        
        self.buttonOK.bind("<ButtonRelease>", self.actionOK)
        self.buttonCancel.bind("<ButtonRelease>", self.actionCancel)
        self.entryEnzyme.bind("<Return>", self.actionOK)
        
        self.gui.mainloop()
#         self.gui.grab_release()
#         self.gui.destroy()

    def actionOK(self, event):
        enzymeString = self.entryEnzyme.get()
        if enzymeString in rest_dict.keys():
            
            if enzymeString in self.parent.optimizer.restrictionEnzymeList:
                showinfo("", (enzymeString + " was already added to the list"))
                return
                
            self.parent.optimizer.restrictionEnzymeList.append(enzymeString)
            self.parent.guiRoot.event_generate("<<Update>>", when="tail")
            self.gui.destroy()
        else:
            showinfo("", (enzymeString + " is not a valid restriction enzyme"))
    
    def actionCancel(self, event):
        self.gui.destroy()
class AddRestrictionDialog:
    def __init__(self, parent):
        self.parent = parent
        self.gui = Toplevel(parent.guiRoot)
        self.gui.grab_set()
        self.gui.focus()

        self.gui.columnconfigure(0, weight=1)
        self.gui.columnconfigure(1, weight=1)

        Label(self.gui, text="Enzyme:").grid(row=0, column=0, sticky="e", padx=5)
        self.entryEnzyme = Entry(self.gui)
        self.entryEnzyme.grid(row=0, column=1, sticky="w", padx=5, pady=10)
        self.frameButtonGroup = Frame(self.gui)
        self.frameButtonGroup.grid(row=1, column=0, columnspan=2, pady=10)
        self.buttonOK = Button(self.frameButtonGroup, text=" OK ")
        self.buttonCancel = Button(self.frameButtonGroup, text=" Cancel ")
        self.buttonOK.grid(row=0, column=1, sticky="w", padx=5)
        self.buttonCancel.grid(row=0, column=0, sticky="e", padx=5)

        # Set (minimum + max) Window size
        self.gui.update()
        self.gui.minsize(self.gui.winfo_width(), self.gui.winfo_height())
        self.gui.maxsize(self.gui.winfo_width(), self.gui.winfo_height())

        self.entryEnzyme.focus()

        self.buttonOK.bind("<ButtonRelease>", self.actionOK)
        self.buttonCancel.bind("<ButtonRelease>", self.actionCancel)
        self.entryEnzyme.bind("<Return>", self.actionOK)

        self.gui.mainloop()

    #         self.gui.grab_release()
    #         self.gui.destroy()

    def actionOK(self, event):
        enzymeString = self.entryEnzyme.get()
        if enzymeString in rest_dict.keys():

            if enzymeString in self.parent.optimizer.restrictionEnzymeList:
                showinfo("", (enzymeString + " was already added to the list"))
                return

            self.parent.optimizer.restrictionEnzymeList.append(enzymeString)
            self.parent.guiRoot.event_generate("<<Update>>", when="tail")
            self.gui.destroy()
        else:
            showinfo("", (enzymeString + " is not a valid restriction enzyme"))

    def actionCancel(self, event):
        self.gui.destroy()
class MainWindow:
    def __init__(self):
        global root
        self.master = Toplevel(root)
        self.master.withdraw()
        self.master.protocol('WM_DELETE_WINDOW', root.destroy)
        self.master.iconbitmap(imgdir)
        self.master.geometry("400x150")
        self.master.resizable(False, False)
        self.master.title("Adb & Fastboot Installer - By @Pato05")
        estyle = Style()
        estyle.element_create("plain.field", "from", "clam")
        estyle.layout("White.TEntry",
                      [('Entry.plain.field', {'children': [(
                          'Entry.background', {'children': [(
                              'Entry.padding', {'children': [(
                                  'Entry.textarea', {'sticky': 'nswe'})],
                                  'sticky': 'nswe'})], 'sticky': 'nswe'})],
                          'border': '4', 'sticky': 'nswe'})])
        estyle.configure("White.TEntry",
                         background="white",
                         foreground="black",
                         fieldbackground="white")
        window = Frame(self.master, relief=FLAT)
        window.pack(padx=10, pady=5, fill=BOTH)
        Label(window, text='Installation path:').pack(fill=X)
        self.syswide = IntVar()
        self.instpath = StringVar()
        self.e = Entry(window, state='readonly',
                       textvariable=self.instpath, style='White.TEntry')
        self.e.pack(fill=X)
        self.toggleroot()
        Label(window, text='Options:').pack(pady=(10, 0), fill=X)
        inst = Checkbutton(window, text="Install Adb and Fastboot system-wide?",
                           variable=self.syswide, command=self.toggleroot)
        inst.pack(fill=X)
        self.path = IntVar(window, value=1)
        Checkbutton(window, text="Put Adb and Fastboot in PATH?",
                    variable=self.path).pack(fill=X)
        Button(window, text='Install', command=self.install).pack(anchor='se')
        self.master.deiconify()

    def toggleroot(self):
        if self.syswide.get() == 0:
            self.instpath.set(installpaths['user'])
        elif self.syswide.get() == 1:
            self.instpath.set(installpaths['system'])

    def install(self):
        self.app = InstallWindow(setpath=self.path.get(
        ), installpath=self.instpath.get(), systemwide=self.syswide.get())
        self.master.destroy()
Пример #13
0
class HelpScreen():

    def __init__(self, parent):
        self.parent = parent
    
    # second screen - load screen
    def help_screen(self):
        """
        This is the initial load window --- maybe separate this and put a load bar in the future
        """
        # init top level frame/window
        self.help = Toplevel(self.parent) 
        # frame/window size
        self.help.geometry("420x420")
        # get frame/window width/height
        windowWidth = self.help.winfo_reqwidth()
        windowHeight = self.help.winfo_reqheight()
        # confirm frame/window width/height
        print("Width",windowWidth,"Height",windowHeight)
        # calculate center of frame/window width/height
        positionRight = int(self.help.winfo_screenwidth()/2 - windowWidth/2)
        positionDown = int(self.help.winfo_screenheight()/2 - windowHeight/2)
        # positions frame/window
        self.help.geometry("+{}+{}".format(positionRight, positionDown))
        # init percentage of load value
        self.percentage = 0
        # load screen text
        self.title2 = Label(self.help, text=f"How do you use this URL scraper?", foreground="black",pady=10, padx=1)    
        self.title2.pack()
        self.text1 = Label(self.help, text=f"\
        1. Copy a URL from any site you are interested in and paste  \n\
        it into the ~Enter URL To Parse~ input box.\n\n\
        2. Make sure the Full HTML checkbox is selected. This will \n\
        search each site from the opening body tag to the opening \n\
        footer tag \n\n\
        3. Upload the .txt data file. This needs to be a list of \n\
        words with a space between each word. \n\n\
        * Important * \n\
        -------------\n\
        The clear button will clear the URL entered and \n\
        the last .txt file uploaded\n\n\
        ** What can this tool do? ** \n\
        -----------------------------\n\
        This tool will request the html from the url \n\
        you entered and search for the keywords from \n\
        the .txt file that you uploaded in the requested html\n", foreground="black", width=70, anchor="w", justify=LEFT)
        self.text1.pack()
        self.button1 = ttk.Button(self.help, text="Close", command=self.close_help)
        self.button1.pack()

    def close_help(self):
        self.help.destroy()
Пример #14
0
class splash():
#    try:
    def __init__(self):
        moduleDir = dirname(__file__)
        moduleDir = moduleDir.rsplit('\\',2)[0]
        image = moduleDir+'\\resources\\sirbot\\splash.gif'
        self.root = Tk()
        self.root.withdraw()
        self.loadingSplash = Toplevel()
        splashimage = PhotoImage(file=image)
        self.loading = ttk.Label(self.loadingSplash,image=splashimage)
        self.loadingSplash.overrideredirect(True)
        self.loading.pack()

        h = self.loading.winfo_screenheight()
        w = self.loading.winfo_screenwidth()

        self.loadingSplash.wm_attributes('-alpha',0.75)
        self.loadingSplash.update_idletasks()
        self.loadingSplash.geometry('262x112+'+str(int(w/2)-131*1)+
                                    '+'+str(int(h/2)-56*1))
        self.loadingSplash.update_idletasks()
        self.loadingSplash.update()
        
#    except:
##        #log
##        loadingSplash = Tk()
##        #myfont = tkFont.families()[0]
##        loading = Label(loadingSplash,text='SirBot')
##        loadingSplash.overrideredirect(True)
##        loading.pack()
##
##        h = loading.winfo_screenheight()
##        w = loading.winfo_screenwidth()
##
##        loadingSplash.wm_attributes('-alpha',0.75)
##        loadingSplash.update_idletasks()
##        loadingSplash.geometry('262x112+'+str(int(w/2)-131*1)+
##                               '+'+str(int(h/2)-56*1))
##        loadingSplash.update_idletasks()
##        loadingSplash.update()

    def destroy(self):
        try:
            self.loadingSplash.destroy()
        except:
            #log
            pass

    def getroot(self):
        return(self.root)
Пример #15
0
    def save_data(self, event):
        #保存数据
        try:
            node_save_path = self.project_path + '/' + self.node_name + '.spliting'
            nowTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
            self.node_setting = {
                'node_type': 'SPLIT',
                'node_name': self.node_name,
                'node_save_path': node_save_path,
                'previous_node_name': self.previous_node_name,
                'previous_node_time': self.previous_node_time,  ##不清楚这两个是干什么的
                'method': self.method,
                'data_role': self.data_role,
                'replace': self.replace,
                'seed': self.seed,
                'train_pct': self.train_pct,
                'valid_pct': self.valid_pct,
                'adjuest_bad': self.sample_flag,
                'bad_sample_pct': self.bad_pct,
                'sample_bad_rate': self.bad_rate,
                'time': nowTime,
                #'check_change':[{'node_name': self.node_name,'node_time':nowTime}]+self.previous_check_change,
                'data_variable_setting': self.par_traindatavariable_setting,
                'use_node': [self.node_name] + self.previous_node_usedlist
            }
            data_save = (self.node_setting, self.trainpart_data,
                         self.validpart_data, self.par_train_data)

            error2 = Toplevel(self.master)
            screenwidth = self.master.winfo_screenwidth()
            screenheight = self.master.winfo_screenheight()
            error2.geometry('%dx%d+%d+%d' % (150, 100, (screenwidth - 150) / 2,
                                             (screenheight - 100) / 2))
            L2 = Label(error2, text="保存中")
            L2.grid()
            self.master.update()

            filename = node_save_path
            fw = open(filename, 'wb')
            pickle.dump(data_save, fw, 1)
            fw.close()

            self.save = 'Y'
            try:
                error2.destroy()
            except:
                pass
            self.master.destroy()

        except Exception as e:
            tk.messagebox.showwarning('错误', e)
Пример #16
0
class DriversWindow:
    def __init__(self, parent, model):
        self.model = model
        self.parent = parent
        self.window = Toplevel(parent.window)
        self.window.title('Lista sterowników')
        self.window.geometry('600x400')
        self.window.rowconfigure(0, weight=1)
        self.window.columnconfigure(0, weight=1)
        self.x_scroll = Scrollbar(self.window, orient=tk.HORIZONTAL)
        self.y_scroll = Scrollbar(self.window, orient=tk.VERTICAL)
        self.x_scroll.grid(row=1, column=0, columnspan=2, sticky=tk.E + tk.W)
        self.y_scroll.grid(row=0, column=2, sticky=tk.N + tk.S)
        self.listbox = Listbox(self.window,
                               xscrollcommand=self.x_scroll.set,
                               yscrollcommand=self.y_scroll.set)
        self.x_scroll['command'] = self.listbox.xview
        self.y_scroll['command'] = self.listbox.yview
        threading.Thread(target=self.populate_list).start()
        self.prog_window = ProgressWindow(self, 'Trwa szukanie sterowników')
        self.prog_window.start()
        self.listbox.grid(row=0,
                          column=0,
                          sticky=tk.N + tk.E + tk.S + tk.W,
                          columnspan=2)
        Button(self.window, text='Wybierz',
               command=self.pick_dev).grid(row=2, sticky=tk.NE, padx=10)
        Button(self.window, text='Anuluj',
               command=self.destroy).grid(row=2,
                                          column=1,
                                          sticky=tk.NW,
                                          padx=10)
        self.window.transient(master=parent.window)

    def pick_dev(self):
        self.model.project.devpath = self.listbox.get(
            self.listbox.curselection()).split()[-1]
        self.parent.refresh_driver()
        self.destroy()

    def populate_list(self):
        dev_list = self.model.list_dev_paths()
        for d in dev_list:
            if d is not '':
                self.listbox.insert(tk.END, d)
        self.prog_window.destroy()
        self.window.grab_set()

    def destroy(self):
        self.window.grab_release()
        self.window.destroy()
Пример #17
0
class SelectionY:
    def __init__(self, master, data):
        self.master = master
        self.data = data
        self.columns = self.data.columns
        self.variable = IntVar()

        self.window = Toplevel(self.master)
        self.window.grab_set()
        self.window.title('Dependent Variables')
        self.window.geometry('400x400')
        self.window.minsize(250, 250)

        self.frame = Frame(self.window)
        self.frame.pack(expand=True, fill=BOTH)

        self.canvas = Canvas(self.frame, background='antique white')

        self.v_scroll = Scrollbar(self.frame,
                                  orient=VERTICAL,
                                  command=self.canvas.yview)
        self.v_scroll.pack(side=RIGHT, fill=Y)

        self.canvas['yscrollcommand'] = self.v_scroll.set
        self.canvas.pack(expand=True, fill=BOTH)

        self.frame2 = Frame(self.canvas, bg='antique white')
        self.canvas.create_window((0, 0), window=self.frame2, anchor=N + W)

        for i in range(len(self.columns)):
            Radiobutton(self.frame2,
                        variable=self.variable,
                        value=i,
                        text=self.columns[i],
                        bg='antique white').pack(anchor=N + W)

        self.none = Button(self.canvas,
                           text='Confirm',
                           height=2,
                           width=10,
                           command=lambda: self.confirm())
        self.none.pack(anchor=E, padx=20, pady=20)

        self.canvas.configure(scrollregion=self.canvas.bbox(ALL))

        self.window.mainloop()

    def confirm(self):
        self.window.grab_release()
        self.window.quit()
        self.window.destroy()
Пример #18
0
class ResultOptions:

	def __init__(self,strtitle,result_str_arr=[],cmd_names=[],cmd_fun=[], args=[]):
		
		self.newwin=Toplevel()
		self.newwin.title(strtitle)

		scrollbar = Scrollbar(self.newwin)
		scrollbar.pack(side = 'right', fill = 'y') 
		
		ylist = tk.Listbox(self.newwin,yscrollcommand = scrollbar.set , width=100 , height=30) # 
		
		try:
		
			for tt in result_str_arr:
				if type(tt)==type([]):
					ylist.insert('end', str(tt[0] ) )   
				else:
					ylist.insert('end', str(tt) )   #.decode("utf-8")
		
		except:
			ylist.insert('end', str('Binary format to avoid system exception') )
			for tt in result_str_arr:
				if type(tt)==type([]):
					ylist.insert('end', str(tt[0].encode("utf-8")) )   
				else:
					ylist.insert('end', str(tt.encode("utf-8")) )   
		
		ylist.pack(side = 'top', fill = 'x') 
  
		scrollbar.config( command = ylist.yview )
		
		btns=[]
		
		for ii,btn in enumerate(cmd_names):
		
			tmpargs=()
			if args[ii][0]!=None:
				tmpargs=(result_str_arr,) + args[ii] 
			else:
				tmpargs=(result_str_arr,)
				
				
			btns.append(ttk.Button(self.newwin,text=btn,command=partial(self.run_opt,cmd_fun[ii],tmpargs) ) )
			btns[-1].pack(side='top', fill = 'x')
			
	def run_opt(self,opt_fun,args):
	
		opt_fun(*args)
	
		self.newwin.destroy()
def apply_column_selection(root: tk.Tk, win: tk.Toplevel, pane: ttk.Panedwindow):
    """
    Автор: Баканов Г.
    Цель: применяет к программме выбор столбцов (изменяет рабочее пространство)
    Вход: главное окно, побочное окно выбора столбцов, растягивающийся виджет
    Выход: нет
    """
    if any(glob.columns_selection.values()):
        glob.columns = [x for x in glob.columns_selection.keys() if glob.columns_selection[x].get() == 1]
        open_base(root, pane, glob.current_base_list_id)
        win.destroy()
    else:
        err.error("Не выбран ни один столбец")
        return "break"
Пример #20
0
	def average_normals( self ):
		""" Applies Gouraud normalization to the module		
		"""
		# Set up updater
		top = Toplevel()
		pb = Progressbar(top,orient ="horizontal",length = 200, mode ="determinate")
		pb['maximum'] = len(self.__elements__)
		pb['value'] = 10
		pb.grid(row=0,column=0)
		tx = Label(top)
		tx.grid(row=1,column=0)
		top.update_idletasks()
		top.lift()
		t0 = time.time()
				
		# run the loop, if we're visible and phong shading
		if not self.invisible == 'gouroud':
			try:
				buf = np.array([0,0,0,1])
				for i,polygon in enumerate(self.__elements__):
					if not ispoly(polygon): continue
					polygon._onorms = np.array([polygon.normals.astype(float)+buf for i in range(len(polygon.coordinates))])
					
					# Update the user as to what's going on
					if i % 50 == 0 and i > 0:
						pb['value'] = i
						tmp = i/len(self.__elements__)
						estimation =  int(tmp*(time.time()-t0) * (1-tmp)/tmp)
						tx.configure(text=str(int(100*i/len(self.__elements__)))+"%"+' Estimated time: '+str(estimation)+'s' )
						top.update_idletasks()
						
					for c,coordinate in enumerate(polygon.coordinates):
						for j,opolygon in enumerate(self.__elements__):
							if i == j or not ispoly(opolygon): continue
							for k,ocoordinate in enumerate(opolygon.coordinates):
								if all(coordinate == ocoordinate): # same vertex, finally
									polygon._onorms[c] += (opolygon.normals+buf)
					polygon._onorms /= polygon._onorms[:,3,None]
					
				for polygon in self.__elements__:
					if ispoly(polygon): 
						polygon.normals = polygon._onorms
						del polygon._onorms
			except IndexError as ie: pass
		
		top.destroy()
		
		if self.invisible == 'gouroud':
			self.invisible = False
		return self # for chaining
class CreateToolTip(object):
    """ Create a tooltip for a given widget.
    Parameters
    ----------
    Returns
    ------ 
    """
    def __init__(self, widget, thread, text='widget info'):
        self.widget = widget
        self.text = text
        self.widget.bind("<Enter>", self.timer)
        self.widget.bind("<Leave>", self.close)
        self.thread = thread

    def timer(self, event=None):
        self.inside = True

        def go():
            time.sleep(0.1)
            if self.inside == True:
                self.enter()

        self.thread.submit(go())
        #t.start()

    def enter(self):
        x = y = 0
        x, y, cx, cy = self.widget.bbox("insert")
        x += self.widget.winfo_rootx() + 25
        y += self.widget.winfo_rooty() + 20
        # creates a toplevel window
        self.tw = Toplevel(self.widget)
        # Leaves only the label and removes the app window
        self.tw.wm_overrideredirect(True)
        self.tw.wm_attributes("-alpha", 0.9)
        self.tw.wm_geometry("+%d+%d" % (x, y))
        label = tk.Label(self.tw,
                         text=self.text,
                         justify='left',
                         background='white',
                         relief='solid',
                         borderwidth=1,
                         font=("TkDefautlFont", "8", "normal"))

        label.pack(padx=0, pady=0)

    def close(self, event=None):
        self.inside = False
        if hasattr(self, 'tw'):  #self.tw:
            self.tw.destroy()
Пример #22
0
class About:
    def __init__(self, parent):
        pad_px = 5
        self.top = Toplevel(parent)
        self.top.title('About:')
        self.top.grab_set()  # Make the window modal

        label_title = Label(self.top, text='Minesweeper')
        label_title['font'] = 'Helvetica 16 bold'
        label_title.pack()
        file_path = os.path.dirname(os.path.realpath(__file__))

        grid_middle = Frame(self.top)

        logo = PhotoImage(file=os.path.join(file_path, '../res/logo.gif'))
        label_logo = Label(grid_middle, image=logo)
        label_logo.image = logo  # don't garbage collect me please.
        label_logo.grid(row=0, column=1, rowspan=4)

        label_description = Label(
            grid_middle,
            justify=LEFT,
            text=
            'Use your deductive powers to figure out where the mines are on the grid.\nYou lose if you step on a mine.\nTo win you must open every square except for the mines.'
        )
        label_description.grid(row=0, column=0)

        label_author = Label(grid_middle, justify=LEFT, text='by: SeggiePants')
        label_author.grid(row=1, column=0, sticky='W')

        label_copyright = Label(grid_middle,
                                justify=LEFT,
                                text='Copyright © 2019. All Rights Reserved.')
        label_copyright.grid(row=2, column=0, sticky='W')

        label_version = Label(grid_middle,
                              justify=LEFT,
                              text='Version: ' + __version__)
        label_version.grid(row=3, column=0, sticky='W')
        grid_middle.pack()

        button_ok = Button(self.top, text='OK', command=self.ok)
        button_ok.pack(padx=pad_px, pady=pad_px * 2, anchor=SE)

        self.top.tk.call('wm', 'iconphoto', self.top._w, logo)
        self.top.resizable(False, False)

    def ok(self):
        # Close the dialog
        self.top.destroy()
Пример #23
0
 def save_settings(self, settings_window: Toplevel,
                   settings: types.SimpleNamespace):
     if settings.aspect_ratio_checked.get():
         self.controller.model.args.aspect_ratio = (
             int(settings.aspect_ratio_x.get()),
             int(settings.aspect_ratio_y.get()))
     else:
         self.controller.model.args.aspect_ratio = None
     if settings.resize_checked.get():
         self.controller.model.args.resize = (int(settings.resize_x.get()),
                                              int(settings.resize_y.get()))
     else:
         self.controller.model.args.resize = None
     settings_window.destroy()
Пример #24
0
class EditSoundsPopup(object):
    def __init__(self, overview, master):
        self.top = Toplevel(master, padx=50, pady=20)
        self.top.title("Edit Sounds")
        self.master = master
        self.overview = overview

        s_a = [x[x.rfind("\\") + 1:] for x in self.overview.sound_array]

        ind = next(iter([i for i in range(len(self.overview.sound_array)) \
            if self.overview.sound_array[i].find(self.overview.sound_name) != -1]), None)
        if ind is None:
            ErrorPopup(
                self.master,
                "default sound " + self.overview.sound_name + " not found!")
            return

        soundobj = self.overview.sound_array[ind]
        self.c = Combobox(self.top, values=s_a, width=40)
        self.c.set(soundobj[soundobj.rfind("\\") + 1:])
        self.c.grid(row=1, column=0, columnspan=2, sticky="NEWS")
        Label(self.top, text="Choose a sound:").grid(row=0,
                                                     column=0,
                                                     columnspan=2,
                                                     sticky="NEWS")

        Button(self.top, text='Preview', command=self.play_s).grid(row=2,
                                                                   column=0,
                                                                   pady=10)
        Button(self.top, text='Set', command=self.set_s).grid(row=2,
                                                              column=1,
                                                              pady=10)

        ##center after packing
        center(self.top, master)

    def play_s(self):
        print(self.c.get())
        ns = AudioSegment.from_file(
            os.path.join(self.overview._SOUNDS, self.c.get()))
        ns = ns[:3 * 1000]
        play(ns)

    def set_s(self):
        self.overview.sound_name = self.c.get()
        self.cleanup()

    def cleanup(self):
        self.top.destroy()
Пример #25
0
class directCheckUI():
    def __init__(self, owner, repo, branch):
        # calculation
        try:
            nCommit = getNCommit(owner, repo, branch)
            msg = f"Number of commit: {str(nCommit)}"
        except HTTPError:
            msg = "Given repository or branch not found"
        self.tk = Toplevel()
        self.tk.focus_set()
        self.tk.geometry('260x150')
        centerWindow(self.tk)
        self.tk["bg"] = COLORs['bg']
        self.tk.attributes("-alpha", 0.95)
        # apearance
        Label(self.tk,
              text=f"{owner}/{repo}",
              bg=COLORs['bg'],
              font=Font(root=self.tk, family="Helvetica", size=13),
              fg=COLORs['txt']).place(anchor=N, x=130, y=15)
        Label(self.tk,
              text=branch,
              bg=COLORs['bg'],
              font=Font(root=self.tk, family="Helvetica", size=11),
              fg=COLORs['txt']).place(anchor=N, x=130, y=35)
        Label(self.tk,
              text=msg,
              bg=COLORs['bg'],
              font=Font(root=self.tk, family="Helvetica", size=11),
              fg=COLORs['txt']).place(anchor=N, x=130, y=65)
        self.btn = Button(self.tk,
                          text="Close",
                          command=(lambda: self.destroyWindow()),
                          bg=COLORs['frmLine'],
                          fg=COLORs['txt'],
                          relief=FLAT,
                          width=5,
                          height=1,
                          font=Font(root=self.tk, family="Helvetica", size=11),
                          activebackground=COLORs['frmLine'],
                          activeforeground=COLORs['txt'])
        batchBindEvent([self.tk, self.btn],
                       effect=bindPressButtonEffect,
                       target=self.btn,
                       root=self.tk)
        self.btn.place(anchor=N, x=130, y=105)

    def destroyWindow(self):
        self.tk.destroy()
Пример #26
0
    def test_open_and_close(self):
        # open calls create_widgets, which needs default_command
        self.dialog.default_command = None

        toplevel = Toplevel(self.root)
        text = Text(toplevel)
        self.dialog.open(text)
        self.assertEqual(self.dialog.top.state(), 'normal')
        self.dialog.close()
        self.assertEqual(self.dialog.top.state(), 'withdrawn')

        self.dialog.open(text, searchphrase="hello")
        self.assertEqual(self.dialog.ent.get(), 'hello')
        toplevel.update_idletasks()
        toplevel.destroy()
Пример #27
0
class ShapesMenu(object):
    """
    """
    def __init__(self, master, line_collection):
        try:
            self.width_of_entry = len(line_collection[0])
        except IndexError:
            self.width_of_entry = 0
        self.top = Toplevel(master)
        self.current_lines_listbox = Listbox(self.top)
        self.removed_lines_listbox = Listbox(self.top)
        self.submit = Button(self.top, text = "Ok", command=self.submit)
        self.remove_button = Button(self.top, text = "Remove", command=self.remove_line)
        self.cancel = Button(self.top, text = "Cancel", command=self.top.destroy)
        self.top.bind("<Return>", func=self.submit)
        self.current_lines = line_collection
        self.removed_lines = []
        self.ids_internal = []
        self.ids = []
        for index, line in enumerate(self.current_lines):
            #removes the point data and converts the rest to strings
            id = line[1]
            if id not in self.ids_internal:
                self.ids_internal.append(id)
                self.ids.append(id)
                line = [str(element) for element in line[1:]]
                
                #put into the list
                self.current_lines_listbox.insert(index, " ".join(line))
        self.current_lines_listbox.grid(row=0, column=0, columnspan=3)
        self.submit.grid(row=1, column=1)
        self.cancel.grid(row=1, column=2)
        self.remove_button.grid(row=1, column=0)
        
    def submit(self):
        #expose the internal IDs to remove to the exterior methods
        self.ids = self.ids_internal
        self.top.destroy()

    def remove_line(self):
        """Take the active line and remove it"""
        
        line_to_remove = self.current_lines_listbox.get(ANCHOR)
        id_to_remove = int(line_to_remove.split(" ")[0])
        #remove it from the ID list
        self.ids_internal.remove(id_to_remove)
        #remove it from the listbox
        self.current_lines_listbox = self.current_lines_listbox.delete(ANCHOR)
Пример #28
0
class TkWindowNode(BaseWindowNode):
    '''The base class of all the Window Node in the WaveSyn Object Model.
Properties:
    tk_object: The underlying Tk Toplevel object;
    node_path: The path of this node on the WaveSyn Object Model Tree.
Properties inherited from ModelNode:
    root_node: The root node of the WaveSyn Object Model Tree.
'''
    window_name = ''
    _xmlrpcexport_ = ['close']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__tk_object = Toplevel()
        self.__tk_object.title(f'{self.window_name} id={id(self)}')
        self.__tk_object.protocol('WM_DELETE_WINDOW', self.on_close)

    method_name_map = {
        'update': 'update',
        'set_window_attributes': 'wm_attributes'
    }

    for method_name in method_name_map:
        locals()[method_name] = MethodDelegator('tk_object',
                                                method_name_map[method_name])

    def _close_callback(self):
        pass

    @WaveSynScriptAPI
    def close(self):
        #Scripting.root_node.on_window_quit(self)
        if hasattr(self.parent_node, 'on_window_close'):
            self.parent_node.on_window_close(self)
        # For Toplevel objects, use destroy rather than quit.
        if not self._close_callback():
            self.__tk_object.destroy()

    def on_close(self):
        with code_printer():
            self.close()

    @property
    def tk_object(self):
        return self.__tk_object

    def create_timer(self, interval=100, active=False):
        return TkTimer(self.__tk_object, interval, active)
Пример #29
0
        def askgridprop():
            win = Toplevel()
            color = ['#000000', '#000000']

            propvars = [StringVar() for i in range(4)]
            guidata = ({
                'linestyle': ('Major Line Style', propvars[0], None),
                'linewidth':
                ('Major Line Width', propvars[1], check_nonnegative_float)
            }, {
                'linestyle': ('Minor Line Style', propvars[2], None),
                'linewidth':
                ('Minor Line Width', propvars[3], check_nonnegative_float)
            })

            for d in guidata:
                for key in d:
                    pitem = LabeledEntry(win)
                    pitem.pack()
                    pitem.label_text = d[key][0]
                    pitem.entry['textvariable'] = d[key][1]
                    if d[key][2]:
                        pitem.checker_function = d[key][2]

            def setmajorcolor():
                c = askcolor()
                color[0] = c[1]

            def setminorcolor():
                c = askcolor()
                color[1] = c[1]

            Button(win, text='Major Line Color', command=setmajorcolor).pack()
            Button(win, text='Minor Line Color', command=setminorcolor).pack()

            win.protocol('WM_DELETE_WINDOW', win.quit)
            win.focus_set()
            win.grab_set()
            win.mainloop()
            win.destroy()

            c_major = StringVar()
            c_major.set(color[0])
            c_minor = StringVar()
            c_minor.set(color[1])
            guidata[0]['color'] = ('Major Line Color', c_major, None)
            guidata[1]['color'] = ('Minor Line Color', c_minor, None)
            return guidata
Пример #30
0
    def upload():
        file_path_list = filedialog.askopenfilenames(
            initialdir="/",
            title='Upload single or multiple .pdf and/or .docx files')
        if len(file_path_list) != 0:
            window_width = 200
            window_height = 100
            screen_width = root.winfo_screenwidth()
            screen_height = root.winfo_screenheight()
            x = (screen_width / 2) - (window_width / 2)
            y = (screen_height / 2) - (window_height / 2)
            popup_loading = Toplevel()
            popup_loading.geometry(
                f'{window_width}x{window_height}+{int(x)}+{int(y)}')

            info = Label(popup_loading, text="Loading...")
            info.pack(fill='x', padx=15, pady=15)

            for file in file_path_list:
                name, extension = os.path.splitext(file)
                if extension == '.pdf':
                    upload_pdf(file)
                elif extension == '.docx':
                    upload_docx(file)
                else:
                    upload_un_files(file)
            popup_loading.after(5000, lambda: popup_loading.destroy())
Пример #31
0
    def demandeNouvellePartie(self):
        win = Toplevel(self.root)

        strtmp = "Le joueur " + self.reseau.nomAdversaire + " demande de faire une nouvelle partie. Acceptez-vous ?"
        lb = Label(win, text=strtmp)

        tailleX = lb.winfo_reqwidth()
        tailleY = 50

        numero = str(self.root.geometry()).split('+')
        posX = int(numero[1])
        posY = int(numero[2])

        positionX = int(posX + (self.tailleEcranX / 2) - (tailleX / 2))
        positionY = int(posY + (self.tailleEcranY / 2) - (tailleY / 2))

        geo = str(tailleX) + "x" + str(tailleY) + "+" + str(
            positionX) + "+" + str(positionY)

        win.geometry(geo)
        win.title("Demande")
        win.resizable(width=False, height=False)

        lb.grid(row=0, column=0, columnspan=2)

        Button(win,
               text='OUI',
               command=lambda: [self.fenetreChoixEnLigne(),
                                win.destroy()]).grid(row=1, column=0)
        Button(win, text='NON', command=win.destroy).grid(row=1, column=1)
Пример #32
0
def statistics(df, dictionaries):
    """ фомрмирование статистик """
    global stat
    report = Toplevel()
    qty = StringVar(report)
    headers = [item for item in df if item not in ['Цена', 'Билет', 'Время']]
    q1 = LabelFrame(report, text='Качественные')
    q2 = LabelFrame(report, text='Количественные')
    choice = Combobox(q1, values=headers, textvariable=qty)
    qty.trace('w', lambda name, index, mode, sv=qty: updateBoxes(sv))
    qty.set(headers[0])
    choice.current(0)
    choice.pack(side=LEFT, padx=5, pady=5)
    q1.pack(side=TOP, padx=10, pady=10)
    choice2 = Combobox(q2, values=['Цена'])
    choice2.pack(side=LEFT, padx=5, pady=5)
    choice2.current(0)
    choice2.config(state=DISABLED)
    q2.pack(side=TOP, padx=10, pady=10)
    bframe = Frame(report)
    Button(bframe, text='Сформировать', command=lambda frame=df: text_report_old(frame))\
        .pack(side=LEFT, padx=10, pady=10)
    Button(bframe, text='Закрыть', command=lambda: report.destroy())\
        .pack(side=LEFT, padx=10, pady=10)
    bframe.pack(side=TOP)
Пример #33
0
class AreYouSurePopup(object):
    def __init__(self, master, text):
        self.top = Toplevel(master, padx=20)
        Label(self.top, text="Are you sure you want to " + text + "?").pack()
        Button(self.top, text='Yes', command=self.yes).pack()
        Button(self.top, text='No!', command=self.no).pack()
        ##center after packing
        center(self.top, master)

    def yes(self, ):
        self.value = True
        self.top.destroy()

    def no(self, ):
        self.value = False
        self.top.destroy()
Пример #34
0
    def __init__(self, controleur, fenetre):
        self.control = controleur

        jeu = Toplevel()

        cadre = Frame(jeu)
        cadre.pack(padx=5, pady=5)

        etiquette = Label(cadre, text='temps ')
        etiquette.pack(padx=5, pady=5, side=LEFT)
        var_texte = IntVar()
        self.entree = Entry(cadre, textvariable=var_texte, width=50)

        self.entree.pack(padx=5, pady=5, side=LEFT)
        self.entree.focus_force()

        btnAffiche = Button(
            jeu,
            text='ok',
            command=lambda: [self.afficheZoneSaisie(),
                             jeu.destroy()])
        btnAffiche.pack(padx=5, pady=5)
        jeu.transient(fenetre)  # Réduction popup impossible
        jeu.grab_set()
        fenetre.wait_window(jeu)
def privacy_popup():
    #This function defines a popup window that opens when you click the red button in GUI
    privacy_check_popup_window = Toplevel()
    privacy_check_popup_window.geometry(get_main_window_of_gui_postion(
    ))  #this line makes popup open at the place of main window
    privacy_check_popup_window.wm_attributes(
        "-topmost", 1)  #this line makes popup open on top of main window
    privacy_check_popup_window.wm_title("Privacy Check")
    post_comment_input_field = Label(
        privacy_check_popup_window,
        text=
        "Are you sure that this content should go live immediately? \n\n Click 'No' to move it back to Private. \n"
    )
    post_comment_input_field.pack()
    Yes_button = Button(
        privacy_check_popup_window,
        text="Yes",
        width=10,
        height=1,
        command=lambda: privacy_approved(privacy_check_popup_window))
    Yes_button.pack()
    No_button = Button(privacy_check_popup_window,
                       text="No",
                       width=10,
                       height=1,
                       command=lambda: privacy_check_popup_window.destroy())
    No_button.pack()
    privacy_check_popup_window.mainloop()
Пример #36
0
    def open_finder(self, event=None):
        '''Creates and opens a finder window that allows to find a text
        inside the text widget.
        
        Parameters
        ----------
            event : object
                A bind key event
        '''

        finder_window = Toplevel(self.master)
        finder_window.wm_title('Notepad - Finder')
        self.define_window_geometry(finder_window, 374, 115)
        finder_window.takefocus = True

        finder_window._current_text = None

        Label(finder_window, text='Text to find:').place(x=10, y=10)

        finder_window._finder_entry = ttk.Entry(finder_window, width=50)
        finder_window._finder_entry.place(x=10, y=30)

        finder_window._find_button = ttk.Button(finder_window, text='Find',\
           command=lambda: self.find_text(finder_window))
        finder_window._find_button.place(x=117, y=60, width=60)

        finder_window._cancel_button = ttk.Button(finder_window, text='Cancel',\
           command=lambda: finder_window.destroy())
        finder_window._cancel_button.place(x=197, y=60, width=60)
Пример #37
0
    def PausePopup(self, newColor="black", trim=False):
        tl = Toplevel(root)
        tl.attributes('-topmost', 'true')
        tl.grab_set()

        tl.title("Tool change")
        msg = "change the tool for a next color"
        if trim:
            tl.title("Thread trim")
            msg = "cut the thread"

        frame = Frame(tl)
        frame.grid()

        canvas = Canvas(frame, width=64, height=64)
        canvas.grid(row=2, column=0)
        canvas.create_rectangle(0, 0, 65, 65, fill=newColor)
        msgbody = Label(
            frame,
            text=
            "There is the moment to %s. Resume the current job after change." %
            msg)
        msgbody.grid(row=1, column=0, sticky=N)

        okbttn = Button(frame,
                        text="OK",
                        command=lambda: tl.destroy(),
                        width=10)
        okbttn.grid(row=2, column=2)
Пример #38
0
 def JobFinished(self, messagePopup=True):
     self.isJobRunning = False
     self.isJobPaused = False
     self.lastSendCommandIndex = -1
     self.lastMove = None
     self.distanceTraveled = 0
     self.currentToolChange = 0
     self.currentToolPoint = 0
     self.currentColor = 'black'
     self.toolPointsLabel.config(
         text="%d/%d" % (self.currentToolPoint, self.toolPointsTotal))
     self.toolChangesLabel.config(
         text="%d/%d" % (self.currentToolChange, self.toolChangesTotal))
     self.UpdateTimeEstLabel()
     self.startButton.config(text="Start job")
     self.status.config(text="Job finished")
     timeTaken = time.time() - self.start
     # non blocking popup messagebox
     if messagePopup:
         tl = Toplevel(root)
         # this pop-up is always on top and other windows are deactivated
         tl.attributes('-topmost', 'true')
         tl.title("Job finished")
         tl.grab_set()
         frame = Frame(tl)
         frame.grid()
         Label(frame,
               text='Current job is finished and took %s.' %
               time.strftime("%H hours, %M minutes, %S seconds",
                             time.gmtime(timeTaken))).grid(row=0,
                                                           column=0,
                                                           sticky=N)
         Button(frame, text="OK", command=lambda: tl.destroy(),
                width=10).grid(row=1, column=0)
def QuitMainWindow(quit_mainwindow):
    quit_mainwindow = Toplevel()
    quit_mainwindow.title("Attention!")
    center_window(quit_mainwindow, quit_mainwindow_width,
                  quit_mainwindow_height)
    quit_mainwindow.resizable(0, 0)

    # Canvas
    q_canvas = Canvas(quit_mainwindow, highlightthickness=0, bg='white')
    q_canvas.pack(fill='both', expand='yes')

    # 图标
    image = Image.open("./items/Attention1.gif")
    im = ImageTk.PhotoImage(image)
    Pic = Label(q_canvas, highlightthickness=0, image=im, bg='white')
    Pic.pack(side='top', fill='both')

    # Canvas1
    canvas_Button = Canvas(q_canvas, highlightthickness=0, bg='white')

    # 标签及按钮
    label_Title = Label(q_canvas,
                        text="Do you want to quit?",
                        bg='white',
                        font=("Arial", 14, "bold"),
                        width=20,
                        height=3,
                        justify=CENTER)

    button_Yes = Button(canvas_Button,
                        text='Yes',
                        bg='white',
                        font=('Arial 13 normal'),
                        fg='#011640',
                        width=6,
                        height=1,
                        justify=CENTER,
                        command=quit)

    button_No = Button(canvas_Button,
                       text='No',
                       bg='white',
                       font=('Arial 13 normal'),
                       fg='#011640',
                       width=6,
                       height=1,
                       justify=CENTER,
                       command=quit_mainwindow.destroy)
    button_Yes.focus_set()

    quit_mainwindow.bind("<Return>", lambda x: quit())
    quit_mainwindow.bind("<Escape>", lambda x: quit_mainwindow.destroy())

    # 组件管理
    label_Title.pack(side='top', fill='both')
    canvas_Button.pack()
    button_Yes.grid(row=0, column=0, padx=20)
    button_No.grid(row=0, column=1, padx=20)

    quit_mainwindow.mainloop()
Пример #40
0
        def askgridprop():
            win = Toplevel()
            color = ['#000000', '#000000']

            propvars = [StringVar() for i in range(4)]
            guidata = (
                {
                    'linestyle': ('Major Line Style', propvars[0], None),
                    'linewidth': ('Major Line Width', propvars[1], check_nonnegative_float)
                },
                {
                    'linestyle': ('Minor Line Style', propvars[2], None),
                    'linewidth': ('Minor Line Width', propvars[3], check_nonnegative_float)
                }
            )

            for d in guidata:
                for key in d:
                    pitem = LabeledEntry(win)
                    pitem.pack()
                    pitem.label_text = d[key][0]
                    pitem.entry['textvariable'] = d[key][1]
                    if d[key][2]:
                        pitem.checker_function = d[key][2]

            def setmajorcolor():
                c = askcolor()
                color[0] = c[1]

            def setminorcolor():
                c = askcolor()
                color[1] = c[1]
                
            Button(win, text='Major Line Color', command=setmajorcolor).pack()
            Button(win, text='Minor Line Color', command=setminorcolor).pack()

            win.protocol('WM_DELETE_WINDOW', win.quit)
            win.focus_set()
            win.grab_set()
            win.mainloop()
            win.destroy()
            
            c_major = StringVar(); c_major.set(color[0])
            c_minor = StringVar(); c_minor.set(color[1])
            guidata[0]['color'] = ('Major Line Color', c_major, None)
            guidata[1]['color'] = ('Minor Line Color', c_minor, None)
            return guidata
Пример #41
0
class ZoomWindow(object):
    """description of class"""

    def __init__(self, master):
        self.top = Toplevel(master)
        self.entry_width = 15
        self.set_none_limits()
        self.real_max_label = Label(self.top, text="Real Max: ")
        self.real_min_label = Label(self.top, text="Real Min: ")
        self.imag_max_label = Label(self.top, text="Imag Max: ")
        self.imag_min_label = Label(self.top, text="Imag Min: ")
        self.real_max_entry = Entry(self.top, width=self.entry_width)
        self.real_min_entry = Entry(self.top, width=self.entry_width)
        self.imag_max_entry = Entry(self.top, width=self.entry_width)
        self.imag_min_entry = Entry(self.top, width=self.entry_width)
        self.submit_button = Button(self.top, text="Submit", command=self.submit)
        self.cancel_button = Button(self.top, text="Cancel", command=self.top.destroy)
        self.real_max_label.grid(row=0, column=0)
        self.real_min_label.grid(row=1, column=0)
        self.imag_max_label.grid(row=2, column=0)
        self.imag_min_label.grid(row=3, column=0)
        self.real_max_entry.grid(row=0, column=1)
        self.real_min_entry.grid(row=1, column=1)
        self.imag_max_entry.grid(row=2, column=1)
        self.imag_min_entry.grid(row=3, column=1)
        self.submit_button.grid(row=4, column=0)
        self.cancel_button.grid(row=4, column=1)
        self.top.bind("<Return>", self.submit)
        self.top.bind("<Escape>", self.top.destroy)
        self.real_max_entry.focus()
        
    def set_none_limits(self):
        self.imag_min, self.imag_max, self.real_max, self.real_min = (None, None, None, None)

    def submit(self, event=None):
        try:
            self.imag_min = float(self.imag_min_entry.get())
            self.imag_max = float(self.imag_max_entry.get())
            self.real_min = float(self.real_min_entry.get())
            self.real_max = float(self.real_max_entry.get())
            if self.imag_min > self.imag_max or self.real_min > self.real_max:
                self.set_none_limits()
                print("A min field exceeds a max field")
        except TypeError:
            print("Values passed are not real numbers")
        self.top.destroy()
Пример #42
0
 def askSpan(orient='v'):
     win = Toplevel()
     pxmin = LabeledEntry(win)
     pxmin.pack()
     pxmin.label_text = 'xmin' if orient=='v' else 'ymin'
     pxmax = LabeledEntry(win)
     pxmax.pack()
     pxmax.label_text = 'xmax' if orient=='v' else 'ymax'
     def formatter(val):
         val = float(val)
         val /= 100.
         return '{0:0.2f}'.format(val)
     alphaScale = LabeledScale(win, from_=0, to=100, name='alpha', formatter=formatter)
     alphaScale.set(50.0)
     alphaScale.pack()
     win.protocol('WM_DELETE_WINDOW', win.quit)
     win.focus_set()
     win.grab_set()
     win.mainloop()
     xmin    = pxmin.entry.get()
     xmax    = pxmax.entry.get()
     alpha   = alphaScale.get() / 100.
     win.destroy()
     return map(float, (xmin, xmax, alpha))
Пример #43
0
def ask_class_name():
    win = Toplevel()
    
    module_name  = StringVar()
    class_name   = StringVar()
    
    module_item  = LabeledEntry(win)
    module_item.label_text    = 'Module Name'
    module_item.pack()
    module_item.entry_variable     = module_name
    
    class_item   = LabeledEntry(win)
    class_item.label_text     = 'Class Name'
    class_item.pack()
    class_item.entry_variable      = class_name
    
    Button(win, text='OK', command=win.quit).pack()

    win.protocol('WM_DELETE_WINDOW', win.quit)
    win.focus_set()
    win.grab_set()
    win.mainloop()
    win.destroy()
    return module_name.get(), class_name.get()
Пример #44
0
 def destroy(self):  # close win silently
     Toplevel.destroy(self)  # redef for close ops
Пример #45
0
class TextSelect(Frame):

    def __init__(self, client, anchor, items, destroyAnchor=False):
        """
        Args:
            client: [SelectionClient] The window that text is returned to.
            anchor: A window that the text selection popup is created
                relative to.
            items: [str], items to display in the listbox.
            destroyAnchor: [bool] if true, destroy the anchor after
                positioning the window.
        """
        self.top = Toplevel()
        self.anchor = anchor
        self.top.overrideredirect(1)
        self.top.wm_geometry('+%s+%s' % (anchor.winfo_rootx() + anchor.winfo_x(),
                                         anchor.winfo_rooty() + anchor.winfo_y()
                                         )
                             )
        super(TextSelect, self).__init__(self.top)
        self.entry = Entry(self)
        self.client = client
        self.items = items
        self.place(x = 0.5, y = 0.5, height = 100, width = 100)
        self.entry.bind('<Return>', self.close)
        self.entry.bind('<KeyPress>', self.filter)
        self.entry.bind('<Escape>', self.abort)
        self.entry.bind('<Up>', self.up)
        self.entry.bind('<Down>', self.down)
        self.entry.pack()

        # Create the list of items.
        self.list = Listbox(self)
        for item in self.items:
            self.list.insert('end', item)
        self.list.pack()
        self.grid()
        self.entry.focus()

        # Reposition the select button against the anchor.  We defer this
        # until after idle so that the anchor has a chance to get rendered.
        def reposition(*args):
            self.top.wm_geometry('+%s+%s' % (
                anchor.winfo_rootx(),
                anchor.winfo_rooty())
            )
            if destroyAnchor:
                anchor.destroy()
        self.after_idle(reposition)

    def close(self, event):
        sel = self.list.curselection()
        if sel:
            item = self.list.get(sel[0])
        else:
            item = self.entry.get()

        # Note that the order of this appears to be significant: destroying
        # before selecting leaves the focus in a weird state.
        self.client.selected(item)
        self.top.destroy()
        return 'braek'

    def abort(self, event):
        self.top.destroy()
        self.client.aborted()
        return 'break'

    def up(self, event):
        sel = self.list.curselection()
        if not sel:
            self.list.selection_set(0)
            return 'break'
        sel = sel[0]

        print('sel is %s size is %s' % (sel, self.list.size()))
        if sel > 0:
            print('setting selection to %s' % sel)
            self.list.selection_clear(sel)
            self.list.selection_set(sel - 1)
            self.list.see(sel)
        return 'break'

    def down(self, event):
        sel = self.list.curselection()
        if not sel:
            self.list.selection_set(0)
            return 'break'
        sel = sel[0]

        print('sel is %s size is %s' % (sel, self.list.size()))
        if sel < self.list.size() - 1:
            print('setting selection to %s' % (sel + 1))
            self.list.selection_clear(sel)
            self.list.selection_set(sel + 1)
            self.list.see(sel)
        return 'break'

    def filter(self, event):
        """Filter the listbox based on the contents of the entryfield."""
        # first add the character to the entry.
        currentText = self.entry.get()
        print(event.keysym)
        if event.keysym == 'BackSpace':
            # Handle backspace specially.
            if currentText:
                currentText = currentText[:-1]
                self.entry.delete(0, 'end')
                self.entry.insert(0, currentText)
            else:
                return 'break'
        else:
            # Assume normal character. Insert it.
            self.entry.insert('insert', event.char)
            currentText += event.char

        self.list.delete(0, 'end')
        pattern = currentText.upper()
        for item in self.items:
            if pattern in item.upper():
                self.list.insert('end', item)

        return 'break'
Пример #46
0
 def destroy(self):
     Toplevel.destroy(self)
class SpeciesSearchDialog:
    def __init__(self, parent, caller):
        # main window
        self.parent = parent
        # dialog that called this second dialog
        self.caller = caller
        self.gui = Toplevel(parent.guiRoot)
        self.gui.grab_set()
        self.gui.focus()

        self.gui.columnconfigure(0, weight=1)
        self.gui.rowconfigure(1, weight=1)

        self.entrySearch = Entry(self.gui)

        self.buttonSearch = Button(self.gui, text=" Search ")
        self.buttonAdd = Button(self.gui, text=" Add Species ")
        self.buttonClose = Button(self.gui, text=" Close Window ")

        self.frameResults = Frame(self.gui)
        self.frameResults.columnconfigure(0, weight=1)
        self.frameResults.rowconfigure(0, weight=1)
        self.scrollResults = Scrollbar(self.frameResults, orient="vertical")
        self.scrollResults.grid(row=0, column=1, sticky="ns")
        self.listResults = Listbox(self.frameResults, width=70, height=20)
        self.listResults.grid(row=0, column=0, sticky="nswe")

        self.listResults.config(yscrollcommand=self.scrollResults.set)
        self.scrollResults.config(command=self.listResults.yview)

        self.entrySearch.grid(row=0, column=0, columnspan=2, sticky="we", padx=5, pady=5)
        self.frameResults.grid(row=1, column=0, columnspan=3, sticky="nswe", padx=5, pady=5)
        self.buttonSearch.grid(row=0, column=2, padx=5, pady=5, sticky="e")
        self.buttonAdd.grid(row=2, column=1, padx=5, pady=5, sticky="e")
        self.buttonClose.grid(row=2, column=2, padx=5, pady=5, sticky="e")

        self.gui.protocol("WM_DELETE_WINDOW", self.actionClose)
        self.buttonClose.bind("<ButtonRelease>", self.actionClose)
        self.buttonAdd.bind("<ButtonRelease>", self.actionAdd)
        self.buttonSearch.bind("<ButtonRelease>", self.actionSearch)
        self.entrySearch.bind("<Return>", self.actionSearch)

        self.gui.update()
        self.gui.minsize(self.gui.winfo_width(), self.gui.winfo_height())

        self.gui.mainloop()

    def actionAdd(self, event):
        try:
            selection = self.listResults.selection_get()
            selectionSplit = selection.split(":\t", 1)
            selectionSplit2 = selectionSplit[1].split("\t")
            if not (selectionSplit[0], selectionSplit2[0]) in self.parent.optimizer.speciesList:
                self.parent.optimizer.speciesList.append((selectionSplit[0], selectionSplit2[0].strip()))
            self.caller.gui.event_generate("<<Update>>")
        except tkinter.TclError:
            # no selection
            pass

    def actionSearch(self, event):
        query = self.entrySearch.get()
        if query:

            self.listResults.delete(0, "end")

            results = self.parent.optimizer.SPSUMHandler.search(query)
            # sort results by nr of CDS
            results = sorted(results.items(), reverse=True, key=lambda x: (int(x[1][1])))
            for name, (taxid, ncs) in results:
                self.listResults.insert("end", taxid + ":\t " + name + " \t(" + ncs + " CDS)")

    def actionClose(self, event=None):
        self.caller.gui.event_generate("<<Update>>", when="tail")
        self.gui.destroy()
Пример #48
0
class HigherUpsEmail:
    def __init__(self):
        window = Tk()
        window.title("E-mail Your Higher Ups")

        self.ports =  [587,587,587,465, 465, 465, 465, 465, 25, 25, 587, 465, 465, 25, 25, 25, 25, 25, 25, 465, 25, 587, 587, 587, 587, 465, 587, 465, 465, 465]
        self.servername = ["Chose your email provider","gmail","outlook","office365","Yahoo", "Yahoo Mail Plus", "Yahoo Uk"
                           "Yahoo Deutschland", "Yahoo AU/NZ", "O2", "AOL", "AT&T", "NTL @ntlworld.com", "BT Connect",
                           "BT Openworld", "BT Internet", "Orange", "Orange.uk", "Wandoo UK", "Hotmail", "O2 Online Deutschland", "T-Online Deutschland",
                           "1&1 (1and1)", "1&1 Deutschland", "Comcast", "Verizon", "Verizon (Yahoo Hosted)", "Zoho Mail", "Mail.com", "GMX.com"]
        self.server = ["smtp.gmail.com", "smtp.outlook.com", "smtp.office365.com", "smtp.mail.yahoo.com", "plus.smtp.mail.yahoo.com", "smtp.mail.yahoo.co.uk"
                       , "smtp.mail.yahoo.com", "smtp.mail.yahoo.com.au", "smtp.o2.ie", "smtp.o2.co.uk", "smtp.aol.com", "smtp.att.yahoo.com", "smtp.ntlworld.com"
                       , "mail.btconnect.com", "mail.btopenworld.com", "mail.btinternet.com", "smtp.orange.net", "smtp.orange.co.uk", "smtp.wandoo.co.uk", "smtp.live.com",
                       "mail.o2online.de", "secure.smtp.t-online.de", "smtp.1and1.com", "smtp.1und1.de", "smtp.comcast.net", "outgoing.verizon.net",
                       "outgoing.yahoo.verizon.net", "smtp.zoho.com", "smtp.mail.com", "smtp.gmx.com"]
        self.emailEndings = ["gmail.com", "outlook.com", "office365.com", "yahoo.com", "yahoo.com", "yahoo.co.uk", "yahoo.com", "yahoo.com.au", "o2.ie", "o2.co.uk",
                             "aol.com", "att.yahoo.com", "ntlworld.com", "btconnect.com", "btopenworld.com.", "btinternet.com", "orange.net", "orange.co.uk",
                             "wandoo.co.uk", "hotmail.com", "o2online.de", "t-online.de", "1and1.com", "1und1.de", "comcast.net", "verizon.net", "yahoo.verizon.net",
                             "zoho.com", "gmx.com"]
        self.index = 0
        
        
        # Create a menu bar
        menubar = Menu(window)
        window.config(menu = menubar) # Display the menu bar
        
        # create a pulldown menu, and add it to the menu bar
        userMenu = Menu(menubar, tearoff = 0)
        menubar.add_cascade(label = "Users", menu = userMenu)
        userMenu.add_command(label = "Login",  command = self.userLogin)
        
        self.password = StringVar()
        self.email = StringVar()
        

        
        
        
        self.addressInformation = self.loadAddress()
        self.dep = set()
        for i in range(len(self.addressInformation)):
            self.dep.add(self.addressInformation[i].department)
        self.dpt = []
        for i in self.dep:
            self.dpt.append(i)
        self.dpt.insert(0, "Choose a Department")
        print(self.dpt)
        
        self.levl = []
        for i in range(len(self.dpt)):
            self.levl.append({"Choose a Level"})
            for j in range(len(self.addressInformation)):
                if self.addressInformation[j].department == self.dpt[i]:
                    self.levl[i].add(self.addressInformation[j].level)
        self.lvl = []
        for i in range(len(self.levl)):
            self.lvl.append([])
            for j in self.levl[i]:
                self.lvl[i].append(j)



        self.f1 = Frame(window)
        self.f1.pack()
        f2 = Frame(window)
        f2.pack()
        

        Label(self.f1, text = "From: ").grid(row = 1, column = 1)
        Entry(self.f1, textvariable = self.email, state = DISABLED, width = 50).grid(row = 1, column = 2)
        Button(self.f1, text = "Send", command = self.send).grid(row = 1, column = 3, rowspan = 3)
        Label(self.f1, text = "To: ").grid(row = 2, column = 1)
        self.targetDepartment = StringVar()
        self.targetDepartment.set(self.dpt[0])
        self.chosenDepartment = OptionMenu(self.f1, self.targetDepartment, *self.dpt, command = self.setLevels)
        self.chosenDepartment.grid(row = 2, column = 2)
        self.targetLevel = StringVar()
        self.targetLevel.set(self.lvl[0][0])
        self.chosenLevel = OptionMenu(self.f1, self.targetLevel, *self.lvl[0])
        self.chosenLevel.grid(row = 3, column = 2)
        self.subject = StringVar()
        Label(self.f1, text = "Subject: ").grid(row = 4, column = 1)
        Entry(self.f1, textvariable = self.subject, width = 50).grid(row = 4, column = 2)
        self.message = Text(self.f1, width = 80)
        self.message.grid(row=5, column = 1, columnspan = 4)

        Button(f2, text = "Clear", command = self.clearEmail).pack()


        

        

        
        window.mainloop()

    def userLogin(self):
        #make popup window
        self.w = Toplevel()
        self.w.title("Log in Information")

        #frame1 will be used to make the entry forms
        frame1 = Frame(self.w)
        frame1.pack()
        #frame2 will house the buttons 
        frame2 = Frame(self.w)
        frame2.pack()

        
        #log in location
        Label(frame1, text="Email:").grid(row = 1, column = 1)
        Entry(frame1, width = 25, textvariable = self.email).grid(row = 1, column = 2)
        Label(frame1, text = "@").grid(row = 1, column = 3)
        self.provider = StringVar()
        self.provider.set(self.servername[0])
        OptionMenu(frame1, self.provider, *self.servername, command = self.emailProvider).grid(row = 1, column = 4)
        Label(frame1, text = "Password:"******"*").grid(row = 2, column = 2)

        #set buttons
        Button(frame2, text = "Login", command = self.login).pack(side = LEFT)
        Button(frame2, text = "Clear", command = self.clear).pack(side = LEFT)
        

    def login(self):
        useremail = self.email.get()+"@"+self.emailEndings[self.index]
        self.email.set(useremail)
        self.w.destroy()

    def clear(self):
        self.email.set("")
        self.password.set("")
        self.subject.set("")
        

    def setLevels(self, x):
        self.index = self.dpt.index(x)
        self.chosenLevel = OptionMenu(self.f1, self.targetLevel, *self.lvl[self.index])
        self.chosenLevel.grid(row = 3, column = 2)

    def loadAddress(self):
        if not os.path.isfile("emails.dat"):
            return [] # Return an empty list

        try:
            infile = open("emails.dat", "rb")
            addressList = pickle.load(infile)
        except EOFError:
            addressList = []
            
        infile.close()
        return addressList

    def clearEmail(self):
        self.toEmail.set("")
        self.subject.set("")
        self.message.delete(1.0, END)

    def emailProvider(self, provider):
        self.index = self.servername.index(provider)
        self.index -=1
        

    def send(self):
        self.msg = MIMEMultipart()
        server = smtplib.SMTP(self.server[self.index], self.port[self.index])
        server.ehlo()
        server.starttls()
        server.login(self.email.get(), self.password.get())
        for i in range(len(self.addressInformation)):
            if self.addressInformation[i].department == self.targetDepartment.get():
                self.msg['From'] = self.email.get()
                self.msg['To'] = self.addressInformation[i].email
                self.msg['Subject'] = self.subject.get()
                self.msg.attach(MIMEText(self.message.get("1.0",END), 'plain'))
                self.txt = self.msg.as_string()
                server.sendmail(self.email.get(), self.toEmail.get(), self.txt)
        server.quit()
        self.clearEmail()
Пример #49
0
class MusicPlayer(): # the main GUI class stuffs
	def __init__(self):
		self.root = Tk() # make the first window
		self.root.geometry('600x400') # set window size, it is fixed
		self.info = Frame(self.root) # frame for album art and song info
		self.controls = Frame(self.root) # frame for control buttons
		self.info.pack() # put the frames in the window
		self.controls.pack()
		self.root.title("MyTunes") # name the window 'MyTunes'
		self.music = self.readDatabase() # get all the music and put it in a circular queue
		self.current = self.music.head # the first song is the current one displayed
		pygame.mixer.init() # turn on the music player
		try:
			pygame.mixer.music.load(self.current.data.filename) # load the song so it's ready to play
		except:
			messagebox.showinfo('Error', 'There appears to be something wrong with the file for this song. Make sure it is in the correct directory and not corrupted. You may wish to delete this song and add it again') # give them an error if the file doesn't load right
		self.playing = False # not playing, keeps track of wether a song is currently playing
		self.started = False # not started, keeps track of whether a song has started, that way play just unpauses
		self.Title = StringVar() # these are stringvars for holding add song info
		self.Album = StringVar()
		self.Artist = StringVar()
		self.SFilepath = StringVar()
		self.AFilepath = StringVar()
		self.albumCover = Label(self.info, image = self.current.data.art) # these are labels with the current song's info
		self.titleLbl = Label(self.info, text = self.current.data.title)
		self.artistLbl = Label(self.info, text = self.current.data.artist)
		self.albumLbl = Label(self.info, text = self.current.data.album)
		self.albumCover.grid(rowspan = 4, columnspan = 3) # album artwork gets more space than labels do
		self.titleLbl.grid(row = 1, column = 4)
		self.artistLbl.grid(row = 2, column = 4)
		self.albumLbl.grid(row = 3, column = 4)
		self.nextBtn = Button(self.controls, text = 'Next', command = self.next) # command buttons
		self.previousBtn = Button(self.controls, text = 'Previous', command = self.previous)
		self.playBtn = Button(self.controls, text = 'Play', command = self.play)
		self.pauseBtn = Button(self.controls, text = 'Pause', command = self.pause)
		self.deleteBtn = Button(self.controls, text = 'Delete', command = self.delete)
		self.addBtn = Button(self.controls, text = 'Add', command = self.add)
		self.searchBtn = Button(self.controls, text = 'Search', command = self.search)
		self.nextBtn.grid(row = 1, column = 1) # add command buttons under song info
		self.previousBtn.grid(row = 1, column = 2)
		self.playBtn.grid(row = 1, column = 3)
		self.pauseBtn.grid(row = 1, column = 4)
		self.deleteBtn.grid(row = 1, column = 5)
		self.addBtn.grid(row = 1, column = 6)
		self.searchBtn.grid(row = 1, column = 7)
		self.root.mainloop() #start the window
		return

	# gets all the songs from the database and stores in a circular queue
	def readDatabase(self):
		dataFile = open('songs/Songs.database', 'r') # open the database
		circ = circlular()
		for line in dataFile:
			listOfInfo = line.split(',') # info seperated by commas
			circ.addToTail(song(listOfInfo[0], listOfInfo[1], listOfInfo[2], listOfInfo[3], listOfInfo[4].strip())) # last needs .strip() to remove '\n'
		dataFile.close() # have to close file
		return circ

	# moves to the next song
	def next(self):
		self.current = self.current.next # move to next song
		self.update() # update the info
		self.started = False # song doesn't auto start (weird, that'a normal for music players to do that...)
		self.playing = False # last song was stopped and new one isn't playing
		return

	# moves to previous song
	def previous(self):
		self.current = self.current.prev # move to previous
		self.update() # update the info
		self.started = False # just the same as next()
		self.playing = False
		return

	# play the loaded song, acts likenormal play buttons
	def play(self):
		if self.playing: # the song is already playing so don't do anything
			do = 'nothing'
		elif not self.started: # the music has not started and therefor isn't playing
			self.started = True # the music is now started
			pygame.mixer.music.play() # this method starts song from begining
		else: # the song has started and resumes where it is
			pygame.mixer.music.unpause() # resumes playback
		self.playing = True # no matter what the music is now playing (not really no matter what, but in any case)
		return

	# just pause it so it can be resumed
	def pause(self):
		pygame.mixer.music.pause() # this method allows for resuming music
		self.playing = False # not playing, but it is started
		return

	# remove the song from the queue
	def delete(self):
		self.current = self.current.next # move to next node
		self.current.prev = self.current.prev.prev # prev now points to deleted node's previous
		self.current.prev.next = self.current # node before deleted node's next now points to deleted node's next
		self.current = self.current.prev # now move back
		self.next() # moves forward and updates info
		return

	# dialof for adding a song
	def add(self):
		self.entrywindow = Toplevel() # aparently making another Tk() instance is bad practice, this is designed for this
		self.entrywindow.title('New Song') # title of window
		Label(self.entrywindow, text = 'Song Title').grid(row = 1, column = 1) # Labels and entry boxes
		thing1 = Entry(self.entrywindow, textvariable = self.Title)
		thing1.grid(row = 1, column = 2)
		Label(self.entrywindow, text = 'Album Title').grid(row = 2, column = 1)
		thing2 = Entry(self.entrywindow, textvariable = self.Album)
		thing2.grid(row = 2, column = 2)
		Label(self.entrywindow, text = 'Artist').grid(row = 3, column = 1)
		thing3 = Entry(self.entrywindow, textvariable = self.Artist)
		thing3.grid(row = 3, column = 2)
		Label(self.entrywindow, text = 'Song Filepath').grid(row = 4, column = 1)
		thing4 = Entry(self.entrywindow, textvariable = self.SFilepath)
		thing4.grid(row = 4, column = 2)
		Label(self.entrywindow, text = 'Artwork Filepath').grid(row = 5,  column = 1)
		thing5 = Entry(self.entrywindow, textvariable = self.AFilepath)
		thing5.grid(row = 5, column = 2)
		Button(self.entrywindow, text = 'Add', command = self.reallyAdd).grid(row = 6, columnspan = 2) # add button, calls the method that actually adds the song
		return

	# actually adds a song to the queue
	def reallyAdd(self):
		self.music.insert(self.current, song(self.Title.get(), self.Artist.get(), self.Album.get(), self.SFilepath.get(), self.AFilepath.get())) # makes a new song instance and inserts it into the queue at the current position
		self.next() # move current to new song and update info
		self.entrywindow.destroy() # kill the add song dialog
		return

	# search dialog for music, they can put info in both feilds but in that case only artist will be searched
	def search(self):
		self.find = Toplevel() # pop up
		self.find.title('Search') # title
		Label(self.find, text = 'Fill in one of the search criteria:').grid(row = 1, columnspan = 2) # labels
		Label(self.find, text = 'Artist:').grid(row = 3, column = 1)
		Label(self.find, text = 'Title:').grid(row = 2, column = 1)
		self.searchArtist = StringVar() # string vars that hold the info
		self.searchTitle = StringVar()
		searchArtistEnt = Entry(self.find, textvariable = self.searchArtist) # entry boxes
		searchTitleEnt = Entry(self.find, textvariable = self.searchTitle)
		searchArtistEnt.grid(row = 3, column = 2)
		searchTitleEnt.grid(row = 2, column = 2)
		Button(self.find, text = 'Search', command = self.findIt).grid(row = 4, columnspan = 2) # button which calls the actual method for searching
		return

	# determine which criteria to use
	def findIt(self):
		if len(self.searchArtist.get()) > 0: # use artist
			self.setCurrent(self.searchByArtist(self.searchArtist.get())) # search for song and set the current song to it
			self.find.destroy() # kill search dialog
		elif len(self.searchTitle.get()) > 0: # use title
			self.setCurrent(self.searchByTitle(self.searchTitle.get())) # search for song and set the current song to it
			self.find.destroy() # kill search dialog
		return

	# do search by artist
	def searchByArtist(self, artistName):
		start = self.current # will hold the currently displayed song node
		curr = self.current # will be changed as search continues
		match = start # default value for return value is the current node, if no results current will not actually change
		notFound = True # haven't found a match yet
		for i in range(0, self.music.size): # go through all the nodes
			if curr.data.artist == artistName:
				match = curr # we found it so set match equal to the node
				i = self.music.size + 10 # breaks for loop
				notFound = False # found it!
			curr = curr.next # move to next node
		if notFound:
			messagebox.showinfo('Not Found', 'It appears that your search criteria doesn\'t match any songs') # didn't find it so display an error
		return match # return match, defaults to current node if there wasn't a match

	# search by title
	def searchByTitle(self, aSongTitle):
		start = self.current # will hold the currently displayed song node
		curr = self.current # will be changed as search continues
		match = start # default value for return value is the current node, if no results current will not actually change
		notFound = True # haven't found a match yet
		for i in range(0, self.music.size): # go through all the nodes
			if curr.data.title == aSongTitle:
				match = curr # we found it so set match equal to the node
				i = self.music.size + 10 # breaks for loop
				notFound = False # found it!
			curr = curr.next # move to next node
		if notFound:
			messagebox.showinfo('Not Found', 'It appears that your search criteria doesn\'t match any songs') # didn't find it so display an error
		return match # return match, defaults to current node if there wasn't a match

	# set the current node
	def setCurrent(self, aNode):
		self.current = aNode # set the current node to the one passed
		self.update() # update the display info
		self.started = False # song not started
		self.playing = False # song not playing

	# update the display info
	def update(self):
		self.albumCover['image'] = self.current.data.art # change image
		self.titleLbl['text'] = self.current.data.title # change labels to current song's
		self.artistLbl['text'] = self.current.data.artist
		self.albumLbl['text'] = self.current.data.album
		try:
			pygame.mixer.music.load(self.current.data.filename) # load the song so it's ready to play
		except:
			messagebox.showinfo('Error', 'There appears to be something wrong with the file for this song. Make sure it is in the correct directory and not corrupted. You may wish to delete this song and add it again') # give them an error if the file doesn't load right
			self.delete()
			self.previous()
		return
Пример #50
0
 def _popupjoincondwindow(self, index=-1):
     if index < 0:
         cond = JoinSearchCondition(("", ""))
         tofilename = ""
     else:
         condtuple = self._getselectedfile().joincondtuples[index]
         cond = condtuple[0]
         tofilename = condtuple[1]
         
     window = Toplevel(self)
     
     title = Label(window, text="New Search Condition")
     title.grid(row=0, column=0, padx=5, pady=5, sticky=W + N)
     
     filenamelabel = Label(window, text="Target Field Name: ")
     filenamelabel.grid(row=1, column=0, padx=5, pady=5, sticky=W)
     
     filevar = StringVar(window)
     filenameinput = Combobox(window, textvariable=filevar, values=self.filelist.get(0, END), width=30)
     filenameinput.grid(row=1, column=1, columnspan=2, padx=5, pady=5, sticky=W)
     
     fromfieldlabel = Label(window, text="Field in From File: ")
     fromfieldlabel.grid(row=3, column=0, padx=5, pady=5, sticky=W)
     
     fromfields = csvhandler.getfields(self._getselectedfile().filename)
     fromfieldvar = StringVar(window)
     fieldinput = Combobox(window, textvariable=fromfieldvar, values=fromfields, width=20)
     fieldinput.grid(row=3, column=1, columnspan=2, padx=5, pady=5, sticky=W)
     
     tofieldlabel = Label(window, text="Field in Target File: ")
     tofieldlabel.grid(row=4, column=0, padx=5, pady=5, sticky=W)
     
     tofields = []
     tofieldvar = StringVar(window)
     tofieldinput = Combobox(window, textvariable=tofieldvar, values=tofields, width=20)
     tofieldinput.grid(row=4, column=1, columnspan=2, padx=5, pady=5, sticky=W)
     
     def updatetofieldinput(evt):
         if filevar.get() is not None and len(filevar.get()) > 0:
             tofields = csvhandler.getfields(filevar.get())
             window.grid_slaves(4, 1)[0].grid_forget()
             tofieldinput = Combobox(window, textvariable=tofieldvar, values=tofields, width=20)
             tofieldinput.grid(row=4, column=1, columnspan=2, padx=5, pady=5, sticky=W)
     
     filenameinput.bind('<<ComboboxSelected>>', updatetofieldinput)
     
     # init value
     filevar.set(tofilename)
     fromfieldvar.set(cond.fieldtuple[0])
     updatetofieldinput(None)
     tofieldvar.set(cond.fieldtuple[1])
     
     def _newcond():
         '''create new condition
         '''
         cond = JoinSearchCondition((fromfieldvar.get(), tofieldvar.get()))
         tofilename = filevar.get()
         
         selectedfile = self._getselectedfile()
         if index < 0:
             selectedfile.joincondtuples.append((cond, tofilename))
             
         else:
             del selectedfile.joincondtuples[index]
             selectedfile.joincondtuples[index:index] = [(cond, tofilename)]
             
         self._inflatejoincondlist(selectedfile.joincondtuples)
         
         window.destroy()
     
     okbtn = Button(window, text="Confirm", width=7, command=_newcond)
     okbtn.grid(row=6, column=1, rowspan=1, columnspan=1, sticky=E, padx=5, pady=5)
     
     clsbtn = Button(window, text="Close", width=7, command=lambda: window.destroy())
     clsbtn.grid(row=6, column=2, rowspan=1, columnspan=1, sticky=W, padx=5, pady=5)
Пример #51
0
 def _popupsearchcondwindow(self, index=-1):
     if index < 0:
         cond = ValueSearchCondition("", "")
     else:
         cond = self._getselectedfile().searchconds[index]
     
     window = Toplevel(self)
     
     title = Label(window, text="New Search Condition")
     title.grid(row=0, column=0, padx=5, pady=5, sticky=W + N)
     
     fieldlabel = Label(window, text="Field Name: ")
     fieldlabel.grid(row=1, column=0, padx=5, pady=5, sticky=W)
     
     fields = csvhandler.getfields(self._getselectedfile().filename)
     fieldvar = StringVar(window)
     fieldinput = Combobox(window, textvariable=fieldvar, values=fields, width=20)
     fieldinput.grid(row=1, column=1, columnspan=2, padx=5, pady=5, sticky=W)
     
     valuelabel = Label(window, text="Value: ")
     valuelabel.grid(row=3, column=0, padx=5, pady=5, sticky=W)
     
     valueinput = Entry(window)
     valueinput.grid(row=3, column=1, columnspan=2, padx=5, pady=5, sticky=W)
     
     minlabel = Label(window, text="Min Value: ")
     minlabel.grid(row=4, column=0, padx=5, pady=5, sticky=W)
     
     mininput = Entry(window)
     mininput.grid(row=4, column=1, columnspan=2, padx=5, pady=5, sticky=W)
     
     maxlabel = Label(window, text="Max Value: ")
     maxlabel.grid(row=5, column=0, padx=5, pady=5, sticky=W)
     
     maxinput = Entry(window)
     maxinput.grid(row=5, column=1, columnspan=2, padx=5, pady=5, sticky=W)
     
     sarchkind = IntVar()
     
     def _enablesingle():
         valueinput.config(state=NORMAL)
         mininput.config(state=DISABLED)
         maxinput.config(state=DISABLED)
         singlebutton.select()
         
     def _enablejoin():
         valueinput.config(state=DISABLED)
         mininput.config(state=NORMAL)
         maxinput.config(state=NORMAL)
         joinbutton.select()
         
     typelabel = Label(window, text="Search Type: ")
     typelabel.grid(row=2, column=0, padx=5, pady=5, sticky=W)
     
     singlebutton = Radiobutton(window, text="Single", variable=sarchkind, value=1, command=_enablesingle)
     singlebutton.grid(row=2, column=1, columnspan=1, padx=5, pady=5, sticky=W)
     
     joinbutton = Radiobutton(window, text="Range", variable=sarchkind, value=2, command=_enablejoin)
     joinbutton.grid(row=2, column=2, columnspan=1, padx=5, pady=5, sticky=W)
     
     # init value
     fieldvar.set(cond.field)
     if isinstance(cond, ValueSearchCondition):
         valueinput.insert(0, cond.val)
         _enablesingle()
     elif isinstance(cond, RangeSearchCondition):
         mininput.insert(0, cond.valmin)
         maxinput.insert(0, cond.valmax)
         _enablejoin()
         
     def _newcond():
         '''create new condition
         '''
         if sarchkind.get() == 1:
             cond = ValueSearchCondition(fieldvar.get(), valueinput.get())
         else:
             cond = RangeSearchCondition(fieldvar.get(), mininput.get(), maxinput.get())
         selectedfile = self._getselectedfile()
         if index < 0:
             selectedfile.searchconds.append(cond)
             
         else:
             del selectedfile.searchconds[index]
             selectedfile.searchconds[index:index] = [cond]
             
         self._inflatesearchcondlist(selectedfile)
         
         window.destroy()
     
     okbtn = Button(window, text="Confirm", width=7, command=_newcond)
     okbtn.grid(row=6, column=1, rowspan=1, columnspan=1, sticky=E, padx=5, pady=5)
     
     clsbtn = Button(window, text="Close", width=7, command=lambda: window.destroy())
     clsbtn.grid(row=6, column=2, rowspan=1, columnspan=1, sticky=E, padx=5, pady=5)
Пример #52
0
class CFGEditor(object):
    """
    A dialog window for creating and editing context free grammars.
    ``CFGEditor`` imposes the following restrictions:

    - All nonterminals must be strings consisting of word
      characters.
    - All terminals must be strings consisting of word characters
      and space characters.
    """
    # Regular expressions used by _analyze_line.  Precompile them, so
    # we can process the text faster.
    ARROW = SymbolWidget.SYMBOLS['rightarrow']
    _LHS_RE = re.compile(r"(^\s*\w+\s*)(->|("+ARROW+"))")
    _ARROW_RE = re.compile("\s*(->|("+ARROW+"))\s*")
    _PRODUCTION_RE = re.compile(r"(^\s*\w+\s*)" +              # LHS
                                "(->|("+ARROW+"))\s*" +        # arrow
                                r"((\w+|'[\w ]*'|\"[\w ]*\"|\|)\s*)*$") # RHS
    _TOKEN_RE = re.compile("\\w+|->|'[\\w ]+'|\"[\\w ]+\"|("+ARROW+")")
    _BOLD = ('helvetica', -12, 'bold')

    def __init__(self, parent, cfg=None, set_cfg_callback=None):
        self._parent = parent
        if cfg is not None: self._cfg = cfg
        else: self._cfg = ContextFreeGrammar(Nonterminal('S'), [])
        self._set_cfg_callback = set_cfg_callback

        self._highlight_matching_nonterminals = 1

        # Create the top-level window.
        self._top = Toplevel(parent)
        self._init_bindings()

        self._init_startframe()
        self._startframe.pack(side='top', fill='x', expand=0)
        self._init_prodframe()
        self._prodframe.pack(side='top', fill='both', expand=1)
        self._init_buttons()
        self._buttonframe.pack(side='bottom', fill='x', expand=0)

        self._textwidget.focus()

    def _init_startframe(self):
        frame = self._startframe = Frame(self._top)
        self._start = Entry(frame)
        self._start.pack(side='right')
        Label(frame, text='Start Symbol:').pack(side='right')
        Label(frame, text='Productions:').pack(side='left')
        self._start.insert(0, self._cfg.start().symbol())

    def _init_buttons(self):
        frame = self._buttonframe = Frame(self._top)
        Button(frame, text='Ok', command=self._ok,
               underline=0, takefocus=0).pack(side='left')
        Button(frame, text='Apply', command=self._apply,
               underline=0, takefocus=0).pack(side='left')
        Button(frame, text='Reset', command=self._reset,
               underline=0, takefocus=0,).pack(side='left')
        Button(frame, text='Cancel', command=self._cancel,
               underline=0, takefocus=0).pack(side='left')
        Button(frame, text='Help', command=self._help,
               underline=0, takefocus=0).pack(side='right')

    def _init_bindings(self):
        self._top.title('CFG Editor')
        self._top.bind('<Control-q>', self._cancel)
        self._top.bind('<Alt-q>', self._cancel)
        self._top.bind('<Control-d>', self._cancel)
        #self._top.bind('<Control-x>', self._cancel)
        self._top.bind('<Alt-x>', self._cancel)
        self._top.bind('<Escape>', self._cancel)
        #self._top.bind('<Control-c>', self._cancel)
        self._top.bind('<Alt-c>', self._cancel)

        self._top.bind('<Control-o>', self._ok)
        self._top.bind('<Alt-o>', self._ok)
        self._top.bind('<Control-a>', self._apply)
        self._top.bind('<Alt-a>', self._apply)
        self._top.bind('<Control-r>', self._reset)
        self._top.bind('<Alt-r>', self._reset)
        self._top.bind('<Control-h>', self._help)
        self._top.bind('<Alt-h>', self._help)
        self._top.bind('<F1>', self._help)

    def _init_prodframe(self):
        self._prodframe = Frame(self._top)

        # Create the basic Text widget & scrollbar.
        self._textwidget = Text(self._prodframe, background='#e0e0e0',
                                exportselection=1)
        self._textscroll = Scrollbar(self._prodframe, takefocus=0,
                                     orient='vertical')
        self._textwidget.config(yscrollcommand = self._textscroll.set)
        self._textscroll.config(command=self._textwidget.yview)
        self._textscroll.pack(side='right', fill='y')
        self._textwidget.pack(expand=1, fill='both', side='left')

        # Initialize the colorization tags.  Each nonterminal gets its
        # own tag, so they aren't listed here.
        self._textwidget.tag_config('terminal', foreground='#006000')
        self._textwidget.tag_config('arrow', font='symbol')
        self._textwidget.tag_config('error', background='red')

        # Keep track of what line they're on.  We use that to remember
        # to re-analyze a line whenever they leave it.
        self._linenum = 0

        # Expand "->" to an arrow.
        self._top.bind('>', self._replace_arrows)

        # Re-colorize lines when appropriate.
        self._top.bind('<<Paste>>', self._analyze)
        self._top.bind('<KeyPress>', self._check_analyze)
        self._top.bind('<ButtonPress>', self._check_analyze)

        # Tab cycles focus. (why doesn't this work??)
        def cycle(e, textwidget=self._textwidget):
            textwidget.tk_focusNext().focus()
        self._textwidget.bind('<Tab>', cycle)

        prod_tuples = [(p.lhs(),[p.rhs()]) for p in self._cfg.productions()]
        for i in range(len(prod_tuples)-1,0,-1):
            if (prod_tuples[i][0] == prod_tuples[i-1][0]):
                if () in prod_tuples[i][1]: continue
                if () in prod_tuples[i-1][1]: continue
                print(prod_tuples[i-1][1])
                print(prod_tuples[i][1])
                prod_tuples[i-1][1].extend(prod_tuples[i][1])
                del prod_tuples[i]

        for lhs, rhss in prod_tuples:
            print(lhs, rhss)
            s = '%s ->' % lhs
            for rhs in rhss:
                for elt in rhs:
                    if isinstance(elt, Nonterminal): s += ' %s' % elt
                    else: s += ' %r' % elt
                s += ' |'
            s = s[:-2] + '\n'
            self._textwidget.insert('end', s)

        self._analyze()

#         # Add the producitons to the text widget, and colorize them.
#         prod_by_lhs = {}
#         for prod in self._cfg.productions():
#             if len(prod.rhs()) > 0:
#                 prod_by_lhs.setdefault(prod.lhs(),[]).append(prod)
#         for (lhs, prods) in prod_by_lhs.items():
#             self._textwidget.insert('end', '%s ->' % lhs)
#             self._textwidget.insert('end', self._rhs(prods[0]))
#             for prod in prods[1:]:
#                 print '\t|'+self._rhs(prod),
#                 self._textwidget.insert('end', '\t|'+self._rhs(prod))
#             print
#             self._textwidget.insert('end', '\n')
#         for prod in self._cfg.productions():
#             if len(prod.rhs()) == 0:
#                 self._textwidget.insert('end', '%s' % prod)
#         self._analyze()

#     def _rhs(self, prod):
#         s = ''
#         for elt in prod.rhs():
#             if isinstance(elt, Nonterminal): s += ' %s' % elt.symbol()
#             else: s += ' %r' % elt
#         return s

    def _clear_tags(self, linenum):
        """
        Remove all tags (except ``arrow`` and ``sel``) from the given
        line of the text widget used for editing the productions.
        """
        start = '%d.0'%linenum
        end = '%d.end'%linenum
        for tag in self._textwidget.tag_names():
            if tag not in ('arrow', 'sel'):
                self._textwidget.tag_remove(tag, start, end)

    def _check_analyze(self, *e):
        """
        Check if we've moved to a new line.  If we have, then remove
        all colorization from the line we moved to, and re-colorize
        the line that we moved from.
        """
        linenum = int(self._textwidget.index('insert').split('.')[0])
        if linenum != self._linenum:
            self._clear_tags(linenum)
            self._analyze_line(self._linenum)
            self._linenum = linenum

    def _replace_arrows(self, *e):
        """
        Replace any ``'->'`` text strings with arrows (char \\256, in
        symbol font).  This searches the whole buffer, but is fast
        enough to be done anytime they press '>'.
        """
        arrow = '1.0'
        while True:
            arrow = self._textwidget.search('->', arrow, 'end+1char')
            if arrow == '': break
            self._textwidget.delete(arrow, arrow+'+2char')
            self._textwidget.insert(arrow, self.ARROW, 'arrow')
            self._textwidget.insert(arrow, '\t')

        arrow = '1.0'
        while True:
            arrow = self._textwidget.search(self.ARROW, arrow+'+1char',
                                            'end+1char')
            if arrow == '': break
            self._textwidget.tag_add('arrow', arrow, arrow+'+1char')

    def _analyze_token(self, match, linenum):
        """
        Given a line number and a regexp match for a token on that
        line, colorize the token.  Note that the regexp match gives us
        the token's text, start index (on the line), and end index (on
        the line).
        """
        # What type of token is it?
        if match.group()[0] in "'\"": tag = 'terminal'
        elif match.group() in ('->', self.ARROW): tag = 'arrow'
        else:
            # If it's a nonterminal, then set up new bindings, so we
            # can highlight all instances of that nonterminal when we
            # put the mouse over it.
            tag = 'nonterminal_'+match.group()
            if tag not in self._textwidget.tag_names():
                self._init_nonterminal_tag(tag)

        start = '%d.%d' % (linenum, match.start())
        end = '%d.%d' % (linenum, match.end())
        self._textwidget.tag_add(tag, start, end)

    def _init_nonterminal_tag(self, tag, foreground='blue'):
        self._textwidget.tag_config(tag, foreground=foreground,
                                    font=CFGEditor._BOLD)
        if not self._highlight_matching_nonterminals:
            return
        def enter(e, textwidget=self._textwidget, tag=tag):
            textwidget.tag_config(tag, background='#80ff80')
        def leave(e, textwidget=self._textwidget, tag=tag):
            textwidget.tag_config(tag, background='')
        self._textwidget.tag_bind(tag, '<Enter>', enter)
        self._textwidget.tag_bind(tag, '<Leave>', leave)

    def _analyze_line(self, linenum):
        """
        Colorize a given line.
        """
        # Get rid of any tags that were previously on the line.
        self._clear_tags(linenum)

        # Get the line line's text string.
        line = self._textwidget.get(repr(linenum)+'.0', repr(linenum)+'.end')

        # If it's a valid production, then colorize each token.
        if CFGEditor._PRODUCTION_RE.match(line):
            # It's valid; Use _TOKEN_RE to tokenize the production,
            # and call analyze_token on each token.
            def analyze_token(match, self=self, linenum=linenum):
                self._analyze_token(match, linenum)
                return ''
            CFGEditor._TOKEN_RE.sub(analyze_token, line)
        elif line.strip() != '':
            # It's invalid; show the user where the error is.
            self._mark_error(linenum, line)

    def _mark_error(self, linenum, line):
        """
        Mark the location of an error in a line.
        """
        arrowmatch = CFGEditor._ARROW_RE.search(line)
        if not arrowmatch:
            # If there's no arrow at all, highlight the whole line.
            start = '%d.0' % linenum
            end = '%d.end' % linenum
        elif not CFGEditor._LHS_RE.match(line):
            # Otherwise, if the LHS is bad, highlight it.
            start = '%d.0' % linenum
            end = '%d.%d' % (linenum, arrowmatch.start())
        else:
            # Otherwise, highlight the RHS.
            start = '%d.%d' % (linenum, arrowmatch.end())
            end = '%d.end' % linenum

        # If we're highlighting 0 chars, highlight the whole line.
        if self._textwidget.compare(start, '==', end):
            start = '%d.0' % linenum
            end = '%d.end' % linenum
        self._textwidget.tag_add('error', start, end)

    def _analyze(self, *e):
        """
        Replace ``->`` with arrows, and colorize the entire buffer.
        """
        self._replace_arrows()
        numlines = int(self._textwidget.index('end').split('.')[0])
        for linenum in range(1, numlines+1):  # line numbers start at 1.
            self._analyze_line(linenum)

    def _parse_productions(self):
        """
        Parse the current contents of the textwidget buffer, to create
        a list of productions.
        """
        productions = []

        # Get the text, normalize it, and split it into lines.
        text = self._textwidget.get('1.0', 'end')
        text = re.sub(self.ARROW, '->', text)
        text = re.sub('\t', ' ', text)
        lines = text.split('\n')

        # Convert each line to a CFG production
        for line in lines:
            line = line.strip()
            if line=='': continue
            productions += parse_cfg_production(line)
            #if line.strip() == '': continue
            #if not CFGEditor._PRODUCTION_RE.match(line):
            #    raise ValueError('Bad production string %r' % line)
            #
            #(lhs_str, rhs_str) = line.split('->')
            #lhs = Nonterminal(lhs_str.strip())
            #rhs = []
            #def parse_token(match, rhs=rhs):
            #    token = match.group()
            #    if token[0] in "'\"": rhs.append(token[1:-1])
            #    else: rhs.append(Nonterminal(token))
            #    return ''
            #CFGEditor._TOKEN_RE.sub(parse_token, rhs_str)
            #
            #productions.append(Production(lhs, *rhs))

        return productions

    def _destroy(self, *e):
        if self._top is None: return
        self._top.destroy()
        self._top = None

    def _ok(self, *e):
        self._apply()
        self._destroy()

    def _apply(self, *e):
        productions = self._parse_productions()
        start = Nonterminal(self._start.get())
        cfg = ContextFreeGrammar(start, productions)
        if self._set_cfg_callback is not None:
            self._set_cfg_callback(cfg)

    def _reset(self, *e):
        self._textwidget.delete('1.0', 'end')
        for production in self._cfg.productions():
            self._textwidget.insert('end', '%s\n' % production)
        self._analyze()
        if self._set_cfg_callback is not None:
            self._set_cfg_callback(self._cfg)

    def _cancel(self, *e):
        try: self._reset()
        except: pass
        self._destroy()

    def _help(self, *e):
        # The default font's not very legible; try using 'fixed' instead.
        try:
            ShowText(self._parent, 'Help: Chart Parser Demo',
                     (_CFGEditor_HELP).strip(), width=75, font='fixed')
        except:
            ShowText(self._parent, 'Help: Chart Parser Demo',
                     (_CFGEditor_HELP).strip(), width=75)
Пример #53
0
 def destroy(self, event=None):
     "Put the focus back to the parent window and destroy the dialod"
     if self.had_focus is not None:
         self.had_focus.focus_set()
     Toplevel.destroy(self)
Пример #54
-1
class SpeciesListDialog:
    def __init__(self, parent):
        self.parent = parent
        self.gui = Toplevel(parent.guiRoot)
        self.gui.grab_set()
        self.gui.focus()

        self.gui.columnconfigure(0, weight=1)
        self.gui.rowconfigure(1, weight=1)

        Label(self.gui, text="Registered Species:").grid(row=0, column=0, pady=5, padx=5, sticky="w")
        self.listRegisteredSpecies = Listbox(self.gui, width=70)
        self.buttonAdd = Button(self.gui, text=" + ")
        self.buttonDel = Button(self.gui, text=" - ")
        self.listRegisteredSpecies.grid(row=1, column=0, columnspan=3, sticky="nswe", pady=5, padx=5)
        self.buttonAdd.grid(row=2, column=1, pady=5, padx=5)
        self.buttonDel.grid(row=2, column=2, pady=5, padx=5)

        # Set (minimum + max) Window size
        self.gui.update()
        self.gui.minsize(self.gui.winfo_width(), self.gui.winfo_height())
        #         self.gui.maxsize(self.gui.winfo_width(), self.gui.winfo_height())

        self.actionUpdate(None)
        self.gui.bind("<<Update>>", self.actionUpdate)
        self.gui.protocol("WM_DELETE_WINDOW", self.actionClose)

        self.buttonDel.bind("<ButtonRelease>", self.actionDel)
        self.buttonAdd.bind("<ButtonRelease>", self.actionAdd)

        self.gui.mainloop()

    def actionClose(self):
        self.parent.guiRoot.event_generate("<<Update>>", when="tail")
        self.gui.destroy()

    def actionUpdate(self, event):
        self.listRegisteredSpecies.delete(0, "end")
        for (taxid, name) in self.parent.optimizer.speciesList:
            self.listRegisteredSpecies.insert("end", taxid + ": " + name)

    def actionDel(self, event):
        try:
            selection = self.listRegisteredSpecies.selection_get()
            selectionSplit = selection.split(": ")
            self.parent.optimizer.speciesList.remove((selectionSplit[0], selectionSplit[1]))
            self.gui.event_generate("<<Update>>")
        except tkinter.TclError:
            # no selection
            pass

    def actionAdd(self, Event):
        SpeciesSearchDialog(self.parent, self)