Esempio n. 1
1
class OptionWindow(Toplevel):
    def __call__(self, options=[], display=True):
        self.options = options

        self.listbox.delete(0, END)
        for key, value in options:
            self.listbox.insert(END, key)

        if display:
            self.display()

    def __init__(self):
        Toplevel.__init__(self, master=root)
        self.options = None
        self.title('Matches')

        self.listbox = Listbox(master=self)

        self.listbox.pack(expand=True, fill=BOTH, side=TOP)
        self.listbox.focus_set()
        self.listbox.activate(0)
        self.listbox.selection_set(0)

        self.listbox.config(width=50)

        self.listbox.bind('<Key-h>',
                          lambda event: self.listbox.event_generate('<Left>'))

        self.listbox.bind('<Key-l>',
                          lambda event: self.listbox.event_generate('<Right>'))

        self.listbox.bind('<Key-k>',
                          lambda event: self.listbox.event_generate('<Up>'))

        self.listbox.bind('<Key-j>',
                          lambda event: self.listbox.event_generate('<Down>'))

        self.listbox.bind('<Escape>', lambda event: self.close())
        self.protocol("WM_DELETE_WINDOW", self.close)
        self.transient(root)
        self.withdraw()

    def display(self):
        self.grab_set()
        self.deiconify()
        self.listbox.focus_set()
        # self.wait_window(self)

    def close(self):
        # When calling destroy or withdraw without
        # self.deoiconify it doesnt give back
        # the focus to the parent window.

        self.deiconify()
        self.grab_release()
        self.withdraw()
Esempio n. 2
0
class   Application(Frame): 
    def __init__(self,  master=None):
        Frame.__init__(self, master)    
        self.grid(sticky=N+S+E+W)   
        self.mainframe()

    def mainframe(self):                
        self.data = Listbox(self, bg='red')
        self.scrollbar = Scrollbar(self.data, orient=VERTICAL)
        self.data.config(yscrollcommand=self.scrollbar.set)
        self.scrollbar.config(command=self.data.yview)

        for i in range(1000):
            self.data.insert(END, str(i))

        self.run = Button(self, text="run")
        self.stop = Button(self, text="stop")
    
        self.data.grid(row=0, column=0, rowspan=4,
                       columnspan=2, sticky=N+E+S+W)
        self.data.columnconfigure(0, weight=1)
    
        self.run.grid(row=4,column=0,sticky=EW)
        self.stop.grid(row=4,column=1,sticky=EW)
    
        self.scrollbar.grid(column=2, sticky=N+S)
Esempio n. 3
0
class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.grid(sticky=N + S + E + W)
        self.mainframe()

    def mainframe(self):
        self.data = Listbox(self, bg='red')
        self.scrollbar = Scrollbar(self.data, orient=VERTICAL)
        self.data.config(yscrollcommand=self.scrollbar.set)
        self.scrollbar.config(command=self.data.yview)

        for i in range(1000):
            self.data.insert(END, str(i))

    self.run = Button(self, text="run")
    self.stop = Button(self, text="stop")

    self.data.grid(row=0,
                   column=0,
                   rowspan=4,
                   columnspan=2,
                   sticky=N + E + S + W)
    self.data.columnconfigure(0, weight=1)

    self.run.grid(row=4, column=0, sticky=EW)
    self.stop.grid(row=4, column=1, sticky=EW)

    self.scrollbar.grid(column=2, sticky=N + S)
Esempio n. 4
0
 def results(self):
     if self.wrong:
         lb_wrong = Listbox()
         lb_wrong.insert(END, '    [НЕПРАВИЛЬНО]:')
         lb_wrong.insert(END, '')
         for i in self.wrong:
             lb_wrong.insert(END, i)
             lb_wrong.config(fg='#FF79E8', bg='#4D4D4D')
         if self.correct:
             lb_wrong.pack(pady=15, side=LEFT)
         else:
             lb_wrong.pack(pady=15)
     if self.correct:
         lb_correct = Listbox()
         lb_correct.insert(END, '      [ПРАВИЛЬНО]:')
         lb_correct.insert(END, '')
         for j in self.correct:
             lb_correct.insert(END, j)
             lb_correct.config(fg='#11FF00', bg='#4D4D4D')
         if self.wrong:
             lb_correct.pack(pady=15, side=RIGHT)
         else:
             lb_correct.pack(pady=15)
     else:
         self.finish.config(text='Нету правильных', fg='#FF79E8')
     self.look.config(state=DISABLED)
Esempio n. 5
0
def year_window():
    def click():
        entered_text = yearListbox.get(ACTIVE)
        output.delete(0.0, END)
        output.insert(END, individuals_year((yearListbox.get(ACTIVE))))
        
    top = Toplevel()
    top.title("Individuals Year Function")
    top.geometry("605x350+440+470")

    Label (top, text = "Returns the number of individuals sighted in a year", anchor = "w").pack(fill = "both")
    Label (top, text = "Year:", anchor = "w").pack(fill = "both")


    frame = Frame(top)
    frame.pack(anchor = "w")
    yearListbox = Listbox(frame, exportselection = 0, width = 30)
    yearListbox.pack(side = "left", fill = "y")

    scrollbar = Scrollbar(frame, orient = "vertical")
    scrollbar.config(command = yearListbox.yview)
    scrollbar.pack(side = "right", fill = "y")

    yearListbox.config(yscrollcommand = scrollbar.set)
    
    years = years_list()
    years.sort()
    for year in years:
        yearListbox.insert(END, year)


    Button (top, text = "Check record", width = 12, command = click).pack(anchor = "w")

    output = Text(top, width = 75, height = 6, wrap = WORD, background = "white")
    output.pack(anchor = "w")
def ShowResult(m,eid):
    m.destroy()
    root=Tk()
    root.title("Result")
    root.geometry("500x400")

    lframe=Frame(root)
    lframe.pack(side=LEFT)
    load=Image.open("index.png")
    render=ImageTk.PhotoImage(load)
    img=Label(lframe,image=render)
    img.image=render
    img.pack(side=LEFT)
    
    cFrame=Frame(root)
    cFrame.pack(side=LEFT)
    Label(cFrame,text="Panno:",font = "Times 17 bold").pack()
    Label(cFrame,text="").pack()

    listFrame=Frame(cFrame)
    listFrame.pack()
    scrollbarE=Scrollbar(listFrame)
    listBoxPanno=Listbox(listFrame,width=30,selectmode=BROWSE)
    listBoxPanno.config(yscrollcommand=scrollbarE.set)
    scrollbarE.config(command=listBoxPanno.yview)
    listBoxPanno.pack(expand = True, fill = BOTH,side=LEFT)
    scrollbarE.pack(fill = BOTH,side=RIGHT)
    db.getAllPanno(listBoxPanno)
    listBoxPanno.bind('<Double-Button-1>', lambda x:Panno_c(root,eid,listBoxPanno))
    Label(cFrame,text="").pack()
    Button(cFrame,text="Back",font = "Times 10 bold",command=lambda :see_After(root) ).pack(expand = True, fill = BOTH)
    root.mainloop()
Esempio n. 7
0
def create_window_category_change():
    '''Создаем окно, где можно
    добавлять свой пукт расходов или доходов
    '''
    global lbox, entry
    top = Toplevel()
    #фокусируем наше окно
    #top.focus_set()
    #делаем его модальным(чтобы нельзя было переключиться на главное окно)
    #top.grab_set()
    #мы задаем приложению команду, что пока не будет закрыто окно top пользоваться другим окном будет нельзя.
    #top.wait_window()
    lbox_var = StringVar(top)
    new_category = StringVar(top)
    lbox = Listbox(top, selectmode=EXTENDED)
    lbox.pack(side=LEFT)
    scroll = Scrollbar(top, command=lbox.yview)
    scroll.pack(side=LEFT, fill=Y)
    lbox.config(yscrollcommand=scroll.set)
    f = Frame(top)
    f.pack(side=LEFT, padx=10)
    entry = Entry(f)
    entry.pack(anchor=N)
    category_add = Button(f, text="Добавить", command=append_category)
    category_add.pack(fill=X)
    category_del = Button(f, text="Удалить", command=del_category)
    category_del.pack(fill=X)
    update_category_list()
Esempio n. 8
0
    def task_list(self):
        fr = Frame(self)
        fr_top = Frame(fr)
        task_lbx = Listbox(fr_top)
        task_lbx.pack(anchor="center",
                      fill="both",
                      expand=True,
                      padx=3,
                      pady=3)
        self._task_box = task_lbx

        fr_bot = Frame(fr, height='2')
        b1 = Menubutton(fr_bot, text='실행메뉴')
        b1.menu = Menu(b1, tearoff=0)
        b1['menu'] = b1.menu
        b1.menu.add_command(label='실행', command=self.convert)
        b1.menu.add_command(label='비우기', command=self.delete_task_item)
        b1.pack()

        fr_top.pack(side='top', fill='both', expand=True)
        fr_bot.pack(side='bottom', fill='x')
        task_lbx.config(highlightcolor='green',
                        font=('굴림체', 10),
                        activestyle='none',
                        selectmode='extended')

        self.task_lbx = task_lbx

        return fr
Esempio n. 9
0
def Listbox(root, lists=[], **options):

    Lb = TkListbox(root)
    for idx, val in enumerate(lists):
        Lb.insert(idx, val)

    Lb.config(height=0)
    Lb.pack()
    def imprimePontos():

        def exibeValor():
            print(combo.get())
            print(ponto)
            Graph = bpg.Equation(Field, ponto[1], ponto[2], ponto[0])
            Graph.fill_x_and_y_lists()

            if combo.get() == "Ponto de interceptação":
                Graph.plot_graph_one()

            elif combo.get() == "Posição x Tempo":
                Graph.plot_graph_two_Y()
                Graph.plot_graph_two_X()

            elif combo.get() == "Velocidade x Tempo":
                Graph.plot_graph_threeY()
                Graph.plot_graph_threeX()

            elif combo.get() == "Acelereração x Tempo":
                Graph.plot_graph_fourY()
                Graph.plot_graph_fourX()

            elif combo.get() == "Distancia x Tempo":
                Graph.plot_graph_five()

        if len(Field.Interception_Index_Points) != 0:
            nova_janela = tk.Tk()
            nova_janela.title("Bomba Patch 2020 ATUALIZADO")
            nova_janela.geometry("1100x600")

            mostraPontos = Listbox(nova_janela, width=80, height=30, font=("Helvetica", 10), highlightthickness=2, selectbackground="red")
            mostraPontos.place(relx=0.7, rely=0.5, anchor=CENTER)
            mostraPontos.delete(1, END)
            mostraPontos.bind('<<ListboxSelect>>', imprime)

            scrollbar = tk.Scrollbar(nova_janela, orient="vertical")
            scrollbar.config(command=mostraPontos.yview)
            scrollbar.pack(side="right", fill="y")
            mostraPontos.config(yscrollcommand=scrollbar.set)

            if bpf.get_interception_points(Field, mostraPontos):
                combo = Combobox(nova_janela, width=40)
                combo['values'] = (
                "Ponto de interceptação", "Posição x Tempo", "Velocidade x Tempo", "Acelereração x Tempo",
                "Distancia x Tempo")
                combo.current(0)  # definimos o valor padrão!
                combo.pack()
                combo.place(x=280, y=300, anchor=CENTER)

                botao = tk.Button(nova_janela, text = "Mostrar Gráfico",  width=12, height=2,command = exibeValor)
                botao.pack()
                botao.place(x=280, y=350, anchor=CENTER)

            nova_janela.mainloop()
        else:
            messagebox.showinfo("Aviso", "O robô NÃO intercepta a bola")
Esempio n. 11
0
class Configuration():
    def __init__(self, db):

        self.main = Tk()
        self.main.title("Configuration")
        self.db = db

        Button(self.main, text='New tab', command=self.NewTab).grid(row=0,
                                                                    column=0)

        self.maindaily_listbox = Listbox(self.main, exportselection=0)
        self.maindaily_listbox.grid(row=1, column=0)
        self.ls = []
        self.d_tabs = self.db.get_tasks_for_table_('Tabs')
        for tab in self.d_tabs:
            self.maindaily_listbox.insert(END, tab)
        self.maindaily_listbox.config(width=20, height=len(self.d_tabs) + 1)

        self.EntryTask = Entry(self.main)
        self.EntryTask.grid(row=2, column=0)
        self.EntryTask.insert(0, 'new name')

        Button(self.main, text="Rename", command=self.Rename).grid(row=3,
                                                                   column=0)
        Button(self.main, text="Delete", command=self.Delete).grid(row=4,
                                                                   column=0)

    def Rename(self):
        NewName = str(self.EntryTask.get())
        Tab2Update = self.maindaily_listbox.get(
            self.maindaily_listbox.curselection())

        if len(NewName) > 0 and NewName != 'new name':
            for tab in self.d_tabs:
                if tab == Tab2Update:
                    self.db.__update_table__('Tabs', 'tab_id', NewName,
                                             'tab_id', Tab2Update)
        self.main.destroy()

    def Delete(self):
        Tab2Delete = self.maindaily_listbox.get(
            self.maindaily_listbox.curselection())
        self.db.__delete_from_table__('Tabs', Tab2Delete,
                                      self.d_tabs[Tab2Delete])
        self.main.destroy()

    def NewTab(self):
        tab = simpledialog.askstring("askstring", "Enter New Tab")
        position_id = 0
        for tab in self.d_tabs:
            if int(self.d_tabs[tab]) > position_id:
                position_id = int(self.d_tabs[tab])
        self.db.__insert_in_table__('Tabs', tab, str(position_id + 1))
        self.maindaily_listbox.insert(END, tab)
        self.maindaily_listbox.config(width=20, height=len(self.d_tabs) + 1)
Esempio n. 12
0
class AskColumns:

    def __init__(self, master, all_cols):

        self.master = master
        self.master.deiconify()
        self.frame = Frame(self.master)
        self.all_cols = all_cols

        self.prompt = 'Please select which columns will be necessary for ' \
                      'the output excel file.'
        self.label = Label(master, text=self.prompt,
                           width=35,
                           wraplength=150,
                           justify='center').pack()
        self.add_listbox()
        '''submit_button = Button(self,
                               text='Submit',
                               command=self.update_vals())
        submit_button.pack()'''
        self.frame.pack()

    def add_listbox(self):

        self.listbox_frame = Frame(self.master)

        # create a scroll bar for the list box
        scrollbar = Scrollbar(self.listbox_frame)
        scrollbar.pack(side='right', fill='y')

        # create list box
        self.listbox = Listbox(self.listbox_frame,
                               selectmode='multiple',
                               exportselection=0)
        # add column names to the list box
        for col_name in self.all_cols:
            self.listbox.insert(self.all_cols.index(col_name), col_name)
        self.listbox.pack(side='left', fill='y')

        # pack the listbox
        self.listbox_frame.pack()

        # attach listbox to scrollbar
        self.listbox.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.listbox.yview)

    def update_vals(self):

        chosen_lines = self.listbox.curselection()
        cols = [self.all_cols[line] for line in chosen_lines]

        self.master.quit()

        return cols
Esempio n. 13
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()
Esempio n. 14
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        sbar = Scrollbar(self)
        list = Listbox(self)
        sbar.config(command=list.yview)
        list.config(yscrollcommand=sbar.set)
        sbar.pack(side='right', fill='y')
        list.pack(side='left', expand='yes', fill='both')
        list.bind('<<ListboxSelect>>', self._on_listbox_click)

        self.__list_click_callback = None
        self.__list = list
        self.__sbar = sbar
Esempio n. 15
0
  def _add_variable(self, name, default):
    if name != "":
      self.variable[name] = default
    print(self.variable)
    variablelist = Listbox(self._master, width =15, height=5)
    variablelist.place(x=20,y=420)
    scrollbar = Scrollbar(self._master)
    scrollbar.config(command=variablelist.yview)
    scrollbar.place(x=145,y=421, height=90)

    variablelist.config(yscrollcommand=scrollbar.set)
    for x in self.variable:
      variablelist.insert("end", x+" : "+self.variable[x])
Esempio n. 16
0
 def ScroolbarX(self,
                listbox: tk.Listbox,
                x=0,
                y=0,
                width=None,
                height=None,
                frame=None):
     if frame is None: frame = self.frame
     scroll = tk.Scrollbar(frame)
     listbox.config(xscrollcommand=scroll.set)
     scroll.config(command=listbox.xview)
     scroll.place(x=x, y=y, width=width, height=height)
     return scroll
Esempio n. 17
0
 def makeWidgets(self, options_):
     labList = Listbox(self, relief=SUNKEN)
     sbar = Scrollbar(self)
     sbar.config(command=labList.yview)                    # xlink sbar and list
     labList.config(yscrollcommand=sbar.set)               # move one moves other
     sbar.pack(side=RIGHT, fill=Y)                         # pack first=clip last
     labList.pack(side=LEFT, expand=YES, fill=BOTH)        # list clipped first
     pos = 0
     for label in options_:                                 # add to listbox
         labList.insert(pos, label)                        # or insert(END,label)
         pos += 1                                          # or enumerate(options)
     #list.config(selectmode=SINGLE, setgrid=1)            # select,resize modes
     labList.bind('<Double-1>', self.handleList)           # set event handler
     self.listbox = labList
Esempio n. 18
0
 def create_tasks_list(self, person: Person):
     tasks_listbox = Listbox(self.top, height=20)
     scroll = tkinter.Scrollbar(command=tasks_listbox.yview)
     tasks_listbox.bind(
         '<Double-Button>',
         lambda event: self.on_task_select(tasks_listbox, person))
     tasks_listbox.config(yscrollcommand=scroll.set)
     self.fill_listbox(person.tasks_schedule, tasks_listbox)
     person.tasks_schedule.listeners.append(
         lambda: self.fill_listbox(person.tasks_schedule, tasks_listbox))
     tasks_listbox.pack(side="left")
     scroll.pack(side="left", fill=tkinter.Y)
     self.list_boxes.append(tasks_listbox)
     self.list_boxes.append(scroll)
Esempio n. 19
0
    def draw(self, root):
        playerFrame = Frame(root, bg='green', bd=2)
        enemyFrame = Frame(root, bg='green', bd=2, cursor='plus')

        MakeMap(playerFrame, self.playerButtons, self.userSocket,
                self.fontStyle, False)
        MakeMap(enemyFrame, self.enemyButtons, self.userSocket, self.fontStyle,
                True)

        chatFrame = Frame(root, bg='white', bd=2)
        self.infoLabel = Label(chatFrame,
                               bg='grey',
                               fg='black',
                               text='GameInfo')

        chatBox = Listbox(chatFrame)
        self.chatList = chatBox
        entry = Entry(chatFrame)
        entry.insert(0, 'Write your text')

        def click(event):
            entry.delete(0, END)

        entry.bind('<Button-1>', click)

        sendBtn = Button(chatFrame,
                         text='Send Message',
                         bg='white',
                         fg='black',
                         cursor='hand1')

        sendBtn.bind('<Button-1>', MakeChatCallback(entry, self.userSocket))

        entry.bind('<Return>', MakeChatCallback(entry, self.userSocket))

        scrollbar = Scrollbar(chatFrame)
        scrollbar.pack(side=RIGHT, fill=Y)

        chatBox.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=chatBox.yview)

        self.infoLabel.pack(fill=X)
        chatBox.pack(expand=1, fill=BOTH)
        entry.pack(fill=X)
        sendBtn.pack(fill=X)

        playerFrame.grid(row=0, column=0, sticky='nsew')
        enemyFrame.grid(row=0, column=1, sticky='nsew')
        chatFrame.grid(row=0, column=2, sticky='nsew')
Esempio n. 20
0
class ScrollingListbox(Frame):
    def __init__(self, master, height=10, width=45):
        super(ScrollingListbox, self).__init__(master)

        self.listbox = Listbox(self,
                               selectmode='extended',
                               height=height,
                               width=width)
        self.listbox.grid(column=0, row=0)

        self.scrollbar = Scrollbar(self)
        self.scrollbar.grid(column=1, row=0, sticky='ns')

        self.listbox.config(yscrollcommand=self.scrollbar.set)
        self.scrollbar.config(command=self.listbox.yview)
Esempio n. 21
0
 def init_view(self, person):
     available_tasks_listbox = Listbox(self.top, height=20)
     available_tasks_listbox.bind(
         '<Double-Button>',
         lambda event: self.on_select(available_tasks_listbox, person))
     scroll = tkinter.Scrollbar(command=available_tasks_listbox.yview)
     available_tasks_listbox.config(yscrollcommand=scroll.set)
     available_tasks_listbox.pack(side="left")
     scroll.pack(side="left", fill=tkinter.Y)
     self.fill_listbox(person.available_tasks, available_tasks_listbox)
     person.available_tasks.listeners.append(lambda: self.fill_listbox(
         person.available_tasks, available_tasks_listbox))
     self.create_tasks_list(person)
     self.list_boxes.append(available_tasks_listbox)
     self.list_boxes.append(scroll)
Esempio n. 22
0
def listbox():
    global parameters, lb
    wd = Tk()
    wd.title('selected stock list')
    wd.geometry('350x300')
    lb = Listbox(wd, bg='white', selectmode='multiple')
    scrollbar = Scrollbar(wd)
    for i in parameters:
        lb.insert('end', i)
    lb.place(x=30, y=10, height=220, width=250)
    scrollbar.place(x=275, y=10, height=220, width=15)
    lb.config(yscrollcommand=scrollbar.set)
    scrollbar.config(command=lb.yview)
    wd.resizable(0, 0)
    btn = Button(wd, text='STOP!', bg='#e2d1d0', command=Delete)
    btn.place(x=140, y=250, height=35, width=50)
    wd.mainloop()
Esempio n. 23
0
		def listBox() :
			scrollbar = Scrollbar(popup)
			scrollbar.grid(row=0,column=1,sticky="ns")
			listbox = Listbox(popup)
			listbox.grid(row=0,column=0,sticky="snew")
			listbox.config(yscrollcommand=scrollbar.set)
			scrollbar.config(command=listbox.yview)
			self.columnconfigure(0,weight=1)
			self.rowconfigure(0,weight=1)
			def addLogsToListBox() :
				i = 0;
				for log in self.last.read() :
					listbox.insert(END, log.replace("\n",""));
					if i % 2 == 1 :
						listbox.itemconfig(i,{"bg":"#e8dada"})
					i += 1;
			addLogsToListBox();
Esempio n. 24
0
class List:
    def __init__(self, root, array=[]):
        self.__root = root

        self.__frame = Frame(self.__root)

        self.__scrollBar = Scrollbar(self.__frame)

        self.__list = Listbox(self.__frame,
                              font=12,
                              selectmode=SINGLE,
                              width=10,
                              yscrollcommand=self.__scrollBar.set)
        self.__list.config(width=40)
        self.__list.pack(side=LEFT, anchor=W, fill=BOTH, expand=True)

        self.__lessons = []
        self.setList(array)

        self.__scrollBar.config(command=self.__list.yview)
        self.__scrollBar.pack(side=RIGHT, fill=Y)

        self.__frame.pack(side=LEFT, anchor=W, fill=BOTH, expand=True)

    def getObjectList(self):
        return self.__list

    def setList(self, array=[]):
        self.__deleteAll()

        self.__lessons = [x for x in array]
        for item in array:
            self.__list.insert(END, str(item))

    def getSelectedElement(self, e=None):
        if self.__list.curselection() is ():
            return None
        else:
            return self.__lessons[self.__list.curselection()[0]]

    def setSelectedItem(self, i):
        self.__list.activate(i)

    def __deleteAll(self):
        self.__list.delete(0, END)
Esempio n. 25
0
    def listbox_init(self):
        from tkinter import Listbox, Scrollbar
        from tkinter.constants import END

        # 1、创建listbox
        listbox = Listbox(self.frame, width=35)
        for t in self.ls:
            listbox.insert(END, t)
        listbox.place(relx=0.1, rely=0.3)
        listbox.bind('<<ListboxSelect>>', self.onselect)

        # 2、为列表添加滚动条
        s = Scrollbar(listbox)
        s.place(relx=0.94, relheight=1)
        s.config(command=listbox.yview)
        listbox.config(yscrollcommand=s.set)

        return listbox
Esempio n. 26
0
class Relations(Toplevel):

    def __init__(self, relations):
        Toplevel.__init__(self)
        self.geometry("700x470")
        self.title("Relations")
        self.relations = relations

        self.top = Frame(self, height=700, bg='white')
        self.top.pack(fill=X)
        self.listbox = Listbox(self.top, width=80)
        self.listbox.pack(side = LEFT, fill = BOTH)
        self.scrollbar = Scrollbar(self.top)
        self.scrollbar.pack(side = RIGHT, fill = BOTH)
        for values in relations:
            self.listbox.insert(END, values)
        self.listbox.config(yscrollcommand = self.scrollbar.set)
        self.scrollbar.config(command = self.listbox.yview)
Esempio n. 27
0
def openTransactions(handler):
    transactionsWindow = Toplevel()
    transactionsWindow.geometry("420x420")
    transactionsWindow.resizable(False, False)
    transactionsWindow.title("Duino-Coin Wallet - Transactions")
    transactionsWindow.configure(background=backgroundColor)
    transactionsWindow.transient([root])

    # textFont2 = Font(transactionsWindow, size=12,weight="bold")
    textFont3 = Font(transactionsWindow, size=14, weight="bold")
    textFont = Font(transactionsWindow, size=12, weight="normal")

    Label(transactionsWindow,
          text="LOCAL TRANSACTIONS LIST",
          font=textFont3,
          background=backgroundColor,
          foreground=foregroundColor).pack()
    Label(transactionsWindow,
          text="This feature will be improved in the near future",
          font=textFont,
          background=backgroundColor,
          foreground=foregroundColor).pack()

    listbox = Listbox(transactionsWindow)
    listbox.pack(side=LEFT, fill=BOTH, expand=1)
    scrollbar = Scrollbar(transactionsWindow)
    scrollbar.pack(side=RIGHT, fill=BOTH)

    with sqlite3.connect(f"{resources}/wallet.db") as con:
        cur = con.cursor()
        cur.execute("SELECT rowid,* FROM Transactions ORDER BY rowid DESC")
        Transactions = cur.fetchall()
    # transactionstext_format = ''
    for i, row in enumerate(Transactions, start=1):
        listbox.insert(END, f"{str(row[1])}  {row[2]} DUCO\n")

    listbox.config(highlightcolor=backgroundColor,
                   selectbackground="#f39c12",
                   bd=0,
                   yscrollcommand=scrollbar.set,
                   background=backgroundColor,
                   foreground=foregroundColor,
                   font=textFont)
    scrollbar.config(command=listbox.yview, background="#7bed9f")
Esempio n. 28
0
File: 1.py Progetto: Sebkd/public
    def initUI(self):
        self.master.title("Курс рубля по отношению к другим валютам")
        self.pack(fill=BOTH, expand=1)

        lb = Listbox(self)
        '''Заполняю логику списка отображения'''
        for key_to_show in self.dictionary.keys():
            lb.insert(END, key_to_show)
            self.my_list.append(key_to_show)
        '''реакция на выбор'''
        lb.bind("<<ListboxSelect>>", self.onSelect)
        lb.config(height=10, width=50)
        lb.pack(pady=15)
        '''функция отображения выбора '''
        self.var = StringVar()
        self.label = Message(self,
                             foreground='black',
                             font='Arial 10',
                             width=500,
                             textvariable=self.var)
        self.label.pack()
Esempio n. 29
0
	def __addTextbox(self,dx=85,dy=24,x1=27,y=47,x2=624,sdy=430):
		scrolly=Scrollbar(self,activebackground="#171212",bg="#343838",orient=VERTICAL,troughcolor="#171212")
		listbox=Listbox(self,
						height=dy, 
						width=dx ,
						background="#343838",
						borderwidth=0,
						highlightcolor="#4d86a1",
						selectbackground="#4d86a1",
						activestyle=NONE,
						highlightbackground="#4a4a4a",
						yscrollcommand=scrolly.set)

		listbox.config(font=("", 10),fg="#FFFFFF")
		listbox.place(x=x1,y=y+21)
		scrolly.place(x=x2,y=y,height=sdy)	
		self.__list_listbox.append(listbox)
		self.__list_scrollbar.append(scrolly)
		
		listbox.configure(yscrollcommand=scrolly.set)
		scrolly.configure(command=listbox.yview)
Esempio n. 30
0
def open_window3():
    top = Toplevel()
    top.title("Individuals list by Name & Year")
    top.geometry("605x530+420+120")

    def click():
            output.delete(0.0, END)
            output.insert(END, individuals_type_year(nameListbox.get(ACTIVE), yearListbox.get(ACTIVE)))

    Label(top, text = "Function that returns the individuals recorded by species in a certain year.", anchor = "w").pack(fill = "both")
    
    Label(top, text = "Common Name:", anchor = "w").pack(fill = "both")
    nameListbox = Listbox(top, exportselection = 0, width = 30)
    nameListbox.pack(anchor = W)
    names = common_names_list()
    names.sort()
    for name in names:
        nameListbox.insert(END, name)
    
    Label(top, text = "Year:").pack(anchor = "w")
    frame = Frame(top)
    frame.pack(anchor = "w")
    yearListbox = Listbox(frame, exportselection = 0, width = 30)
    yearListbox.pack(side = "left", fill = "y")

    scrollbar = Scrollbar(frame, orient = "vertical")
    scrollbar.config(command = yearListbox.yview)
    scrollbar.pack(side = "right", fill = "y")

    yearListbox.config(yscrollcommand = scrollbar.set)

    years = years_list()
    years.sort()
    for year in years:
        yearListbox.insert(END, year)

    Button(top, text = "Check record", width = 12, command = click).pack(anchor = "w")

    output = Text(top, width = 75, height = 6, wrap = WORD, background = "white")
    output.pack(anchor = "w")
def see_After(m):
    m.destroy()
    root=Tk()
    root.geometry("555x400")
    root.title("See All Election Details")

    leftFrame=Frame(root)
    leftFrame.pack(side=LEFT)

    midFrame=Frame(root)
    midFrame.pack(side=LEFT)

    rightFrame=Frame(root)
    rightFrame.pack(side=LEFT)

    load=Image.open("index.png")
    render=ImageTk.PhotoImage(load)
    img=Label(leftFrame,image=render)
    img.image=render
    img.pack()

    Label(midFrame,text="Elections", font = "Times 15 bold").pack(expand = True, fill = BOTH)
    Label(midFrame,text="", font = "Times 15 bold").pack()
    Eframe=Frame(midFrame)
    Eframe.pack(expand = True,fill = BOTH)
    scrollbarE=Scrollbar(Eframe)
    listBoxElection=Listbox(Eframe,width=30,selectmode=BROWSE)
    listBoxElection.config(yscrollcommand=scrollbarE.set)
    scrollbarE.config(command=listBoxElection.yview)
    listBoxElection.pack(expand = True, fill = BOTH,side=LEFT)
    scrollbarE.pack(fill = BOTH,side=RIGHT)
    Label(midFrame,text="").pack()
    Button(midFrame,text="Back",font = "Times 10 bold",command=lambda:adminPage.adminPageStart(root)).pack(expand = True, fill = BOTH)
    db.loadAfterElectionData(listBoxElection)
    all_items = listBoxElection.get(0, tk.END)
    print(all_items)
    listBoxElection.bind('<Double-Button-1>', lambda x:selectedElection(root,listBoxElection,all_items))

    root.mainloop()
Esempio n. 32
0
class Searcher(Frame):
    """ Keyword Searcher
    This is a very simple python program, which is designed for finding specified key-word
    in files. Just for fun!
    """
    def __init__(self, master=None, cnf={}, **kwargs):
        super(Searcher, self).__init__(master, cnf, **kwargs)
        self._root_path_var = StringVar()
        self._keyword_var = StringVar(self)
        self._listbox = None
        self._result_queue = None
        self.pack(fill=BOTH, expand=YES, padx=5, pady=5)
        self.make_widgets()
        self._consumer()

        # config for main window
        self.master.title('Keyword Searcher')

    def make_widgets(self):
        frm1 = Frame(self)
        frm1.pack(side=TOP, fill=X)
        Entry(frm1, textvariable=self._root_path_var, font=DEFAULT_FONT).pack(side=LEFT, fill=X, expand=YES)
        Button(frm1, text='Add directory', font=DEFAULT_FONT,
               command=lambda: self._root_path_var.set(askdirectory(title='Add directory'))).pack(side=RIGHT)
        
        frm2 = Frame(self)
        frm2.pack(side=TOP, fill=X)
        keyword_ent = Entry(frm2, textvariable=self._keyword_var, font=DEFAULT_FONT)
        keyword_ent.pack(side=LEFT, fill=X, expand=YES)
        Button(frm2, text='Find', font=DEFAULT_FONT, command=self.find).pack(side=RIGHT)

        vs = Scrollbar(self)
        hs = Scrollbar(self)
        self._listbox = Listbox(self)
        vs.pack(side=RIGHT, fill=Y)
        vs.config(command=self._listbox.yview)
        hs.pack(side=BOTTOM, fill=X)
        hs.config(command=self._listbox.xview, orient='horizontal')
        self._listbox.config(yscrollcommand=vs.set, xscrollcommand=hs.set,
                             font=DEFAULT_FONT)
        self._listbox.pack(fill=BOTH, expand=YES)
        self._listbox.bind('<Double-1>', self._navigate_to)

    def find(self):
        self._result_queue = queue.Queue()
        self._listbox.delete('0', 'end')
        Thread(target=self._find, args=(self._root_path_var.get(),
                                        self._keyword_var.get()), daemon=True).start()

    def _find(self, path, keyword):
        if not os.path.exists(path):
            return None

        for this_dir, sub_dirs, files in os.walk(path):
            for file in files:
                file_type = guess_type(file)[0]
                if file_type and 'text' in file_type:
                    fp = os.path.join(this_dir, file)
                    self._result_queue.put(fp) if keyword in open(fp).read() else None

    def _consumer(self):
        if self._result_queue:
            try:
                fp = self._result_queue.get(block=False)
            except queue.Empty:
                pass
            else:
                self._listbox.insert('end', fp)
                # auto scroll.
                self._listbox.yview('end')

        self.after(100, self._consumer)

    def _navigate_to(self, event):
        """
        Only works on Ubuntu platform currently.
        Double click to navigate to selected path.
        It's a very convenient function.
        :return: None
        """
        print(event)
        # get active item from listbox
        path = self._listbox.get('active')
        print(path)

        # open nautilus with param path, before that, check your platform.
        if 'ubuntu' in (os.popen('uname -a').read()).lower():
            os.system('/usr/bin/nautilus {}'.format(path))
        else:
            pass
Esempio n. 33
0
class RecursiveDescentApp(object):
    """
    A graphical tool for exploring the recursive descent parser.  The tool
    displays the parser's tree and the remaining text, and allows the
    user to control the parser's operation.  In particular, the user
    can expand subtrees on the frontier, match tokens on the frontier
    against the text, and backtrack.  A "step" button simply steps
    through the parsing process, performing the operations that
    ``RecursiveDescentParser`` would use.
    """
    def __init__(self, grammar, sent, trace=0):
        self._sent = sent
        self._parser = SteppingRecursiveDescentParser(grammar, trace)

        # Set up the main window.
        self._top = Tk()
        self._top.title('Recursive Descent Parser Application')

        # Set up key bindings.
        self._init_bindings()

        # Initialize the fonts.
        self._init_fonts(self._top)

        # Animations.  animating_lock is a lock to prevent the demo
        # from performing new operations while it's animating.
        self._animation_frames = IntVar(self._top)
        self._animation_frames.set(5)
        self._animating_lock = 0
        self._autostep = 0

        # The user can hide the grammar.
        self._show_grammar = IntVar(self._top)
        self._show_grammar.set(1)

        # Create the basic frames.
        self._init_menubar(self._top)
        self._init_buttons(self._top)
        self._init_feedback(self._top)
        self._init_grammar(self._top)
        self._init_canvas(self._top)

        # Initialize the parser.
        self._parser.initialize(self._sent)

        # Resize callback
        self._canvas.bind('<Configure>', self._configure)

    #########################################
    ##  Initialization Helpers
    #########################################

    def _init_fonts(self, root):
        # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html>
        self._sysfont = tkinter.font.Font(font=Button()["font"])
        root.option_add("*Font", self._sysfont)

        # TWhat's our font size (default=same as sysfont)
        self._size = IntVar(root)
        self._size.set(self._sysfont.cget('size'))

        self._boldfont = tkinter.font.Font(family='helvetica', weight='bold',
                                    size=self._size.get())
        self._font = tkinter.font.Font(family='helvetica',
                                    size=self._size.get())
        if self._size.get() < 0: big = self._size.get()-2
        else: big = self._size.get()+2
        self._bigfont = tkinter.font.Font(family='helvetica', weight='bold',
                                    size=big)

    def _init_grammar(self, parent):
        # Grammar view.
        self._prodframe = listframe = Frame(parent)
        self._prodframe.pack(fill='both', side='left', padx=2)
        self._prodlist_label = Label(self._prodframe, font=self._boldfont,
                                     text='Available Expansions')
        self._prodlist_label.pack()
        self._prodlist = Listbox(self._prodframe, selectmode='single',
                                 relief='groove', background='white',
                                 foreground='#909090', font=self._font,
                                 selectforeground='#004040',
                                 selectbackground='#c0f0c0')

        self._prodlist.pack(side='right', fill='both', expand=1)

        self._productions = list(self._parser.grammar().productions())
        for production in self._productions:
            self._prodlist.insert('end', ('  %s' % production))
        self._prodlist.config(height=min(len(self._productions), 25))

        # Add a scrollbar if there are more than 25 productions.
        if len(self._productions) > 25:
            listscroll = Scrollbar(self._prodframe,
                                   orient='vertical')
            self._prodlist.config(yscrollcommand = listscroll.set)
            listscroll.config(command=self._prodlist.yview)
            listscroll.pack(side='left', fill='y')

        # If they select a production, apply it.
        self._prodlist.bind('<<ListboxSelect>>', self._prodlist_select)

    def _init_bindings(self):
        # Key bindings are a good thing.
        self._top.bind('<Control-q>', self.destroy)
        self._top.bind('<Control-x>', self.destroy)
        self._top.bind('<Escape>', self.destroy)
        self._top.bind('e', self.expand)
        #self._top.bind('<Alt-e>', self.expand)
        #self._top.bind('<Control-e>', self.expand)
        self._top.bind('m', self.match)
        self._top.bind('<Alt-m>', self.match)
        self._top.bind('<Control-m>', self.match)
        self._top.bind('b', self.backtrack)
        self._top.bind('<Alt-b>', self.backtrack)
        self._top.bind('<Control-b>', self.backtrack)
        self._top.bind('<Control-z>', self.backtrack)
        self._top.bind('<BackSpace>', self.backtrack)
        self._top.bind('a', self.autostep)
        #self._top.bind('<Control-a>', self.autostep)
        self._top.bind('<Control-space>', self.autostep)
        self._top.bind('<Control-c>', self.cancel_autostep)
        self._top.bind('<space>', self.step)
        self._top.bind('<Delete>', self.reset)
        self._top.bind('<Control-p>', self.postscript)
        #self._top.bind('<h>', self.help)
        #self._top.bind('<Alt-h>', self.help)
        self._top.bind('<Control-h>', self.help)
        self._top.bind('<F1>', self.help)
        #self._top.bind('<g>', self.toggle_grammar)
        #self._top.bind('<Alt-g>', self.toggle_grammar)
        #self._top.bind('<Control-g>', self.toggle_grammar)
        self._top.bind('<Control-g>', self.edit_grammar)
        self._top.bind('<Control-t>', self.edit_sentence)

    def _init_buttons(self, parent):
        # Set up the frames.
        self._buttonframe = buttonframe = Frame(parent)
        buttonframe.pack(fill='none', side='bottom', padx=3, pady=2)
        Button(buttonframe, text='Step',
               background='#90c0d0', foreground='black',
               command=self.step,).pack(side='left')
        Button(buttonframe, text='Autostep',
               background='#90c0d0', foreground='black',
               command=self.autostep,).pack(side='left')
        Button(buttonframe, text='Expand', underline=0,
               background='#90f090', foreground='black',
               command=self.expand).pack(side='left')
        Button(buttonframe, text='Match', underline=0,
               background='#90f090', foreground='black',
               command=self.match).pack(side='left')
        Button(buttonframe, text='Backtrack', underline=0,
               background='#f0a0a0', foreground='black',
               command=self.backtrack).pack(side='left')
        # Replace autostep...
#         self._autostep_button = Button(buttonframe, text='Autostep',
#                                        underline=0, command=self.autostep)
#         self._autostep_button.pack(side='left')

    def _configure(self, event):
        self._autostep = 0
        (x1, y1, x2, y2) = self._cframe.scrollregion()
        y2 = event.height - 6
        self._canvas['scrollregion'] = '%d %d %d %d' % (x1,y1,x2,y2)
        self._redraw()

    def _init_feedback(self, parent):
        self._feedbackframe = feedbackframe = Frame(parent)
        feedbackframe.pack(fill='x', side='bottom', padx=3, pady=3)
        self._lastoper_label = Label(feedbackframe, text='Last Operation:',
                                     font=self._font)
        self._lastoper_label.pack(side='left')
        lastoperframe = Frame(feedbackframe, relief='sunken', border=1)
        lastoperframe.pack(fill='x', side='right', expand=1, padx=5)
        self._lastoper1 = Label(lastoperframe, foreground='#007070',
                                background='#f0f0f0', font=self._font)
        self._lastoper2 = Label(lastoperframe, anchor='w', width=30,
                                foreground='#004040', background='#f0f0f0',
                                font=self._font)
        self._lastoper1.pack(side='left')
        self._lastoper2.pack(side='left', fill='x', expand=1)

    def _init_canvas(self, parent):
        self._cframe = CanvasFrame(parent, background='white',
                                   #width=525, height=250,
                                   closeenough=10,
                                   border=2, relief='sunken')
        self._cframe.pack(expand=1, fill='both', side='top', pady=2)
        canvas = self._canvas = self._cframe.canvas()

        # Initially, there's no tree or text
        self._tree = None
        self._textwidgets = []
        self._textline = None

    def _init_menubar(self, parent):
        menubar = Menu(parent)

        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label='Reset Parser', underline=0,
                             command=self.reset, accelerator='Del')
        filemenu.add_command(label='Print to Postscript', underline=0,
                             command=self.postscript, accelerator='Ctrl-p')
        filemenu.add_command(label='Exit', underline=1,
                             command=self.destroy, accelerator='Ctrl-x')
        menubar.add_cascade(label='File', underline=0, menu=filemenu)

        editmenu = Menu(menubar, tearoff=0)
        editmenu.add_command(label='Edit Grammar', underline=5,
                             command=self.edit_grammar,
                             accelerator='Ctrl-g')
        editmenu.add_command(label='Edit Text', underline=5,
                             command=self.edit_sentence,
                             accelerator='Ctrl-t')
        menubar.add_cascade(label='Edit', underline=0, menu=editmenu)

        rulemenu = Menu(menubar, tearoff=0)
        rulemenu.add_command(label='Step', underline=1,
                             command=self.step, accelerator='Space')
        rulemenu.add_separator()
        rulemenu.add_command(label='Match', underline=0,
                             command=self.match, accelerator='Ctrl-m')
        rulemenu.add_command(label='Expand', underline=0,
                             command=self.expand, accelerator='Ctrl-e')
        rulemenu.add_separator()
        rulemenu.add_command(label='Backtrack', underline=0,
                             command=self.backtrack, accelerator='Ctrl-b')
        menubar.add_cascade(label='Apply', underline=0, menu=rulemenu)

        viewmenu = Menu(menubar, tearoff=0)
        viewmenu.add_checkbutton(label="Show Grammar", underline=0,
                                 variable=self._show_grammar,
                                 command=self._toggle_grammar)
        viewmenu.add_separator()
        viewmenu.add_radiobutton(label='Tiny', variable=self._size,
                                 underline=0, value=10, command=self.resize)
        viewmenu.add_radiobutton(label='Small', variable=self._size,
                                 underline=0, value=12, command=self.resize)
        viewmenu.add_radiobutton(label='Medium', variable=self._size,
                                 underline=0, value=14, command=self.resize)
        viewmenu.add_radiobutton(label='Large', variable=self._size,
                                 underline=0, value=18, command=self.resize)
        viewmenu.add_radiobutton(label='Huge', variable=self._size,
                                 underline=0, value=24, command=self.resize)
        menubar.add_cascade(label='View', underline=0, menu=viewmenu)

        animatemenu = Menu(menubar, tearoff=0)
        animatemenu.add_radiobutton(label="No Animation", underline=0,
                                    variable=self._animation_frames,
                                    value=0)
        animatemenu.add_radiobutton(label="Slow Animation", underline=0,
                                    variable=self._animation_frames,
                                    value=10, accelerator='-')
        animatemenu.add_radiobutton(label="Normal Animation", underline=0,
                                    variable=self._animation_frames,
                                    value=5, accelerator='=')
        animatemenu.add_radiobutton(label="Fast Animation", underline=0,
                                    variable=self._animation_frames,
                                    value=2, accelerator='+')
        menubar.add_cascade(label="Animate", underline=1, menu=animatemenu)


        helpmenu = Menu(menubar, tearoff=0)
        helpmenu.add_command(label='About', underline=0,
                             command=self.about)
        helpmenu.add_command(label='Instructions', underline=0,
                             command=self.help, accelerator='F1')
        menubar.add_cascade(label='Help', underline=0, menu=helpmenu)

        parent.config(menu=menubar)

    #########################################
    ##  Helper
    #########################################

    def _get(self, widget, treeloc):
        for i in treeloc: widget = widget.subtrees()[i]
        if isinstance(widget, TreeSegmentWidget):
            widget = widget.label()
        return widget

    #########################################
    ##  Main draw procedure
    #########################################

    def _redraw(self):
        canvas = self._canvas

        # Delete the old tree, widgets, etc.
        if self._tree is not None:
            self._cframe.destroy_widget(self._tree)
        for twidget in self._textwidgets:
            self._cframe.destroy_widget(twidget)
        if self._textline is not None:
            self._canvas.delete(self._textline)

        # Draw the tree.
        helv = ('helvetica', -self._size.get())
        bold = ('helvetica', -self._size.get(), 'bold')
        attribs = {'tree_color': '#000000', 'tree_width': 2,
                   'node_font': bold, 'leaf_font': helv,}
        tree = self._parser.tree()
        self._tree = tree_to_treesegment(canvas, tree, **attribs)
        self._cframe.add_widget(self._tree, 30, 5)

        # Draw the text.
        helv = ('helvetica', -self._size.get())
        bottom = y = self._cframe.scrollregion()[3]
        self._textwidgets = [TextWidget(canvas, word, font=self._font)
                             for word in self._sent]
        for twidget in self._textwidgets:
            self._cframe.add_widget(twidget, 0, 0)
            twidget.move(0, bottom-twidget.bbox()[3]-5)
            y = min(y, twidget.bbox()[1])

        # Draw a line over the text, to separate it from the tree.
        self._textline = canvas.create_line(-5000, y-5, 5000, y-5, dash='.')

        # Highlight appropriate nodes.
        self._highlight_nodes()
        self._highlight_prodlist()

        # Make sure the text lines up.
        self._position_text()


    def _redraw_quick(self):
        # This should be more-or-less sufficient after an animation.
        self._highlight_nodes()
        self._highlight_prodlist()
        self._position_text()

    def _highlight_nodes(self):
        # Highlight the list of nodes to be checked.
        bold = ('helvetica', -self._size.get(), 'bold')
        for treeloc in self._parser.frontier()[:1]:
            self._get(self._tree, treeloc)['color'] = '#20a050'
            self._get(self._tree, treeloc)['font'] = bold
        for treeloc in self._parser.frontier()[1:]:
            self._get(self._tree, treeloc)['color'] = '#008080'

    def _highlight_prodlist(self):
        # Highlight the productions that can be expanded.
        # Boy, too bad tkinter doesn't implement Listbox.itemconfig;
        # that would be pretty useful here.
        self._prodlist.delete(0, 'end')
        expandable = self._parser.expandable_productions()
        untried = self._parser.untried_expandable_productions()
        productions = self._productions
        for index in range(len(productions)):
            if productions[index] in expandable:
                if productions[index] in untried:
                    self._prodlist.insert(index, ' %s' % productions[index])
                else:
                    self._prodlist.insert(index, ' %s (TRIED)' %
                                          productions[index])
                self._prodlist.selection_set(index)
            else:
                self._prodlist.insert(index, ' %s' % productions[index])

    def _position_text(self):
        # Line up the text widgets that are matched against the tree
        numwords = len(self._sent)
        num_matched = numwords - len(self._parser.remaining_text())
        leaves = self._tree_leaves()[:num_matched]
        xmax = self._tree.bbox()[0]
        for i in range(0, len(leaves)):
            widget = self._textwidgets[i]
            leaf = leaves[i]
            widget['color'] = '#006040'
            leaf['color'] = '#006040'
            widget.move(leaf.bbox()[0] - widget.bbox()[0], 0)
            xmax = widget.bbox()[2] + 10

        # Line up the text widgets that are not matched against the tree.
        for i in range(len(leaves), numwords):
            widget = self._textwidgets[i]
            widget['color'] = '#a0a0a0'
            widget.move(xmax - widget.bbox()[0], 0)
            xmax = widget.bbox()[2] + 10

        # If we have a complete parse, make everything green :)
        if self._parser.currently_complete():
            for twidget in self._textwidgets:
                twidget['color'] = '#00a000'

        # Move the matched leaves down to the text.
        for i in range(0, len(leaves)):
            widget = self._textwidgets[i]
            leaf = leaves[i]
            dy = widget.bbox()[1] - leaf.bbox()[3] - 10.0
            dy = max(dy, leaf.parent().label().bbox()[3] - leaf.bbox()[3] + 10)
            leaf.move(0, dy)

    def _tree_leaves(self, tree=None):
        if tree is None: tree = self._tree
        if isinstance(tree, TreeSegmentWidget):
            leaves = []
            for child in tree.subtrees(): leaves += self._tree_leaves(child)
            return leaves
        else:
            return [tree]

    #########################################
    ##  Button Callbacks
    #########################################

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

    def reset(self, *e):
        self._autostep = 0
        self._parser.initialize(self._sent)
        self._lastoper1['text'] = 'Reset Application'
        self._lastoper2['text'] = ''
        self._redraw()

    def autostep(self, *e):
        if self._animation_frames.get() == 0:
            self._animation_frames.set(2)
        if self._autostep:
            self._autostep = 0
        else:
            self._autostep = 1
            self._step()

    def cancel_autostep(self, *e):
        #self._autostep_button['text'] = 'Autostep'
        self._autostep = 0

    # Make sure to stop auto-stepping if we get any user input.
    def step(self, *e): self._autostep = 0; self._step()
    def match(self, *e): self._autostep = 0; self._match()
    def expand(self, *e): self._autostep = 0; self._expand()
    def backtrack(self, *e): self._autostep = 0; self._backtrack()

    def _step(self):
        if self._animating_lock: return

        # Try expanding, matching, and backtracking (in that order)
        if self._expand(): pass
        elif self._parser.untried_match() and self._match(): pass
        elif self._backtrack(): pass
        else:
            self._lastoper1['text'] = 'Finished'
            self._lastoper2['text'] = ''
            self._autostep = 0

        # Check if we just completed a parse.
        if self._parser.currently_complete():
            self._autostep = 0
            self._lastoper2['text'] += '    [COMPLETE PARSE]'

    def _expand(self, *e):
        if self._animating_lock: return
        old_frontier = self._parser.frontier()
        rv = self._parser.expand()
        if rv is not None:
            self._lastoper1['text'] = 'Expand:'
            self._lastoper2['text'] = rv
            self._prodlist.selection_clear(0, 'end')
            index = self._productions.index(rv)
            self._prodlist.selection_set(index)
            self._animate_expand(old_frontier[0])
            return 1
        else:
            self._lastoper1['text'] = 'Expand:'
            self._lastoper2['text'] = '(all expansions tried)'
            return 0

    def _match(self, *e):
        if self._animating_lock: return
        old_frontier = self._parser.frontier()
        rv = self._parser.match()
        if rv is not None:
            self._lastoper1['text'] = 'Match:'
            self._lastoper2['text'] = rv
            self._animate_match(old_frontier[0])
            return 1
        else:
            self._lastoper1['text'] = 'Match:'
            self._lastoper2['text'] = '(failed)'
            return 0

    def _backtrack(self, *e):
        if self._animating_lock: return
        if self._parser.backtrack():
            elt = self._parser.tree()
            for i in self._parser.frontier()[0]:
                elt = elt[i]
            self._lastoper1['text'] = 'Backtrack'
            self._lastoper2['text'] = ''
            if isinstance(elt, Tree):
                self._animate_backtrack(self._parser.frontier()[0])
            else:
                self._animate_match_backtrack(self._parser.frontier()[0])
            return 1
        else:
            self._autostep = 0
            self._lastoper1['text'] = 'Finished'
            self._lastoper2['text'] = ''
            return 0

    def about(self, *e):
        ABOUT = ("NLTK Recursive Descent Parser Application\n"+
                 "Written by Edward Loper")
        TITLE = 'About: Recursive Descent Parser Application'
        try:
            from tkinter.messagebox import Message
            Message(message=ABOUT, title=TITLE).show()
        except:
            ShowText(self._top, TITLE, ABOUT)

    def help(self, *e):
        self._autostep = 0
        # The default font's not very legible; try using 'fixed' instead.
        try:
            ShowText(self._top, 'Help: Recursive Descent Parser Application',
                     (__doc__ or '').strip(), width=75, font='fixed')
        except:
            ShowText(self._top, 'Help: Recursive Descent Parser Application',
                     (__doc__ or '').strip(), width=75)

    def postscript(self, *e):
        self._autostep = 0
        self._cframe.print_to_file()

    def mainloop(self, *args, **kwargs):
        """
        Enter the Tkinter mainloop.  This function must be called if
        this demo is created from a non-interactive program (e.g.
        from a secript); otherwise, the demo will close as soon as
        the script completes.
        """
        if in_idle(): return
        self._top.mainloop(*args, **kwargs)

    def resize(self, size=None):
        if size is not None: self._size.set(size)
        size = self._size.get()
        self._font.configure(size=-(abs(size)))
        self._boldfont.configure(size=-(abs(size)))
        self._sysfont.configure(size=-(abs(size)))
        self._bigfont.configure(size=-(abs(size+2)))
        self._redraw()

    #########################################
    ##  Expand Production Selection
    #########################################

    def _toggle_grammar(self, *e):
        if self._show_grammar.get():
            self._prodframe.pack(fill='both', side='left', padx=2,
                                 after=self._feedbackframe)
            self._lastoper1['text'] = 'Show Grammar'
        else:
            self._prodframe.pack_forget()
            self._lastoper1['text'] = 'Hide Grammar'
        self._lastoper2['text'] = ''

#     def toggle_grammar(self, *e):
#         self._show_grammar = not self._show_grammar
#         if self._show_grammar:
#             self._prodframe.pack(fill='both', expand='y', side='left',
#                                  after=self._feedbackframe)
#             self._lastoper1['text'] = 'Show Grammar'
#         else:
#             self._prodframe.pack_forget()
#             self._lastoper1['text'] = 'Hide Grammar'
#         self._lastoper2['text'] = ''

    def _prodlist_select(self, event):
        selection = self._prodlist.curselection()
        if len(selection) != 1: return
        index = int(selection[0])
        old_frontier = self._parser.frontier()
        production = self._parser.expand(self._productions[index])

        if production:
            self._lastoper1['text'] = 'Expand:'
            self._lastoper2['text'] = production
            self._prodlist.selection_clear(0, 'end')
            self._prodlist.selection_set(index)
            self._animate_expand(old_frontier[0])
        else:
            # Reset the production selections.
            self._prodlist.selection_clear(0, 'end')
            for prod in self._parser.expandable_productions():
                index = self._productions.index(prod)
                self._prodlist.selection_set(index)

    #########################################
    ##  Animation
    #########################################

    def _animate_expand(self, treeloc):
        oldwidget = self._get(self._tree, treeloc)
        oldtree = oldwidget.parent()
        top = not isinstance(oldtree.parent(), TreeSegmentWidget)

        tree = self._parser.tree()
        for i in treeloc:
            tree = tree[i]

        widget = tree_to_treesegment(self._canvas, tree,
                                     node_font=self._boldfont,
                                     leaf_color='white',
                                     tree_width=2, tree_color='white',
                                     node_color='white',
                                     leaf_font=self._font)
        widget.label()['color'] = '#20a050'

        (oldx, oldy) = oldtree.label().bbox()[:2]
        (newx, newy) = widget.label().bbox()[:2]
        widget.move(oldx-newx, oldy-newy)

        if top:
            self._cframe.add_widget(widget, 0, 5)
            widget.move(30-widget.label().bbox()[0], 0)
            self._tree = widget
        else:
            oldtree.parent().replace_child(oldtree, widget)

        # Move the children over so they don't overlap.
        # Line the children up in a strange way.
        if widget.subtrees():
            dx = (oldx + widget.label().width()/2 -
                  widget.subtrees()[0].bbox()[0]/2 -
                  widget.subtrees()[0].bbox()[2]/2)
            for subtree in widget.subtrees(): subtree.move(dx, 0)

        self._makeroom(widget)

        if top:
            self._cframe.destroy_widget(oldtree)
        else:
            oldtree.destroy()

        colors = ['gray%d' % (10*int(10*x/self._animation_frames.get()))
                  for x in range(self._animation_frames.get(),0,-1)]

        # Move the text string down, if necessary.
        dy = widget.bbox()[3] + 30 - self._canvas.coords(self._textline)[1]
        if dy > 0:
            for twidget in self._textwidgets: twidget.move(0, dy)
            self._canvas.move(self._textline, 0, dy)

        self._animate_expand_frame(widget, colors)

    def _makeroom(self, treeseg):
        """
        Make sure that no sibling tree bbox's overlap.
        """
        parent = treeseg.parent()
        if not isinstance(parent, TreeSegmentWidget): return

        index = parent.subtrees().index(treeseg)

        # Handle siblings to the right
        rsiblings = parent.subtrees()[index+1:]
        if rsiblings:
            dx = treeseg.bbox()[2] - rsiblings[0].bbox()[0] + 10
            for sibling in rsiblings: sibling.move(dx, 0)

        # Handle siblings to the left
        if index > 0:
            lsibling = parent.subtrees()[index-1]
            dx = max(0, lsibling.bbox()[2] - treeseg.bbox()[0] + 10)
            treeseg.move(dx, 0)

        # Keep working up the tree.
        self._makeroom(parent)

    def _animate_expand_frame(self, widget, colors):
        if len(colors) > 0:
            self._animating_lock = 1
            widget['color'] = colors[0]
            for subtree in widget.subtrees():
                if isinstance(subtree, TreeSegmentWidget):
                    subtree.label()['color'] = colors[0]
                else:
                    subtree['color'] = colors[0]
            self._top.after(50, self._animate_expand_frame,
                            widget, colors[1:])
        else:
            widget['color'] = 'black'
            for subtree in widget.subtrees():
                if isinstance(subtree, TreeSegmentWidget):
                    subtree.label()['color'] = 'black'
                else:
                    subtree['color'] = 'black'
            self._redraw_quick()
            widget.label()['color'] = 'black'
            self._animating_lock = 0
            if self._autostep: self._step()

    def _animate_backtrack(self, treeloc):
        # Flash red first, if we're animating.
        if self._animation_frames.get() == 0: colors = []
        else: colors = ['#a00000', '#000000', '#a00000']
        colors += ['gray%d' % (10*int(10*x/(self._animation_frames.get())))
                   for x in range(1, self._animation_frames.get()+1)]

        widgets = [self._get(self._tree, treeloc).parent()]
        for subtree in widgets[0].subtrees():
            if isinstance(subtree, TreeSegmentWidget):
                widgets.append(subtree.label())
            else:
                widgets.append(subtree)

        self._animate_backtrack_frame(widgets, colors)

    def _animate_backtrack_frame(self, widgets, colors):
        if len(colors) > 0:
            self._animating_lock = 1
            for widget in widgets: widget['color'] = colors[0]
            self._top.after(50, self._animate_backtrack_frame,
                            widgets, colors[1:])
        else:
            for widget in widgets[0].subtrees():
                widgets[0].remove_child(widget)
                widget.destroy()
            self._redraw_quick()
            self._animating_lock = 0
            if self._autostep: self._step()

    def _animate_match_backtrack(self, treeloc):
        widget = self._get(self._tree, treeloc)
        node = widget.parent().label()
        dy = (1.0 * (node.bbox()[3] - widget.bbox()[1] + 14) /
              max(1, self._animation_frames.get()))
        self._animate_match_backtrack_frame(self._animation_frames.get(),
                                            widget, dy)

    def _animate_match(self, treeloc):
        widget = self._get(self._tree, treeloc)

        dy = ((self._textwidgets[0].bbox()[1] - widget.bbox()[3] - 10.0) /
              max(1, self._animation_frames.get()))
        self._animate_match_frame(self._animation_frames.get(), widget, dy)

    def _animate_match_frame(self, frame, widget, dy):
        if frame > 0:
            self._animating_lock = 1
            widget.move(0, dy)
            self._top.after(10, self._animate_match_frame,
                            frame-1, widget, dy)
        else:
            widget['color'] = '#006040'
            self._redraw_quick()
            self._animating_lock = 0
            if self._autostep: self._step()

    def _animate_match_backtrack_frame(self, frame, widget, dy):
        if frame > 0:
            self._animating_lock = 1
            widget.move(0, dy)
            self._top.after(10, self._animate_match_backtrack_frame,
                            frame-1, widget, dy)
        else:
            widget.parent().remove_child(widget)
            widget.destroy()
            self._animating_lock = 0
            if self._autostep: self._step()

    def edit_grammar(self, *e):
        CFGEditor(self._top, self._parser.grammar(), self.set_grammar)

    def set_grammar(self, grammar):
        self._parser.set_grammar(grammar)
        self._productions = list(grammar.productions())
        self._prodlist.delete(0, 'end')
        for production in self._productions:
            self._prodlist.insert('end', (' %s' % production))

    def edit_sentence(self, *e):
        sentence = " ".join(self._sent)
        title = 'Edit Text'
        instr = 'Enter a new sentence to parse.'
        EntryDialog(self._top, sentence, instr, self.set_sentence, title)

    def set_sentence(self, sentence):
        self._sent = sentence.split() #[XX] use tagged?
        self.reset()
Esempio n. 34
0
class ShiftReduceApp(object):
    """
    A graphical tool for exploring the shift-reduce parser.  The tool
    displays the parser's stack and the remaining text, and allows the
    user to control the parser's operation.  In particular, the user
    can shift tokens onto the stack, and can perform reductions on the
    top elements of the stack.  A "step" button simply steps through
    the parsing process, performing the operations that
    ``nltk.parse.ShiftReduceParser`` would use.
    """
    def __init__(self, grammar, sent, trace=0):
        self._sent = sent
        self._parser = SteppingShiftReduceParser(grammar, trace)

        # Set up the main window.
        self._top = Tk()
        self._top.title('Shift Reduce Parser Application')

        # Animations.  animating_lock is a lock to prevent the demo
        # from performing new operations while it's animating.
        self._animating_lock = 0
        self._animate = IntVar(self._top)
        self._animate.set(10) # = medium

        # The user can hide the grammar.
        self._show_grammar = IntVar(self._top)
        self._show_grammar.set(1)

        # Initialize fonts.
        self._init_fonts(self._top)

        # Set up key bindings.
        self._init_bindings()

        # Create the basic frames.
        self._init_menubar(self._top)
        self._init_buttons(self._top)
        self._init_feedback(self._top)
        self._init_grammar(self._top)
        self._init_canvas(self._top)

        # A popup menu for reducing.
        self._reduce_menu = Menu(self._canvas, tearoff=0)

        # Reset the demo, and set the feedback frame to empty.
        self.reset()
        self._lastoper1['text'] = ''

    #########################################
    ##  Initialization Helpers
    #########################################

    def _init_fonts(self, root):
        # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html>
        self._sysfont = tkinter.font.Font(font=Button()["font"])
        root.option_add("*Font", self._sysfont)

        # TWhat's our font size (default=same as sysfont)
        self._size = IntVar(root)
        self._size.set(self._sysfont.cget('size'))

        self._boldfont = tkinter.font.Font(family='helvetica', weight='bold',
                                    size=self._size.get())
        self._font = tkinter.font.Font(family='helvetica',
                                    size=self._size.get())

    def _init_grammar(self, parent):
        # Grammar view.
        self._prodframe = listframe = Frame(parent)
        self._prodframe.pack(fill='both', side='left', padx=2)
        self._prodlist_label = Label(self._prodframe,
                                     font=self._boldfont,
                                     text='Available Reductions')
        self._prodlist_label.pack()
        self._prodlist = Listbox(self._prodframe, selectmode='single',
                                 relief='groove', background='white',
                                 foreground='#909090',
                                 font=self._font,
                                 selectforeground='#004040',
                                 selectbackground='#c0f0c0')

        self._prodlist.pack(side='right', fill='both', expand=1)

        self._productions = list(self._parser.grammar().productions())
        for production in self._productions:
            self._prodlist.insert('end', (' %s' % production))
        self._prodlist.config(height=min(len(self._productions), 25))

        # Add a scrollbar if there are more than 25 productions.
        if 1:#len(self._productions) > 25:
            listscroll = Scrollbar(self._prodframe,
                                   orient='vertical')
            self._prodlist.config(yscrollcommand = listscroll.set)
            listscroll.config(command=self._prodlist.yview)
            listscroll.pack(side='left', fill='y')

        # If they select a production, apply it.
        self._prodlist.bind('<<ListboxSelect>>', self._prodlist_select)

        # When they hover over a production, highlight it.
        self._hover = -1
        self._prodlist.bind('<Motion>', self._highlight_hover)
        self._prodlist.bind('<Leave>', self._clear_hover)

    def _init_bindings(self):
        # Quit
        self._top.bind('<Control-q>', self.destroy)
        self._top.bind('<Control-x>', self.destroy)
        self._top.bind('<Alt-q>', self.destroy)
        self._top.bind('<Alt-x>', self.destroy)

        # Ops (step, shift, reduce, undo)
        self._top.bind('<space>', self.step)
        self._top.bind('<s>', self.shift)
        self._top.bind('<Alt-s>', self.shift)
        self._top.bind('<Control-s>', self.shift)
        self._top.bind('<r>', self.reduce)
        self._top.bind('<Alt-r>', self.reduce)
        self._top.bind('<Control-r>', self.reduce)
        self._top.bind('<Delete>', self.reset)
        self._top.bind('<u>', self.undo)
        self._top.bind('<Alt-u>', self.undo)
        self._top.bind('<Control-u>', self.undo)
        self._top.bind('<Control-z>', self.undo)
        self._top.bind('<BackSpace>', self.undo)

        # Misc
        self._top.bind('<Control-p>', self.postscript)
        self._top.bind('<Control-h>', self.help)
        self._top.bind('<F1>', self.help)
        self._top.bind('<Control-g>', self.edit_grammar)
        self._top.bind('<Control-t>', self.edit_sentence)

        # Animation speed control
        self._top.bind('-', lambda e,a=self._animate:a.set(20))
        self._top.bind('=', lambda e,a=self._animate:a.set(10))
        self._top.bind('+', lambda e,a=self._animate:a.set(4))

    def _init_buttons(self, parent):
        # Set up the frames.
        self._buttonframe = buttonframe = Frame(parent)
        buttonframe.pack(fill='none', side='bottom')
        Button(buttonframe, text='Step',
               background='#90c0d0', foreground='black',
               command=self.step,).pack(side='left')
        Button(buttonframe, text='Shift', underline=0,
               background='#90f090', foreground='black',
               command=self.shift).pack(side='left')
        Button(buttonframe, text='Reduce', underline=0,
               background='#90f090', foreground='black',
               command=self.reduce).pack(side='left')
        Button(buttonframe, text='Undo', underline=0,
               background='#f0a0a0', foreground='black',
               command=self.undo).pack(side='left')

    def _init_menubar(self, parent):
        menubar = Menu(parent)

        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label='Reset Parser', underline=0,
                             command=self.reset, accelerator='Del')
        filemenu.add_command(label='Print to Postscript', underline=0,
                             command=self.postscript, accelerator='Ctrl-p')
        filemenu.add_command(label='Exit', underline=1,
                             command=self.destroy, accelerator='Ctrl-x')
        menubar.add_cascade(label='File', underline=0, menu=filemenu)

        editmenu = Menu(menubar, tearoff=0)
        editmenu.add_command(label='Edit Grammar', underline=5,
                             command=self.edit_grammar,
                             accelerator='Ctrl-g')
        editmenu.add_command(label='Edit Text', underline=5,
                             command=self.edit_sentence,
                             accelerator='Ctrl-t')
        menubar.add_cascade(label='Edit', underline=0, menu=editmenu)

        rulemenu = Menu(menubar, tearoff=0)
        rulemenu.add_command(label='Step', underline=1,
                             command=self.step, accelerator='Space')
        rulemenu.add_separator()
        rulemenu.add_command(label='Shift', underline=0,
                             command=self.shift, accelerator='Ctrl-s')
        rulemenu.add_command(label='Reduce', underline=0,
                             command=self.reduce, accelerator='Ctrl-r')
        rulemenu.add_separator()
        rulemenu.add_command(label='Undo', underline=0,
                             command=self.undo, accelerator='Ctrl-u')
        menubar.add_cascade(label='Apply', underline=0, menu=rulemenu)

        viewmenu = Menu(menubar, tearoff=0)
        viewmenu.add_checkbutton(label="Show Grammar", underline=0,
                                 variable=self._show_grammar,
                                 command=self._toggle_grammar)
        viewmenu.add_separator()
        viewmenu.add_radiobutton(label='Tiny', variable=self._size,
                                 underline=0, value=10, command=self.resize)
        viewmenu.add_radiobutton(label='Small', variable=self._size,
                                 underline=0, value=12, command=self.resize)
        viewmenu.add_radiobutton(label='Medium', variable=self._size,
                                 underline=0, value=14, command=self.resize)
        viewmenu.add_radiobutton(label='Large', variable=self._size,
                                 underline=0, value=18, command=self.resize)
        viewmenu.add_radiobutton(label='Huge', variable=self._size,
                                 underline=0, value=24, command=self.resize)
        menubar.add_cascade(label='View', underline=0, menu=viewmenu)

        animatemenu = Menu(menubar, tearoff=0)
        animatemenu.add_radiobutton(label="No Animation", underline=0,
                                    variable=self._animate, value=0)
        animatemenu.add_radiobutton(label="Slow Animation", underline=0,
                                    variable=self._animate, value=20,
                                    accelerator='-')
        animatemenu.add_radiobutton(label="Normal Animation", underline=0,
                                    variable=self._animate, value=10,
                                    accelerator='=')
        animatemenu.add_radiobutton(label="Fast Animation", underline=0,
                                    variable=self._animate, value=4,
                                    accelerator='+')
        menubar.add_cascade(label="Animate", underline=1, menu=animatemenu)


        helpmenu = Menu(menubar, tearoff=0)
        helpmenu.add_command(label='About', underline=0,
                             command=self.about)
        helpmenu.add_command(label='Instructions', underline=0,
                             command=self.help, accelerator='F1')
        menubar.add_cascade(label='Help', underline=0, menu=helpmenu)

        parent.config(menu=menubar)

    def _init_feedback(self, parent):
        self._feedbackframe = feedbackframe = Frame(parent)
        feedbackframe.pack(fill='x', side='bottom', padx=3, pady=3)
        self._lastoper_label = Label(feedbackframe, text='Last Operation:',
                                     font=self._font)
        self._lastoper_label.pack(side='left')
        lastoperframe = Frame(feedbackframe, relief='sunken', border=1)
        lastoperframe.pack(fill='x', side='right', expand=1, padx=5)
        self._lastoper1 = Label(lastoperframe, foreground='#007070',
                                background='#f0f0f0', font=self._font)
        self._lastoper2 = Label(lastoperframe, anchor='w', width=30,
                                foreground='#004040', background='#f0f0f0',
                                font=self._font)
        self._lastoper1.pack(side='left')
        self._lastoper2.pack(side='left', fill='x', expand=1)

    def _init_canvas(self, parent):
        self._cframe = CanvasFrame(parent, background='white',
                                   width=525, closeenough=10,
                                   border=2, relief='sunken')
        self._cframe.pack(expand=1, fill='both', side='top', pady=2)
        canvas = self._canvas = self._cframe.canvas()

        self._stackwidgets = []
        self._rtextwidgets = []
        self._titlebar = canvas.create_rectangle(0,0,0,0, fill='#c0f0f0',
                                                 outline='black')
        self._exprline = canvas.create_line(0,0,0,0, dash='.')
        self._stacktop = canvas.create_line(0,0,0,0, fill='#408080')
        size = self._size.get()+4
        self._stacklabel = TextWidget(canvas, 'Stack', color='#004040',
                                      font=self._boldfont)
        self._rtextlabel = TextWidget(canvas, 'Remaining Text',
                                      color='#004040', font=self._boldfont)
        self._cframe.add_widget(self._stacklabel)
        self._cframe.add_widget(self._rtextlabel)

    #########################################
    ##  Main draw procedure
    #########################################

    def _redraw(self):
        scrollregion = self._canvas['scrollregion'].split()
        (cx1, cy1, cx2, cy2) = [int(c) for c in scrollregion]

        # Delete the old stack & rtext widgets.
        for stackwidget in self._stackwidgets:
            self._cframe.destroy_widget(stackwidget)
        self._stackwidgets = []
        for rtextwidget in self._rtextwidgets:
            self._cframe.destroy_widget(rtextwidget)
        self._rtextwidgets = []

        # Position the titlebar & exprline
        (x1, y1, x2, y2) = self._stacklabel.bbox()
        y = y2-y1+10
        self._canvas.coords(self._titlebar, -5000, 0, 5000, y-4)
        self._canvas.coords(self._exprline, 0, y*2-10, 5000, y*2-10)

        # Position the titlebar labels..
        (x1, y1, x2, y2) = self._stacklabel.bbox()
        self._stacklabel.move(5-x1, 3-y1)
        (x1, y1, x2, y2) = self._rtextlabel.bbox()
        self._rtextlabel.move(cx2-x2-5, 3-y1)

        # Draw the stack.
        stackx = 5
        for tok in self._parser.stack():
            if isinstance(tok, Tree):
                attribs = {'tree_color': '#4080a0', 'tree_width': 2,
                           'node_font': self._boldfont,
                           'node_color': '#006060',
                           'leaf_color': '#006060', 'leaf_font':self._font}
                widget = tree_to_treesegment(self._canvas, tok,
                                             **attribs)
                widget.label()['color'] = '#000000'
            else:
                widget = TextWidget(self._canvas, tok,
                                    color='#000000', font=self._font)
            widget.bind_click(self._popup_reduce)
            self._stackwidgets.append(widget)
            self._cframe.add_widget(widget, stackx, y)
            stackx = widget.bbox()[2] + 10

        # Draw the remaining text.
        rtextwidth = 0
        for tok in self._parser.remaining_text():
            widget = TextWidget(self._canvas, tok,
                                color='#000000', font=self._font)
            self._rtextwidgets.append(widget)
            self._cframe.add_widget(widget, rtextwidth, y)
            rtextwidth = widget.bbox()[2] + 4

        # Allow enough room to shift the next token (for animations)
        if len(self._rtextwidgets) > 0:
            stackx += self._rtextwidgets[0].width()

        # Move the remaining text to the correct location (keep it
        # right-justified, when possible); and move the remaining text
        # label, if necessary.
        stackx = max(stackx, self._stacklabel.width()+25)
        rlabelwidth = self._rtextlabel.width()+10
        if stackx >= cx2-max(rtextwidth, rlabelwidth):
            cx2 = stackx + max(rtextwidth, rlabelwidth)
        for rtextwidget in self._rtextwidgets:
            rtextwidget.move(4+cx2-rtextwidth, 0)
        self._rtextlabel.move(cx2-self._rtextlabel.bbox()[2]-5, 0)

        midx = (stackx + cx2-max(rtextwidth, rlabelwidth))/2
        self._canvas.coords(self._stacktop, midx, 0, midx, 5000)
        (x1, y1, x2, y2) = self._stacklabel.bbox()

        # Set up binding to allow them to shift a token by dragging it.
        if len(self._rtextwidgets) > 0:
            def drag_shift(widget, midx=midx, self=self):
                if widget.bbox()[0] < midx: self.shift()
                else: self._redraw()
            self._rtextwidgets[0].bind_drag(drag_shift)
            self._rtextwidgets[0].bind_click(self.shift)

        # Draw the stack top.
        self._highlight_productions()

    def _draw_stack_top(self, widget):
        # hack..
        midx = widget.bbox()[2]+50
        self._canvas.coords(self._stacktop, midx, 0, midx, 5000)

    def _highlight_productions(self):
        # Highlight the productions that can be reduced.
        self._prodlist.selection_clear(0, 'end')
        for prod in self._parser.reducible_productions():
            index = self._productions.index(prod)
            self._prodlist.selection_set(index)

    #########################################
    ##  Button Callbacks
    #########################################

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

    def reset(self, *e):
        self._parser.initialize(self._sent)
        self._lastoper1['text'] = 'Reset App'
        self._lastoper2['text'] = ''
        self._redraw()

    def step(self, *e):
        if self.reduce(): return True
        elif self.shift(): return True
        else:
            if list(self._parser.parses()):
                self._lastoper1['text'] = 'Finished:'
                self._lastoper2['text'] = 'Success'
            else:
                self._lastoper1['text'] = 'Finished:'
                self._lastoper2['text'] = 'Failure'

    def shift(self, *e):
        if self._animating_lock: return
        if self._parser.shift():
            tok = self._parser.stack()[-1]
            self._lastoper1['text'] = 'Shift:'
            self._lastoper2['text'] = '%r' % tok
            if self._animate.get():
                self._animate_shift()
            else:
                self._redraw()
            return True
        return False

    def reduce(self, *e):
        if self._animating_lock: return
        production = self._parser.reduce()
        if production:
            self._lastoper1['text'] = 'Reduce:'
            self._lastoper2['text'] = '%s' % production
            if self._animate.get():
                self._animate_reduce()
            else:
                self._redraw()
        return production

    def undo(self, *e):
        if self._animating_lock: return
        if self._parser.undo():
            self._redraw()

    def postscript(self, *e):
        self._cframe.print_to_file()

    def mainloop(self, *args, **kwargs):
        """
        Enter the Tkinter mainloop.  This function must be called if
        this demo is created from a non-interactive program (e.g.
        from a secript); otherwise, the demo will close as soon as
        the script completes.
        """
        if in_idle(): return
        self._top.mainloop(*args, **kwargs)

    #########################################
    ##  Menubar callbacks
    #########################################

    def resize(self, size=None):
        if size is not None: self._size.set(size)
        size = self._size.get()
        self._font.configure(size=-(abs(size)))
        self._boldfont.configure(size=-(abs(size)))
        self._sysfont.configure(size=-(abs(size)))

        #self._stacklabel['font'] = ('helvetica', -size-4, 'bold')
        #self._rtextlabel['font'] = ('helvetica', -size-4, 'bold')
        #self._lastoper_label['font'] = ('helvetica', -size)
        #self._lastoper1['font'] = ('helvetica', -size)
        #self._lastoper2['font'] = ('helvetica', -size)
        #self._prodlist['font'] = ('helvetica', -size)
        #self._prodlist_label['font'] = ('helvetica', -size-2, 'bold')
        self._redraw()

    def help(self, *e):
        # The default font's not very legible; try using 'fixed' instead.
        try:
            ShowText(self._top, 'Help: Shift-Reduce Parser Application',
                     (__doc__ or '').strip(), width=75, font='fixed')
        except:
            ShowText(self._top, 'Help: Shift-Reduce Parser Application',
                     (__doc__ or '').strip(), width=75)

    def about(self, *e):
        ABOUT = ("NLTK Shift-Reduce Parser Application\n"+
                 "Written by Edward Loper")
        TITLE = 'About: Shift-Reduce Parser Application'
        try:
            from tkinter.messagebox import Message
            Message(message=ABOUT, title=TITLE).show()
        except:
            ShowText(self._top, TITLE, ABOUT)

    def edit_grammar(self, *e):
        CFGEditor(self._top, self._parser.grammar(), self.set_grammar)

    def set_grammar(self, grammar):
        self._parser.set_grammar(grammar)
        self._productions = list(grammar.productions())
        self._prodlist.delete(0, 'end')
        for production in self._productions:
            self._prodlist.insert('end', (' %s' % production))

    def edit_sentence(self, *e):
        sentence = " ".join(self._sent)
        title = 'Edit Text'
        instr = 'Enter a new sentence to parse.'
        EntryDialog(self._top, sentence, instr, self.set_sentence, title)

    def set_sentence(self, sent):
        self._sent = sent.split() #[XX] use tagged?
        self.reset()

    #########################################
    ##  Reduce Production Selection
    #########################################

    def _toggle_grammar(self, *e):
        if self._show_grammar.get():
            self._prodframe.pack(fill='both', side='left', padx=2,
                                 after=self._feedbackframe)
            self._lastoper1['text'] = 'Show Grammar'
        else:
            self._prodframe.pack_forget()
            self._lastoper1['text'] = 'Hide Grammar'
        self._lastoper2['text'] = ''

    def _prodlist_select(self, event):
        selection = self._prodlist.curselection()
        if len(selection) != 1: return
        index = int(selection[0])
        production = self._parser.reduce(self._productions[index])
        if production:
            self._lastoper1['text'] = 'Reduce:'
            self._lastoper2['text'] = '%s' % production
            if self._animate.get():
                self._animate_reduce()
            else:
                self._redraw()
        else:
            # Reset the production selections.
            self._prodlist.selection_clear(0, 'end')
            for prod in self._parser.reducible_productions():
                index = self._productions.index(prod)
                self._prodlist.selection_set(index)

    def _popup_reduce(self, widget):
        # Remove old commands.
        productions = self._parser.reducible_productions()
        if len(productions) == 0: return

        self._reduce_menu.delete(0, 'end')
        for production in productions:
            self._reduce_menu.add_command(label=str(production),
                                          command=self.reduce)
        self._reduce_menu.post(self._canvas.winfo_pointerx(),
                               self._canvas.winfo_pointery())

    #########################################
    ##  Animations
    #########################################

    def _animate_shift(self):
        # What widget are we shifting?
        widget = self._rtextwidgets[0]

        # Where are we shifting from & to?
        right = widget.bbox()[0]
        if len(self._stackwidgets) == 0: left = 5
        else: left = self._stackwidgets[-1].bbox()[2]+10

        # Start animating.
        dt = self._animate.get()
        dx = (left-right)*1.0/dt
        self._animate_shift_frame(dt, widget, dx)

    def _animate_shift_frame(self, frame, widget, dx):
        if frame > 0:
            self._animating_lock = 1
            widget.move(dx, 0)
            self._top.after(10, self._animate_shift_frame,
                            frame-1, widget, dx)
        else:
            # but: stacktop??

            # Shift the widget to the stack.
            del self._rtextwidgets[0]
            self._stackwidgets.append(widget)
            self._animating_lock = 0

            # Display the available productions.
            self._draw_stack_top(widget)
            self._highlight_productions()

    def _animate_reduce(self):
        # What widgets are we shifting?
        numwidgets = len(self._parser.stack()[-1]) # number of children
        widgets = self._stackwidgets[-numwidgets:]

        # How far are we moving?
        if isinstance(widgets[0], TreeSegmentWidget):
            ydist = 15 + widgets[0].label().height()
        else:
            ydist = 15 + widgets[0].height()

        # Start animating.
        dt = self._animate.get()
        dy = ydist*2.0/dt
        self._animate_reduce_frame(dt/2, widgets, dy)

    def _animate_reduce_frame(self, frame, widgets, dy):
        if frame > 0:
            self._animating_lock = 1
            for widget in widgets: widget.move(0, dy)
            self._top.after(10, self._animate_reduce_frame,
                            frame-1, widgets, dy)
        else:
            del self._stackwidgets[-len(widgets):]
            for widget in widgets:
                self._cframe.remove_widget(widget)
            tok = self._parser.stack()[-1]
            if not isinstance(tok, Tree): raise ValueError()
            label = TextWidget(self._canvas, str(tok.label()), color='#006060',
                               font=self._boldfont)
            widget = TreeSegmentWidget(self._canvas, label, widgets,
                                       width=2)
            (x1, y1, x2, y2) = self._stacklabel.bbox()
            y = y2-y1+10
            if not self._stackwidgets: x = 5
            else: x = self._stackwidgets[-1].bbox()[2] + 10
            self._cframe.add_widget(widget, x, y)
            self._stackwidgets.append(widget)

            # Display the available productions.
            self._draw_stack_top(widget)
            self._highlight_productions()

#             # Delete the old widgets..
#             del self._stackwidgets[-len(widgets):]
#             for widget in widgets:
#                 self._cframe.destroy_widget(widget)
#
#             # Make a new one.
#             tok = self._parser.stack()[-1]
#             if isinstance(tok, Tree):
#                 attribs = {'tree_color': '#4080a0', 'tree_width': 2,
#                            'node_font': bold, 'node_color': '#006060',
#                            'leaf_color': '#006060', 'leaf_font':self._font}
#                 widget = tree_to_treesegment(self._canvas, tok.type(),
#                                              **attribs)
#                 widget.node()['color'] = '#000000'
#             else:
#                 widget = TextWidget(self._canvas, tok.type(),
#                                     color='#000000', font=self._font)
#             widget.bind_click(self._popup_reduce)
#             (x1, y1, x2, y2) = self._stacklabel.bbox()
#             y = y2-y1+10
#             if not self._stackwidgets: x = 5
#             else: x = self._stackwidgets[-1].bbox()[2] + 10
#             self._cframe.add_widget(widget, x, y)
#             self._stackwidgets.append(widget)

            #self._redraw()
            self._animating_lock = 0

    #########################################
    ##  Hovering.
    #########################################

    def _highlight_hover(self, event):
        # What production are we hovering over?
        index = self._prodlist.nearest(event.y)
        if self._hover == index: return

        # Clear any previous hover highlighting.
        self._clear_hover()

        # If the production corresponds to an available reduction,
        # highlight the stack.
        selection = [int(s) for s in self._prodlist.curselection()]
        if index in selection:
            rhslen = len(self._productions[index].rhs())
            for stackwidget in self._stackwidgets[-rhslen:]:
                if isinstance(stackwidget, TreeSegmentWidget):
                    stackwidget.label()['color'] = '#00a000'
                else:
                    stackwidget['color'] = '#00a000'

        # Remember what production we're hovering over.
        self._hover = index

    def _clear_hover(self, *event):
        # Clear any previous hover highlighting.
        if self._hover == -1: return
        self._hover = -1
        for stackwidget in self._stackwidgets:
            if isinstance(stackwidget, TreeSegmentWidget):
                stackwidget.label()['color'] = 'black'
            else:
                stackwidget['color'] = 'black'
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()
Esempio n. 36
0
class Application():
    def __init__(self, master, network, debug=False):
        """
        Init method for the Application class, this method is the GUI
        Class for our solution, it gets master (Tk root, network
        and debug (Open debug window if needded)
        :param master: The root Tk of the Application
        :param network: network is object from Network class (communication)
        :param debug: bool, to open or not..
        """
        self.init_constants(master, network)  # create constants
        self.__create_top_toolbar()
        self.__create_app_frame()
        self.bindings()
        self.__network.listen()  # network mainloop..
        if debug:
            self.debug = True
            self.open_debug_dialog()

    def init_constants(self, master, network):
        """
        This function contruct all the vital constant
        for this class it gets the root and the network
        and save them as constant of the class
        :param master: The root Tk of the Application
        :param network: network is object from Network class (communication)
        """
        self.__master_splinter = master
        self.__user_color = StringVar()
        self.__current_shape = None
        self.__drawing_shape = None
        self.__users_list = []
        self.__points = []  # private because I dont want that someone change them
        self.__network = network  # private for the same reason
        self.debug = False

    def __create_app_frame(self):
        """
        This function creates and pack (using grid) the main app frame
        (The left toolbar (users list) and the canvas
        """
        app_frame = Frame(self.__master_splinter)
        self.create_game_canvas(app_frame)
        self.create_left_toolbar(app_frame)
        app_frame.grid(row=1)

    def create_game_canvas(self, app_frame):
        """
        This function creates and pack the game canvas
        :param app_frame: Tk frame object
        """
        self.canvas = Canvas(app_frame, width=500, height=500, bg='white')
        self.canvas.grid(column=1)

    def __create_top_toolbar(self):
        """
        This function creates and pack the top toolbar (with all the colors, shapes
        and etc..
        """
        top_toolbar = Frame(self.__master_splinter)
        help_button = Button(top_toolbar, text="Help", command=self.open_help_dialog)
        help_button.grid(row=0, column=4)

        color_frame = self.create_color_frame(top_toolbar)
        color_frame.grid(row=0, column=0)

        empty_label = Label(top_toolbar, padx=20)
        empty_label.grid(column=1, row=0)

        my_shapes_frame = self.create_shape_buttons(top_toolbar)
        my_shapes_frame.grid(row=0, column=2)

        empty_label = Label(top_toolbar, padx=45)
        empty_label.grid(column=3, row=0)

        top_toolbar.grid(row=0)

    def create_left_toolbar(self, app_frame):
        """
        This function creates and pack the left toolbar
        :param app_frame: root for this toolbar.. (Frame obj)
        :return:
        """
        left_toolbar = Frame(app_frame)
        self.lb_users = Listbox(left_toolbar)
        self.lb_users.config(height=30)
        self.lb_users.grid(row=0, column=0)
        scroll_bar = Scrollbar(left_toolbar)
        scroll_bar.config(command=self.lb_users.yview)
        scroll_bar.grid(row=0, column=1, sticky='ns')
        left_toolbar.propagate("false")
        left_toolbar.grid(column=0, row=0)
        self.lb_users.config(yscrollcommand=scroll_bar.set)
        self.debug_event("Left toolbar was generated")

    def create_shape_buttons(self, root):
        """
        This function get a root and creates all the shapes
        buttons (because they have picture they need to
        compile and resize the icons...
        :param root: Tk frame
        :return: returns Frame object (it won`t pack it)
        """
        shapes_frame = Frame(root)
        shape_text = Label(shapes_frame, text="Shape: ")
        shape_text.grid(row=0, column=0)
        self.line_image = self.create_shape_img(SHAPES_DICT[LINE])
        line_btn = Button(shapes_frame,
                          image=self.line_image,
                          command=lambda: self.create_shape(LINE))
        line_btn.grid(row=0, column=1)
        self.square_image = self.create_shape_img(SHAPES_DICT[SQUARE])
        square_btn = Button(shapes_frame,
                            image=self.square_image,
                            command=lambda: self.create_shape(SQUARE))
        square_btn.grid(row=0, column=2)
        self.triangle_image = self.create_shape_img(SHAPES_DICT[TRIANGLE])
        triangle_btn = Button(shapes_frame,
                              image=self.triangle_image,
                              command=lambda: self.create_shape(TRIANGLE))
        triangle_btn.grid(row=0, column=3)
        self.elipse_image = self.create_shape_img(SHAPES_DICT[ELIPSE])
        elipse_btn = Button(shapes_frame,
                            image=self.elipse_image,
                            command=lambda: self.create_shape(ELIPSE))
        elipse_btn.grid(row=0, column=4)
        self.debug_event("shapes toolbar was generated")
        return shapes_frame

    def create_color_frame(self, root):
        """
        This function creates a color frame
        :param root: Frame obj
        :return: frame..
        """
        color_frame = Frame(root)
        color_text = Label(color_frame, text="Color:  ")
        color_text.grid(row=0, column=0)
        self.colors_list = ttk.Combobox(color_frame,
                                        textvariable=self.__user_color,
                                        values=COLOR_LIST,
                                        state="readonly")
        self.colors_list.grid(row=0, column=1)
        self.colors_list.current(FIRST_COLOR)
        self.debug_event("color toolbar was generated")
        return color_frame

    def create_shape_img(self, path):
        """
        This function get a path for picture.. and creates a
        icon in size of 32X32
        :param path:
        :return:
        """
        img = Image.open(path)
        img = img.resize(ICON_SIZE, Image.ANTIALIAS)
        return ImageTk.PhotoImage(img)



    def bindings(self):
        """
        This is our binding function.. it bind some things in the GUI
        some events like get new user, get clicks, close window
        """
        self.canvas.bind(LEFT_BUTTON_CLICK,
                         lambda event: self.try_draw_user_shape(event))
        self.__master_splinter.bind(JOIN_EVT,
                                    lambda x: self.change_users_list(JOIN_EVT, self.__network.get_event(JOIN_EVT)))
        self.__master_splinter.bind(LEAVE_EVT,
                                    lambda x: self.change_users_list(LEAVE_EVT, self.__network.get_event(LEAVE_EVT)))
        self.__master_splinter.bind(SHAPE_EVT, lambda event: self.shape_handler())
        self.__master_splinter.bind(USERS_EVT, lambda event: self.init_users())
        self.__master_splinter.protocol(CLOSE_WINDOW_PROT, self.on_close)

    def create_shape(self, shape_type):
        """
        After click on Shape this function appear :)
        it set the current shape to "shape type"
        :param shape_type: String repr shape type
        """
        self.canvas.config(cursor="target")
        self.__points = []
        self.__current_shape = shape_type
        self.debug_event("button " + shape_type + " clicked")

    def shape_handler(self):
        """
        This function handle new shapes events
        :return:
        """
        shape = self.__network.get_event(SHAPE_EVT)
        points = self.points_to_tuple(shape[COORDS])
        self.debug_event("shape msg:")
        self.debug_event(str(points))
        self.draw_shape(points, shape[SHAPE_TYPE], shape[USER], shape[COLOR])

    def init_users(self):
        """
        This function handle "connected" msg
        when connected it asks the communicator
        for users list, group name and user name
        and update the users list
        """
        group_name = self.__network.get_group()
        self.add_user_to_list(group_name + ":")
        user = self.__network.get_user_name()
        self.add_user_to_list(user)
        users = self.__network.get_user_list()
        self.debug_event("users list generated")
        for user in users:
            self.add_user_to_list(user)


    def try_draw_user_shape(self, event):
        """
        This function handles canvas clicks,
        after any click on the canvas this function
        checks if there was enough clicks to create
        the relevant shape (If shape is None it won`t happen..)
        :param event: event obj, contain the x,y of the click
        """
        # trying to draw
        if self.__current_shape is not self.__drawing_shape:
            # check if it is a new shape
            self.__drawing_shape = self.__current_shape
        self.__points.append((event.x, event.y))
        if len(self.__points) is POINTS_NEEDED[self.__drawing_shape]:  # Success
            self.send_shape_details_and_restart()
        self.debug_event("button is clicked in " + str(event.x) + "," + str(event.y))

    def send_shape_details_and_restart(self):
        """
        This function called when the user completed a shape
        it send to communicator a message the says "New shape was added"
        """
        self.__network.shape_msg([self.__drawing_shape, self.__points, self.__user_color.get()])
        self.__current_shape = None
        self.__drawing_shape = None
        self.__points = []
        self.canvas.config(cursor="")



    def draw_shape(self, points, s_type, user_name, color):
        """
        This function draw a new shape on the screen
        :param points: "x,y,z,w,a,b" string
        that each odd nu is x and each even is y
        :param s_type: shape type, string
        :param user_name: user_name string
        :param color: color, string
        """
        if s_type == LINE:
            self.canvas.create_line(points,
                                    fill=color, width=LINE_WIDTH)
        elif s_type == SQUARE:
            self.canvas.create_rectangle(points,
                                         fill=color)
        elif s_type == ELIPSE:
            self.canvas.create_oval(points,
                                    fill=color)
        elif s_type == TRIANGLE:
            self.canvas.create_polygon(points,
                                       fill=color)
        self.canvas.create_text(points[:FIRST_XY],
                                text=user_name)
        self.debug_event("draws: " + s_type)

    def points_to_tuple(self, str_points):
        """
        this function gets alot of numbers in string and returns
        :param str_points: "x,y,z,w,a,b" string
        that each odd nu is x and each even is y
        :return: list of coordinates as tuple in format (x,y,x,y,x,y)
        """
        nums = str_points.split(',')
        return tuple(nums)

    def open_help_dialog(self):
        """
        This function creates new "help" dialog
        :return:
        """
        try:
            self.help_frame.destroy()
        except:
            pass
        infromative_txt = self.get_informative_text()
        self.help_frame = Tk()
        self.help_frame.title(HELP_TITLE)
        infromative_text = Label(self.help_frame, text=infromative_txt)
        infromative_text.pack()
        self.help_frame.mainloop()

    def get_informative_text(self):
        f = open(INFO_DIR, READ_PREM)
        reader = f.read()
        f.close()
        return reader

    def open_debug_dialog(self):
        """
        this function create new "debug" dialog
        :return:
        """
        self.debug_frame = Tk()
        self.debug_frame.title(DEBUG_TITLE)
        self.debug_messages = Text(self.debug_frame)
        self.debug_messages.insert(END, "Messages")
        self.debug_messages.pack()
        self.debug_frame.mainloop()

    def debug_event(self, event):
        """
        This function check if the debug option is enabled
        if it is it will record the event in the debug messages dialog
        :param event: string repr event to debug..
        """
        if self.debug:
            self.debug_messages.insert(END, "\nEVENT: " + str(event))

    def on_close(self):
        """
        Handles closing the programe
        :return:
        """
        self.__network.leave_msg()
        self.__master_splinter.destroy()
        try:
            self.debug_frame.destroy()
            self.help_frame.destroy()
        except:
            pass

    def change_users_list(self, msg_type, user):
        """
        Handle "change user" event (Leave\Join)
        :param msg_type: CONSTANT, JOIN\LEAVE
        :param user: list of users..
        """
        users = user[ONE_USER]
        self.debug_event(user + " has " + msg_type)
        if msg_type is LEAVE_EVT:
            self.remove_user_from_list(users)
        elif msg_type is JOIN_EVT:
            self.add_user_to_list(users)

    def add_user_to_list(self, user):
        """
        Add specific user the list_box.. of users list
        :param user: string repr username
        """
        if user not in self.__users_list:
            self.__users_list.append(user)
            self.lb_users.insert(END, user)
        else:
            self.debug_event(user + " already exists")

    def remove_user_from_list(self, user):
        """
        This function tries to delete specific username
        from the list
        :param user: string repr username
        :return:
        """
        try:
            i = self.__users_list.index(user)
            self.lb_users.delete(i)
            self.__users_list.pop(i)
        except:
            self.debug_event(user + " is not in our list..")
Esempio n. 37
0
class GetKeysDialog(Toplevel):

    # Dialog title for invalid key sequence
    keyerror_title = 'Key Sequence Error'

    def __init__(self, parent, title, action, current_key_sequences,
                 *, _htest=False, _utest=False):
        """
        parent - parent of this dialog
        title - string which is the title of the popup dialog
        action - string, the name of the virtual event these keys will be
                 mapped to
        current_key_sequences - list, a list of all key sequence lists
                 currently mapped to virtual events, for overlap checking
        _htest - bool, change box location when running htest
        _utest - bool, do not wait when running unittest
        """
        Toplevel.__init__(self, parent)
        self.withdraw()  # Hide while setting geometry.
        self.configure(borderwidth=5)
        self.resizable(height=False, width=False)
        self.title(title)
        self.transient(parent)
        self.grab_set()
        self.protocol("WM_DELETE_WINDOW", self.cancel)
        self.parent = parent
        self.action = action
        self.current_key_sequences = current_key_sequences
        self.result = ''
        self.key_string = StringVar(self)
        self.key_string.set('')
        # Set self.modifiers, self.modifier_label.
        self.set_modifiers_for_platform()
        self.modifier_vars = []
        for modifier in self.modifiers:
            variable = StringVar(self)
            variable.set('')
            self.modifier_vars.append(variable)
        self.advanced = False
        self.create_widgets()
        self.update_idletasks()
        self.geometry(
                "+%d+%d" % (
                    parent.winfo_rootx() +
                    (parent.winfo_width()/2 - self.winfo_reqwidth()/2),
                    parent.winfo_rooty() +
                    ((parent.winfo_height()/2 - self.winfo_reqheight()/2)
                    if not _htest else 150)
                ) )  # Center dialog over parent (or below htest box).
        if not _utest:
            self.deiconify()  # Geometry set, unhide.
            self.wait_window()

    def showerror(self, *args, **kwargs):
        # Make testing easier.  Replace in #30751.
        messagebox.showerror(*args, **kwargs)

    def create_widgets(self):
        self.frame = frame = Frame(self, borderwidth=2, relief='sunken')
        frame.pack(side='top', expand=True, fill='both')

        frame_buttons = Frame(self)
        frame_buttons.pack(side='bottom', fill='x')

        self.button_ok = Button(frame_buttons, text='OK',
                                width=8, command=self.ok)
        self.button_ok.grid(row=0, column=0, padx=5, pady=5)
        self.button_cancel = Button(frame_buttons, text='Cancel',
                                   width=8, command=self.cancel)
        self.button_cancel.grid(row=0, column=1, padx=5, pady=5)

        # Basic entry key sequence.
        self.frame_keyseq_basic = Frame(frame, name='keyseq_basic')
        self.frame_keyseq_basic.grid(row=0, column=0, sticky='nsew',
                                      padx=5, pady=5)
        basic_title = Label(self.frame_keyseq_basic,
                            text=f"New keys for '{self.action}' :")
        basic_title.pack(anchor='w')

        basic_keys = Label(self.frame_keyseq_basic, justify='left',
                           textvariable=self.key_string, relief='groove',
                           borderwidth=2)
        basic_keys.pack(ipadx=5, ipady=5, fill='x')

        # Basic entry controls.
        self.frame_controls_basic = Frame(frame)
        self.frame_controls_basic.grid(row=1, column=0, sticky='nsew', padx=5)

        # Basic entry modifiers.
        self.modifier_checkbuttons = {}
        column = 0
        for modifier, variable in zip(self.modifiers, self.modifier_vars):
            label = self.modifier_label.get(modifier, modifier)
            check = Checkbutton(self.frame_controls_basic,
                                command=self.build_key_string, text=label,
                                variable=variable, onvalue=modifier, offvalue='')
            check.grid(row=0, column=column, padx=2, sticky='w')
            self.modifier_checkbuttons[modifier] = check
            column += 1

        # Basic entry help text.
        help_basic = Label(self.frame_controls_basic, justify='left',
                           text="Select the desired modifier keys\n"+
                                "above, and the final key from the\n"+
                                "list on the right.\n\n" +
                                "Use upper case Symbols when using\n" +
                                "the Shift modifier.  (Letters will be\n" +
                                "converted automatically.)")
        help_basic.grid(row=1, column=0, columnspan=4, padx=2, sticky='w')

        # Basic entry key list.
        self.list_keys_final = Listbox(self.frame_controls_basic, width=15,
                                       height=10, selectmode='single')
        self.list_keys_final.insert('end', *AVAILABLE_KEYS)
        self.list_keys_final.bind('<ButtonRelease-1>', self.final_key_selected)
        self.list_keys_final.grid(row=0, column=4, rowspan=4, sticky='ns')
        scroll_keys_final = Scrollbar(self.frame_controls_basic,
                                      orient='vertical',
                                      command=self.list_keys_final.yview)
        self.list_keys_final.config(yscrollcommand=scroll_keys_final.set)
        scroll_keys_final.grid(row=0, column=5, rowspan=4, sticky='ns')
        self.button_clear = Button(self.frame_controls_basic,
                                   text='Clear Keys',
                                   command=self.clear_key_seq)
        self.button_clear.grid(row=2, column=0, columnspan=4)

        # Advanced entry key sequence.
        self.frame_keyseq_advanced = Frame(frame, name='keyseq_advanced')
        self.frame_keyseq_advanced.grid(row=0, column=0, sticky='nsew',
                                         padx=5, pady=5)
        advanced_title = Label(self.frame_keyseq_advanced, justify='left',
                               text=f"Enter new binding(s) for '{self.action}' :\n" +
                                     "(These bindings will not be checked for validity!)")
        advanced_title.pack(anchor='w')
        self.advanced_keys = Entry(self.frame_keyseq_advanced,
                                   textvariable=self.key_string)
        self.advanced_keys.pack(fill='x')

        # Advanced entry help text.
        self.frame_help_advanced = Frame(frame)
        self.frame_help_advanced.grid(row=1, column=0, sticky='nsew', padx=5)
        help_advanced = Label(self.frame_help_advanced, justify='left',
            text="Key bindings are specified using Tkinter keysyms as\n"+
                 "in these samples: <Control-f>, <Shift-F2>, <F12>,\n"
                 "<Control-space>, <Meta-less>, <Control-Alt-Shift-X>.\n"
                 "Upper case is used when the Shift modifier is present!\n\n" +
                 "'Emacs style' multi-keystroke bindings are specified as\n" +
                 "follows: <Control-x><Control-y>, where the first key\n" +
                 "is the 'do-nothing' keybinding.\n\n" +
                 "Multiple separate bindings for one action should be\n"+
                 "separated by a space, eg., <Alt-v> <Meta-v>." )
        help_advanced.grid(row=0, column=0, sticky='nsew')

        # Switch between basic and advanced.
        self.button_level = Button(frame, command=self.toggle_level,
                                  text='<< Basic Key Binding Entry')
        self.button_level.grid(row=2, column=0, stick='ew', padx=5, pady=5)
        self.toggle_level()

    def set_modifiers_for_platform(self):
        """Determine list of names of key modifiers for this platform.

        The names are used to build Tk bindings -- it doesn't matter if the
        keyboard has these keys; it matters if Tk understands them.  The
        order is also important: key binding equality depends on it, so
        config-keys.def must use the same ordering.
        """
        if sys.platform == "darwin":
            self.modifiers = ['Shift', 'Control', 'Option', 'Command']
        else:
            self.modifiers = ['Control', 'Alt', 'Shift']
        self.modifier_label = {'Control': 'Ctrl'}  # Short name.

    def toggle_level(self):
        "Toggle between basic and advanced keys."
        if  self.button_level.cget('text').startswith('Advanced'):
            self.clear_key_seq()
            self.button_level.config(text='<< Basic Key Binding Entry')
            self.frame_keyseq_advanced.lift()
            self.frame_help_advanced.lift()
            self.advanced_keys.focus_set()
            self.advanced = True
        else:
            self.clear_key_seq()
            self.button_level.config(text='Advanced Key Binding Entry >>')
            self.frame_keyseq_basic.lift()
            self.frame_controls_basic.lift()
            self.advanced = False

    def final_key_selected(self, event=None):
        "Handler for clicking on key in basic settings list."
        self.build_key_string()

    def build_key_string(self):
        "Create formatted string of modifiers plus the key."
        keylist = modifiers = self.get_modifiers()
        final_key = self.list_keys_final.get('anchor')
        if final_key:
            final_key = translate_key(final_key, modifiers)
            keylist.append(final_key)
        self.key_string.set(f"<{'-'.join(keylist)}>")

    def get_modifiers(self):
        "Return ordered list of modifiers that have been selected."
        mod_list = [variable.get() for variable in self.modifier_vars]
        return [mod for mod in mod_list if mod]

    def clear_key_seq(self):
        "Clear modifiers and keys selection."
        self.list_keys_final.select_clear(0, 'end')
        self.list_keys_final.yview('moveto', '0.0')
        for variable in self.modifier_vars:
            variable.set('')
        self.key_string.set('')

    def ok(self, event=None):
        keys = self.key_string.get().strip()
        if not keys:
            self.showerror(title=self.keyerror_title, parent=self,
                           message="No key specified.")
            return
        if (self.advanced or self.keys_ok(keys)) and self.bind_ok(keys):
            self.result = keys
        self.grab_release()
        self.destroy()

    def cancel(self, event=None):
        self.result = ''
        self.grab_release()
        self.destroy()

    def keys_ok(self, keys):
        """Validity check on user's 'basic' keybinding selection.

        Doesn't check the string produced by the advanced dialog because
        'modifiers' isn't set.
        """
        final_key = self.list_keys_final.get('anchor')
        modifiers = self.get_modifiers()
        title = self.keyerror_title
        key_sequences = [key for keylist in self.current_key_sequences
                             for key in keylist]
        if not keys.endswith('>'):
            self.showerror(title, parent=self,
                           message='Missing the final Key')
        elif (not modifiers
              and final_key not in FUNCTION_KEYS + MOVE_KEYS):
            self.showerror(title=title, parent=self,
                           message='No modifier key(s) specified.')
        elif (modifiers == ['Shift']) \
                 and (final_key not in
                      FUNCTION_KEYS + MOVE_KEYS + ('Tab', 'Space')):
            msg = 'The shift modifier by itself may not be used with'\
                  ' this key symbol.'
            self.showerror(title=title, parent=self, message=msg)
        elif keys in key_sequences:
            msg = 'This key combination is already in use.'
            self.showerror(title=title, parent=self, message=msg)
        else:
            return True
        return False

    def bind_ok(self, keys):
        "Return True if Tcl accepts the new keys else show message."
        try:
            binding = self.bind(keys, lambda: None)
        except TclError as err:
            self.showerror(
                    title=self.keyerror_title, parent=self,
                    message=(f'The entered key sequence is not accepted.\n\n'
                             f'Error: {err}'))
            return False
        else:
            self.unbind(keys, binding)
            return True
Esempio n. 38
0
class App(Frame):
    version = "0.1"
    padding = 10
    screenWidth = 800
    screenHeight = 600

    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent

        self.py = pydle()

        self._initUI()

    def _initUI(self):
        self.parent.title("Pydle v" + self.version)
        self.parent.minsize(width=str(self.screenWidth), height=str(self.screenHeight))
        # self.parent.config(border=0)

        # Styles
        style = Style()
        style.configure("TFrame", background="gray", border=0)
        style.configure("TButton", background="gray", foreground="lightgray", highlightforeground="black", highlightbackground="darkgray", compound=RIGHT, relief=FLAT)

        self.config(style="TFrame")
        self.pack(fill=BOTH, expand=1)

        # Menus
        mnuBar = Menu(self.parent)
        self.parent.config(menu=mnuBar)

        mnuFile = Menu(mnuBar, background="gray")
        mnuFile.add_command(label="Exit", command=self.onExitMnu)
        mnuBar.add_cascade(label="File", menu=mnuFile)

        mnuHelp = Menu(mnuBar, background="gray")
        mnuHelp.add_command(label="About", command=self.onAboutMnu)
        mnuBar.add_cascade(label="Help", menu=mnuHelp)

        # Frame content
        frmBooks = Frame(self, style="TFrame")
        frmBooks.pack(side=LEFT, anchor=N+W, fill=BOTH, expand=1, padx=(self.padding, self.padding / 2), pady=self.padding)

        self.lstBooks = Listbox(frmBooks)
        self.lstBooks.config(background="lightgray", foreground="black", borderwidth=0)
        self.lstBooks.pack(fill=BOTH, expand=1)

        frmButtons = Frame(self)
        frmButtons.pack(anchor=N+E, padx=(self.padding / 2, self.padding), pady=self.padding)

        btnLoadBooks = Button(frmButtons, text="Load Books", style="TButton", command=self.onLoadBooksBtn)
        btnLoadBooks.pack(side=TOP, fill=X)

        btnGetNotes = Button(frmButtons, text="Get Notes", style="TButton", command=self.onGetNotesBtn)
        btnGetNotes.pack(side=TOP, fill=X)

        btnBackupBook = Button(frmButtons, text="Backup Book", style="TButton", command=self.onBackupBtn)
        btnBackupBook.pack(side=TOP, fill=X)

        btnBackupAllBooks = Button(frmButtons, text="Backup All Books", style="TButton", command=self.onBackupAllBtn)
        btnBackupAllBooks.pack(side=TOP, fill=X)

    def onLoadBooksBtn(self):
        books = self.py.getBooks()

        for book in books:
            self.lstBooks.insert(END, book["name"])

    def onBackupBtn(self):
        pass

    def onBackupAllBtn(self):
        pass

    def onGetNotesBtn(self):
        notes = self.py.getNotes()

        for note in notes:
            self.lstBooks.insert(END, note)

    def onAboutMnu(self):
        pass

    def onExitMnu(self):
        self.onExit()

    def onExit(self):
        self.quit()
Esempio n. 39
0
class ListChooserDialog:

	def __init__(self, parent, listEntries, guiPrompt, allowManualFolderSelection, forceFolderOnlyChoosing=False):
		"""
		NOTE: do not call this constructor directly. Use the ListChooserDialog.showDialog function instead.
		"""
		self.forceFolderOnlyChoosing = forceFolderOnlyChoosing

		self.top = tkinter.Toplevel(parent)
		defaultPadding = {"padx":20, "pady":10}

		# Set a description for this dialog (eg "Please choose a game to mod"
		tkinter.Label(self.top, text=guiPrompt).pack()

		# Define the main listbox to hold the choices given by the 'listEntries' parameter
		listboxFrame = tkinter.Frame(self.top)

		# Define a scrollbar and a listbox. The yscrollcommand is so that the listbox can control the scrollbar
		scrollbar = tkinter.Scrollbar(listboxFrame, orient=tkinter.VERTICAL)
		self.listbox = Listbox(listboxFrame, selectmode=tkinter.BROWSE, yscrollcommand=scrollbar.set)

		# Also configure the scrollbar to control the listbox, and pack it
		scrollbar.config(command=self.listbox.yview)
		scrollbar.pack(side=tkinter.RIGHT, fill=tkinter.Y)

		# Setting width to 0 forces auto-resize of listbox see: https://stackoverflow.com/a/26504193/848627
		for item in listEntries:
			self.listbox.insert(tkinter.END, item)
		self.listbox.config(width=0)
		self.listbox.pack(side=tkinter.LEFT, fill=tkinter.BOTH, expand=1)

		# Finally, pack the Frame so its contents are displayed on the dialog
		listboxFrame.pack(**defaultPadding)

		# If the user is allowed to choose a directory manually, add directory chooser button
		if allowManualFolderSelection:
			b2 = tkinter.Button(self.top, text="Choose Folder Manually", command=self.showDirectoryChooser)
			b2.pack(**defaultPadding)

		# Add an 'OK' button. When pressed, the dialog is closed
		b = tkinter.Button(self.top, text="OK", command=self.ok)
		b.pack(**defaultPadding)

		# This variable stores the returned value from the dialog
		self.result = None

	def showDirectoryChooser(self):
		if IS_MAC and not self.forceFolderOnlyChoosing:
			self.result = filedialog.askopenfilename(filetypes=[(None, "com.apple.application")])
		else:
			self.result = filedialog.askdirectory()
		self.top.destroy()

	def ok(self):
		"""
		This function is called when the 'OK' button is pressed. It retrieves the value of the currently selected item,
		then closes the dialog
		:return:
		"""
		selected_value = None

		if len(self.listbox.curselection()) > 0:
			selected_index = self.listbox.curselection()[0]
			selected_value = self.listbox.get(selected_index)

		self.result = selected_value

		self.top.destroy()

	@staticmethod
	def showDialog(rootGUIWindow, choiceList, guiPrompt, allowManualFolderSelection, forceFolderOnlyChoosing=False):
		"""
		Static helper function to show dialog and get a return value. Arguments are the same as constructor
		:param rootGUIWindow: the parent tkinter object of the dialog (can be root window)
		:param choiceList: a list of strings that the user is to choose from
		:param guiPrompt: the description that will be shown on the dialog
		:param allowManualFolderSelection: if true, user is allowed to select a folder manually.
		:return: returns the value the user selected (string), or None if none available
		"""
		d = ListChooserDialog(rootGUIWindow, choiceList, guiPrompt, allowManualFolderSelection, forceFolderOnlyChoosing)
		rootGUIWindow.wait_window(d.top)
		return d.result
Esempio n. 40
0
class ListboxVidget(Vidget, Eventor):
    """
    ListboxVidget contains a Listbox widget. It adds the following abilities:
    - Store items of any type, unlike Listbox widget that only stores texts.
    - Remember selected item even if the listbox widget lost focus.
    - Notify pre-change and post-change events.
    """

    # Error raised when trying to change the listbox while a change is going on
    class CircularCallError(ValueError):
        pass

    # Error raised when trying to change the listbox while it is disabled
    class DisabledError(ValueError):
        pass

    # Event notified when the listbox's items are to be changed
    ITEMS_CHANGE_SOON = 'ITEMS_CHANGE_SOON'

    # Event notified when the listbox's items are changed
    ITEMS_CHANGE_DONE = 'ITEMS_CHANGE_DONE'

    # Event notified when the listbox's active item is to be changed
    ITEMCUR_CHANGE_SOON = 'ITEMCUR_CHANGE_SOON'

    # Event notified when the listbox's active item is changed
    ITEMCUR_CHANGE_DONE = 'ITEMCUR_CHANGE_DONE'

    # Events list
    EVENTS = (
        ITEMS_CHANGE_SOON,
        ITEMS_CHANGE_DONE,
        ITEMCUR_CHANGE_SOON,
        ITEMCUR_CHANGE_DONE,
    )

    def __init__(
        self,
        items=None,
        item_to_text=None,
        normal_bg='',
        normal_fg='',
        active_bg='sky blue',
        active_fg='white',
        selected_bg='steel blue',
        selected_fg='white',
        master=None,
    ):
        """
        Initialize object.

        @param items: Items list.

        @param item_to_text: Item-to-text function. Default is `str`.

        @param normal_bg: Unselected item background color.

        @param normal_fg: Unselected item foreground color.

        @param active_bg: Active item background color. `Active` means the item
        is selected (in general meaning) but the listbox has no focus.

        @param active_fg: Active item foreground color. `Active` means the item
        is selected (in general meaning) but the listbox has no focus.

        @param selected_bg: Selected item background color. `Selected` means
        the item is selected (in general meaning) and the listbox has focus.

        @param selected_fg: Selected item foreground color. `Selected` means
        the item is selected (in general meaning) and the listbox has focus.

        @param master: Master widget.

        @return: None.
        """
        # Initialize Vidget.
        # Create main frame widget.
        Vidget.__init__(
            self,
            master=master,
        )

        # Initialize Eventor
        Eventor.__init__(self)

        # If items list is given
        if items is not None:
            # If items list is not list
            if not isinstance(items, list):
                # Raise error
                raise TypeError(items)

            # If items list is list.

        # If items list is not given, or items list is given and is list

        # Items list
        self._items = items if items is not None else []

        # Item-to-text function. Default is `str`.
        self._item_to_text = item_to_text if item_to_text is not None else str

        # Unselected item background color
        self._normal_fg = normal_fg

        # Unselected item foreground color
        self._normal_bg = normal_bg

        # Active item background color
        self._active_fg = active_fg

        # Active item foreground color
        self._active_bg = active_bg

        # Selected item background color
        self._selected_fg = selected_fg

        # Selected item foreground color
        self._selected_bg = selected_bg

        # Whether the listbox is changing
        self._is_changing = False

        # Active index. `-1` means void, i.e. no item is active.
        self._indexcur = -1

        # Whether active index is being reset to same value
        self._is_resetting = False

        # Create listbox widget
        self._listbox = Listbox(
            master=self.widget(),
            relief='groove',
            activestyle='none',
            highlightthickness=0,
            # Active index cache only supports single-selection mode for now.
            # See 2N6OR.
            selectmode='single',
        )

        # Set the listbox widget as config target
        self.config_target_set(self._listbox)

        # Create x-axis scrollbar
        self._scrollbar_xview = _HiddenScrollbar(
            self.widget(),
            orient=HORIZONTAL,
        )

        # Create y-axis scrollbar
        self._scrollbar_yview = _HiddenScrollbar(
            self.widget(),
            orient=VERTICAL,
        )

        # Mount scrollbars
        self._listbox.config(xscrollcommand=self._scrollbar_xview.set)

        self._listbox.config(yscrollcommand=self._scrollbar_yview.set)

        self._scrollbar_xview.config(command=self._listbox.xview)

        self._scrollbar_yview.config(command=self._listbox.yview)

        # Bind single-click event handler
        self._listbox.bind('<Button-1>', self._on_single_click)

        # Bind double-click event handler
        self._listbox.bind('<Double-Button-1>', self._on_double_click)

        # Update listbox widget
        self._listbox_widget_update(keep_active=False)

        # Update widget
        self._widget_update()

    def _widget_update(self):
        """
        Update widget.

        @return: None.
        """
        # Row 0 for listbox and y-axis scrollbar
        self.widget().rowconfigure(0, weight=1)

        # Row 1 for x-axis scrollbar
        self.widget().rowconfigure(1, weight=0)

        # Column 0 for listbox and x-axis scrollbar
        self.widget().columnconfigure(0, weight=1)

        # Column 1 for y-axis scrollbar
        self.widget().columnconfigure(1, weight=0)

        # Lay out listbox
        self._listbox.grid(row=0, column=0, sticky='NSEW')

        # Lay out x-axis scrollbar
        self._scrollbar_xview.grid(row=1, column=0, sticky='EW')

        # Lay out y-axis scrollbar
        self._scrollbar_yview.grid(row=0, column=1, sticky='NS')

    def is_enabled(self):
        """
        Test whether the listbox is enabled.

        @return: Boolean.
        """
        # Return whether the listbox is enabled
        return self._listbox.config('state')[4] != DISABLED

    def is_changing(self):
        """
        Test whether the listbox is changing.

        @return: Boolean.
        """
        # Return whether the listbox is changing
        return self._is_changing

    def is_resetting(self):
        """
        Test whether the listbox is setting active index to the same value.

        @return: Boolean.
        """
        # Return whether the listbox is setting active index to the same value
        return self._is_resetting

    def size(self):
        """
        Get number of items.

        @return: Number of items.
        """
        # Return number of items
        return len(self._items)

    def items(self):
        """
        Get items list.
        Notice do not change the list outside.

        @return: Items list.
        """
        # Return items list
        return self._items

    def items_set(
        self,
        items,
        notify=True,
        keep_active=False,
    ):
        """
        Set items list.

        Notice do not change the list outside.

        @param items: Items list.

        @param notify: Whether notify pre-change and post-change events.

        @param keep_active: Whether keep or clear active index.

        @return: None.
        """
        # If the items is not list
        if not isinstance(items, list):
            # Raise error
            raise TypeError(items)

        # If the items is list.

        # If the listbox is disabled
        if not self.is_enabled():
            # Raise error
            raise ListboxVidget.DisabledError()

        # If the listbox is not disabled.

        # If the listbox is changing
        if self._is_changing:
            # Raise error
            raise ListboxVidget.CircularCallError()

        # If the listbox is not changing.

        # Set changing flag on
        self._is_changing = True

        # If notify events
        if notify:
            # Notify pre-change event
            self.handler_notify(self.ITEMS_CHANGE_SOON)

        # Store the new items
        self._items = items

        # Update listbox widget
        self._listbox_widget_update(
            keep_active=keep_active
        )

        # If notify events
        if notify:
            # Notify post-change event
            self.handler_notify(self.ITEMS_CHANGE_DONE)

        # Set changing flag off
        self._is_changing = False

    def index_is_valid(self, index):
        """
        Test whether given index is valid. Notice -1 is not valid.

        @param index: Index to test.

        @return: Boolean.
        """
        # Test whether given index is valid
        return 0 <= index and index < self.size()

    def index_is_valid_or_void(self, index):
        """
        Test whether given index is valid or is -1.

        @param index: Index to test.

        @return: Boolean.
        """
        # Test whether given index is valid or is -1
        return index == -1 or self.index_is_valid(index)

    def index_first(self):
        """
        Get the first item's index.

        @return: First item's index, or -1 if the listbox is empty.
        """
        # Return the first item's index
        return 0 if self.size() > 0 else -1

    def index_last(self):
        """
        Get the last item's index.

        @return: Last item's index, or -1 if the listbox is empty.
        """
        # Return the last item's index
        return self.size() - 1

    def indexcur(self, internal=False, raise_error=False):
        """
        Get the active index.

        @param internal: See 2N6OR.

        @return: The active index. If no active active, either return -1, or
        raise IndexError if `raise_error` is True.
        """
        # Get active indexes
        indexcurs = self._indexcurs(internal=internal)

        # If have active indexes
        if indexcurs:
            # Return the first active index
            return indexcurs[0]

        # If no active indexes
        else:
            # If raise error
            if raise_error:
                # Raise error
                raise IndexError(-1)

            # If not raise error
            else:
                # Return -1
                return -1

    def _indexcurs(self, internal=False):
        """
        Get active indexes list.

        2N6OR
        @param internal: Whether use listbox widget's selected indexes, instead
        of cached active index.
        Notice listbox widget has no selected indexes if it has no focus.
        Notice using cached active index only supports single-selection mode,
        which means the result list has at most one index.

        @return: Active indexes list.
        """
        # If use listbox widget's selected indexes
        if internal:
            # Return listbox widget's selected indexes list
            return [int(x) for x in self._listbox.curselection()]

        # If not use listbox widget's selected indexes
        else:
            # If cached active index is valid
            if self.index_is_valid(self._indexcur):
                # Return a list with the cached active index
                return [self._indexcur]

            # If cached active index is not valid
            else:
                # Return empty list
                return []

    def indexcur_set(
        self,
        index,
        focus=False,
        notify=True,
        notify_arg=None,
    ):
        """
        Set active index.

        @param index: The index to set.

        @param focus: Whether set focus on the listbox widget.

        @param notify: Whether notify pre-change and post-change events.

        @param notify_arg: Event argument.

        @return: None.
        """
        # If the index is not valid or -1
        if not self.index_is_valid_or_void(index):
            # Raise error
            raise IndexError(index)

        # If the index is valid or is -1.

        # If the listbox is not enabled
        if not self.is_enabled():
            # Raise error
            raise ListboxVidget.DisabledError()

        # If the listbox is enabled.

        # If the listbox is changing
        if self._is_changing:
            # Raise error
            raise ListboxVidget.CircularCallError()

        # If the listbox is not changing.

        # Set changing flag on
        self._is_changing = True

        # Get old active index
        old_indexcur = self._indexcur

        # Set resetting flag on if new and old indexes are equal
        self._is_resetting = (index == old_indexcur)

        # If notify events
        if notify:
            # Notify pre-change event
            self.handler_notify(self.ITEMCUR_CHANGE_SOON, notify_arg)

        # If old active index is valid
        if self.index_is_valid(old_indexcur):
            # Set old active item's background color to normal color
            self._listbox.itemconfig(old_indexcur, background=self._normal_bg)

            # Set old active item's foreground color to normal color
            self._listbox.itemconfig(old_indexcur, foreground=self._normal_fg)

        # Cache new active index
        self._indexcur = index

        # Clear listbox widget's selection
        self._listbox.selection_clear(0, END)

        # Set listbox widget's selection
        self._listbox.selection_set(index)

        # Set listbox widget's activated index
        self._listbox.activate(index)

        # If new active index is valid
        if index != -1:
            # Set new active item's background color to active color
            self._listbox.itemconfig(index, background=self._active_bg)

            # Set new active item's foreground color to active color
            self._listbox.itemconfig(index, foreground=self._active_fg)

        # If set focus
        if focus:
            # Set focus on the listbox widget
            self._listbox.focus_set()

        # If new active index is valid
        if index != -1:
            # Make the active item visible
            self._listbox.see(index)

        # If notify events
        if notify:
            # Notify post-change event
            self.handler_notify(self.ITEMCUR_CHANGE_DONE, notify_arg)

        # Set resetting flag off
        self._is_resetting = False

        # Set changing flag off
        self._is_changing = False

    def indexcur_set_by_event(
        self,
        event,
        focus=False,
        notify=True,
        notify_arg=None,
    ):
        """
        Set active index using a Tkinter event object that contains coordinates
        of the active item.

        @param event: Tkinter event object.

        @param focus: Whether set focus on the listbox widget.

        @param notify: Whether notify pre-change and post-change events.

        @param notify_arg: Event argument.

        @return: None.
        """
        # Get the event's y co-ordinate's nearest listbox item index
        index = self._listbox.nearest(event.y)

        # If the index is not valid
        if not self.index_is_valid_or_void(index):
            # Ignore the event
            return

        # If the index is valid
        else:
            # Set the index as active index
            self.indexcur_set(
                index=index,
                focus=focus,
                notify=notify,
                notify_arg=notify_arg,
            )

    def item(self, index):
        """
        Get item at given index.

        @return: Item at given index, or IndexError if the index is not valid.
        """
        return self.items()[index]

    def itemcur(self, internal=False, raise_error=False):
        """
        Get the active item.

        @param internal: See 2N6OR.

        @param raise_error: Whether raise error if no active item.

        @return: The active item. If no active item, if `raise_error` is
        True, raise IndexError, otherwise return None.
        """
        # Get active index.
        # May raise IndexError if `raise_error` is True.
        indexcur = self.indexcur(
            internal=internal,
            raise_error=raise_error,
        )

        # If no active index
        if indexcur == -1:
            # Return None
            return None

        # If have active index
        else:
            # Return the active item
            return self.items()[indexcur]

    def item_insert(
        self,
        item,
        index=None,
        notify=True,
        keep_active=True,
    ):
        """
        Insert item at given index.

        @param item: Item to insert.

        @param index: Index to insert. `None` means active index, and if no
        active index, insert at the end.

        @param notify: Whether notify pre-change and post-change events.

        @param keep_active: Whether keep or clear active index.

        @return: None.
        """
        # If notify events
        if notify:
            # Notify pre-change events
            self.handler_notify(self.ITEMCUR_CHANGE_SOON)

            self.handler_notify(self.ITEMS_CHANGE_SOON)

        # Get old active index
        active_index = self.indexcur()

        # If the index is None,
        # it means use active index.
        if index is None:
            # Use active index.
            # `-1` works and means appending.
            index = active_index

        # Insert the item to the items list
        self._items.insert(index, item)

        # If old active index is valid
        if active_index != -1:
            # If old active index is GE the inserted index
            if active_index >= index:
                # Shift active index by one
                active_index += 1

            # If old active index is not GE the inserted index, use it as-is.

        # Set new active index
        self.indexcur_set(index=active_index, notify=False)

        # Update listbox widget
        self._listbox_widget_update(
            keep_active=keep_active
        )

        # If notify events
        if notify:
            # Notify post-change events
            self.handler_notify(self.ITEMS_CHANGE_DONE)

            self.handler_notify(self.ITEMCUR_CHANGE_DONE)

    def item_remove(
        self,
        index,
        notify=True,
        keep_active=True,
    ):
        """
        Remove item at given index.

        @param index: Index to remove.

        @param notify: Whether notify pre-change and post-change events.

        @param keep_active: Whether keep or clear active index.

        @return: None.
        """
        # If the index is not valid
        if not self.index_is_valid(index):
            # Raise error
            raise ValueError(index)

        # If the index is valid.

        # If notify events
        if notify:
            # Notify pre-change events
            self.handler_notify(self.ITEMCUR_CHANGE_SOON)

            self.handler_notify(self.ITEMS_CHANGE_SOON)

        # Get old active index
        active_index = self.indexcur()

        # Remove item at the index
        del self._items[index]

        # If old active index is valid
        if active_index != -1:
            # Get the last index
            index_last = self.index_last()

            # If old active index is GT the last index
            if active_index > index_last:
                # Use the last index as new active index
                active_index = index_last

            # If old active index is not GT the last index, use it as-is.

        # Set new active index
        self.indexcur_set(index=active_index, notify=False)

        # Update listbox widget
        self._listbox_widget_update(
            keep_active=keep_active
        )

        # If notify events
        if notify:
            # Notify post-change events
            self.handler_notify(self.ITEMS_CHANGE_DONE)

            self.handler_notify(self.ITEMCUR_CHANGE_DONE)

    def handler_add(
        self,
        event,
        handler,
        need_arg=False,
    ):
        """
        Add event handler for an event.
        If the event is ListboxVidget event, add the event handler to Eventor.
        If the event is not ListboxVidget event, add the event handler to
        listbox widget.

        Notice this method overrides `Eventor.handler_add` in order to add
        non-ListboxVidget event handler to listbox widget.

        @param event: Event name.

        @param handler: Event handler.

        @param need_arg: Whether the event handler needs event argument.

        @return: None.
        """
        # If the event is ListboxVidget event
        if event in self.EVENTS:
            # Add the event handler to Eventor
            return Eventor.handler_add(
                self,
                event=event,
                handler=handler,
                need_arg=need_arg,
            )

        # If the event is not ListboxVidget event,
        # it is assumed to be Tkinter widget event.
        else:
            # Add the event handler to listbox widget
            return self.bind(
                event=event,
                handler=handler,
            )

    def bind(
        self,
        event,
        handler,
    ):
        """
        Add event handler to listbox widget.

        ListboxVidget internally uses `<Button-1>` and `<Double-Button-1>` to
        capture active index changes. So if the given event is `<Button-1>` or
        `<Double-Button-1>`, the given handler will be wrapped.

        @param event: Event name.

        @param handler: Event handler.

        @return: None.
        """
        # If the event is not `<Button-1>` or `<Double-Button-1>`
        if event not in ['<Button-1>', '<Double-Button-1>']:
            # Add the event handler to listbox widget
            self._listbox.bind(event, handler)

        # If the event is `<Button-1>` or `<Double-Button-1>`
        else:
            # Create event handler wrapper
            def handler_wrapper(e):
                """
                Event handler wrapper that sets new active index and then calls
                the wrapped event handler.

                Setting new active index is needed because when this handler is
                called by Tkinter, the active index of the listbox is still
                old.

                @param e: Tkinter event object.

                @return: None.
                """
                # Set new active index
                self.indexcur_set_by_event(e, notify=True)

                # Call the wrapped event handler
                handler(e)

            # Add the event handler wrapper to the listbox widget
            self._listbox.bind(event, handler_wrapper)

    def _on_single_click(self, event):
        """
        `<Button-1>` event handler that updates active index.

        @param event: Tkinter event object.

        @return: None.
        """
        # Updates active index
        self.indexcur_set_by_event(event, notify=True)

    def _on_double_click(self, event):
        """
        `<Double-Button-1>` event handler that updates active index.

        @param event: Tkinter event object.

        @return: None.
        """
        # Updates active index
        self.indexcur_set_by_event(event, notify=True)

    def _listbox_widget_update(
        self,
        keep_active,
    ):
        """
        Update listbox widget's items and selection.

        @param keep_active: Whether keep or clear active index.

        @return: None.
        """
        # Remove old items from listbox widget
        self._listbox.delete(0, END)

        # Insert new items into listbox widget.
        # For each ListboxVidget items.
        for index, item in enumerate(self.items()):
            # Get item text
            item_text = self._item_to_text(item)

            # Insert the item text into listbox widget
            self._listbox.insert(index, item_text)

            # Set the item's normal background color
            self._listbox.itemconfig(index, background=self._normal_bg)

            # Set the item's normal foreground color
            self._listbox.itemconfig(index, foreground=self._normal_fg)

            # Set the item's selected background color
            self._listbox.itemconfig(index, selectbackground=self._selected_bg)

            # Set the item's selected foreground color
            self._listbox.itemconfig(index, selectforeground=self._selected_fg)

        # If keep active index
        if keep_active:
            # Use old active index
            indexcur = self._indexcur

        # If not keep active index
        else:
            # Set active index to -1
            indexcur = self._indexcur = -1

        # Clear old selection
        self._listbox.selection_clear(0, END)

        # Set new selection.
        # `-1` works.
        self._listbox.selection_set(indexcur)

        # Set new active index.
        # `-1` works.
        self._listbox.activate(indexcur)

        # If new active index is valid
        if indexcur != -1:
            # Set active background color
            self._listbox.itemconfig(indexcur, background=self._active_bg)

            # Set active foreground color
            self._listbox.itemconfig(indexcur, foreground=self._active_fg)

            # Make the active item visible
            self._listbox.see(indexcur)
Esempio n. 41
0
class LucteriosMainForm(Tk):

    def __init__(self):
        Tk.__init__(self)
        try:
            img = Image("photo", file=join(
                dirname(import_module('lucterios.install').__file__), "lucterios.png"))
            self.tk.call('wm', 'iconphoto', self._w, img)
        except:
            pass
        self.has_checked = False
        self.title(ugettext("Lucterios installer"))
        self.minsize(475, 260)
        self.grid_columnconfigure(0, weight=1)
        self.grid_rowconfigure(0, weight=1)
        self.running_instance = {}
        self.resizable(True, True)
        self.protocol("WM_DELETE_WINDOW", self.on_closing)

        self.ntbk = ttk.Notebook(self)
        self.ntbk.grid(row=0, column=0, columnspan=1, sticky=(N, S, E, W))

        self.create_instance_panel()
        self.create_module_panel()

        stl = ttk.Style()
        stl.theme_use("default")
        stl.configure("TProgressbar", thickness=5)
        self.progress = ttk.Progressbar(
            self, style="TProgressbar", orient='horizontal', mode='indeterminate')
        self.progress.grid(row=1, column=0, sticky=(E, W))

        self.btnframe = Frame(self, bd=1)
        self.btnframe.grid(row=2, column=0, columnspan=1)
        Button(self.btnframe, text=ugettext("Refresh"), width=20, command=self.refresh).grid(
            row=0, column=0, padx=3, pady=3, sticky=(N, S))
        self.btnupgrade = Button(
            self.btnframe, text=ugettext("Search upgrade"), width=20, command=self.upgrade)
        self.btnupgrade.config(state=DISABLED)
        self.btnupgrade.grid(row=0, column=1, padx=3, pady=3, sticky=(N, S))
        Button(self.btnframe, text=ugettext("Close"), width=20, command=self.on_closing).grid(
            row=0, column=2, padx=3, pady=3, sticky=(N, S))

    def on_closing(self):
        all_stop = True
        instance_names = list(self.running_instance.keys())
        for old_item in instance_names:
            if (self.running_instance[old_item] is not None) and self.running_instance[old_item].is_running():
                all_stop = False
        if all_stop or askokcancel(None, ugettext("An instance is always running.\nDo you want to close?")):
            self.destroy()
        else:
            self.refresh()

    def destroy(self):
        instance_names = list(self.running_instance.keys())
        for old_item in instance_names:
            if self.running_instance[old_item] is not None:
                self.running_instance[old_item].stop()
                del self.running_instance[old_item]
        Tk.destroy(self)

    def create_instance_panel(self):
        frm_inst = Frame(self.ntbk)
        frm_inst.grid_columnconfigure(0, weight=1)
        frm_inst.grid_rowconfigure(0, weight=1)
        frm_inst.grid_columnconfigure(1, weight=3)
        frm_inst.grid_rowconfigure(1, weight=0)
        self.instance_list = Listbox(frm_inst, width=20)
        self.instance_list.bind('<<ListboxSelect>>', self.select_instance)
        self.instance_list.pack()
        self.instance_list.grid(row=0, column=0, sticky=(N, S, W, E))

        self.instance_txt = Text(frm_inst, width=75)
        self.instance_txt.grid(row=0, column=1, rowspan=2, sticky=(N, S, W, E))
        self.instance_txt.config(state=DISABLED)

        self.btninstframe = Frame(frm_inst, bd=1)
        self.btninstframe.grid(row=1, column=0, columnspan=1)
        self.btninstframe.grid_columnconfigure(0, weight=1)
        Button(self.btninstframe, text=ugettext("Launch"), width=25, command=self.open_inst).grid(
            row=0, column=0, columnspan=2, sticky=(N, S))
        Button(self.btninstframe, text=ugettext("Modify"), width=10,
               command=self.modify_inst).grid(row=1, column=0, sticky=(N, S))
        Button(self.btninstframe, text=ugettext("Delete"), width=10,
               command=self.delete_inst).grid(row=1, column=1, sticky=(N, S))
        Button(self.btninstframe, text=ugettext("Save"), width=10,
               command=self.save_inst).grid(row=2, column=0, sticky=(N, S))
        Button(self.btninstframe, text=ugettext("Restore"), width=10,
               command=self.restore_inst).grid(row=2, column=1, sticky=(N, S))
        Button(self.btninstframe, text=ugettext("Add"), width=25, command=self.add_inst).grid(
            row=3, column=0, columnspan=2, sticky=(N, S))

        self.ntbk.add(frm_inst, text=ugettext('Instances'))

    def create_module_panel(self):
        frm_mod = Frame(self.ntbk)
        frm_mod.grid_columnconfigure(0, weight=1)
        frm_mod.grid_rowconfigure(0, weight=1)
        self.module_txt = Text(frm_mod)
        self.module_txt.grid(row=0, column=0, sticky=(N, S, W, E))
        self.module_txt.config(state=DISABLED)
        self.ntbk.add(frm_mod, text=ugettext('Modules'))

    def do_progress(self, progressing):
        if not progressing:
            self.progress.stop()
            self.progress.grid_remove()
        else:
            self.progress.start(25)
            self.progress.grid(row=1, column=0, sticky=(E, W))

    def enabled(self, is_enabled, widget=None):
        if widget is None:
            widget = self
            self.do_progress(not is_enabled)
        if is_enabled:
            widget.config(cursor="")
        else:

            widget.config(cursor="watch")
        if isinstance(widget, Button) and (widget != self.btnupgrade):
            if is_enabled and (not hasattr(widget, 'disabled') or not widget.disabled):
                widget.config(state=NORMAL)
            else:
                widget.config(state=DISABLED)
        else:
            for child_cmp in widget.winfo_children():
                self.enabled(is_enabled, child_cmp)

    @ThreadRun
    def refresh(self, instance_name=None):
        if instance_name is None:
            instance_name = self.get_selected_instance_name()
        self.instance_txt.delete("1.0", END)
        self._refresh_instance_list()
        self.set_select_instance_name(instance_name)
        if not self.has_checked:
            self._refresh_modules()
            if self.instance_list.size() == 0:
                sleep(.3)
                self._refresh_modules()
                sleep(.3)
                self.after_idle(self.add_inst)

    def _refresh_modules(self):
        self.btnupgrade.config(state=DISABLED)
        self.module_txt.config(state=NORMAL)
        self.module_txt.delete("1.0", END)
        lct_glob = LucteriosGlobal()
        mod_lucterios, mod_applis, mod_modules = lct_glob.installed()
        self.module_txt.insert(
            END, ugettext("Lucterios core\t\t%s\n") % mod_lucterios[1])
        self.module_txt.insert(END, '\n')
        self.module_txt.insert(END, ugettext("Application\n"))
        for appli_item in mod_applis:
            self.module_txt.insert(
                END, "\t%s\t%s\n" % (appli_item[0].ljust(30), appli_item[1]))
        self.module_txt.insert(END, ugettext("Modules\n"))
        for module_item in mod_modules:
            self.module_txt.insert(
                END, "\t%s\t%s\n" % (module_item[0].ljust(30), module_item[1]))
        extra_urls = lct_glob.get_extra_urls()
        if len(extra_urls) > 0:
            self.module_txt.insert(END, "\n")
            self.module_txt.insert(END, ugettext("Pypi servers\n"))
            for extra_url in extra_urls:
                self.module_txt.insert(END, "\t%s\n" % extra_url)
        self.module_txt.config(state=DISABLED)
        self.has_checked = True

        self.after(1000, lambda: Thread(target=self.check).start())

    def _refresh_instance_list(self):
        self.instance_list.delete(0, END)
        luct_glo = LucteriosGlobal()
        instance_list = luct_glo.listing()
        for item in instance_list:
            self.instance_list.insert(END, item)
            if item not in self.running_instance.keys():
                self.running_instance[item] = None

        instance_names = list(self.running_instance.keys())
        for old_item in instance_names:
            if old_item not in instance_list:
                if self.running_instance[old_item] is not None:
                    self.running_instance[old_item].stop()
                del self.running_instance[old_item]

    def set_select_instance_name(self, instance_name):
        cur_sel = 0
        for sel_iter in range(self.instance_list.size()):
            if self.instance_list.get(sel_iter) == instance_name:
                cur_sel = sel_iter
                break
        self.instance_list.selection_set(cur_sel)
        self.select_instance(None)

    def get_selected_instance_name(self):
        if len(self.instance_list.curselection()) > 0:
            return self.instance_list.get(int(self.instance_list.curselection()[0]))
        else:
            return ""

    def set_ugrade_state(self, must_upgrade):
        if must_upgrade:
            self.btnupgrade.config(state=NORMAL)
            self.btnupgrade["text"] = ugettext("Upgrade needs")
        else:
            self.btnupgrade["text"] = ugettext("No upgrade")
            self.btnupgrade.config(state=DISABLED)

    def check(self):
        must_upgrade = False
        try:
            lct_glob = LucteriosGlobal()
            _, must_upgrade = lct_glob.check()
        finally:
            self.after(300, self.set_ugrade_state, must_upgrade)

    @ThreadRun
    def upgrade(self):
        self.btnupgrade.config(state=DISABLED)
        self.instance_list.config(state=DISABLED)
        try:
            from logging import getLogger
            admin_path = import_module(
                "lucterios.install.lucterios_admin").__file__
            proc = Popen(
                [sys.executable, admin_path, "update"], stderr=STDOUT, stdout=PIPE)
            value = proc.communicate()[0]
            try:
                value = value.decode('ascii')
            except:
                pass
            six.print_(value)
            if proc.returncode != 0:
                getLogger("lucterios.admin").error(value)
            else:
                getLogger("lucterios.admin").info(value)
            showinfo(ugettext("Lucterios installer"), ugettext(
                "The application must restart"))
            python = sys.executable
            os.execl(python, python, *sys.argv)
        finally:
            self._refresh_modules()
            self.btnupgrade.config(state=NORMAL)
            self.instance_list.config(state=NORMAL)

    @ThreadRun
    def select_instance(self, evt):

        if self.instance_list['state'] == NORMAL:
            self.instance_list.config(state=DISABLED)
            try:
                instance_name = self.get_selected_instance_name()
                self.instance_txt.configure(state=NORMAL)
                self.instance_txt.delete("1.0", END)
                if instance_name != '':
                    if instance_name not in self.running_instance.keys():
                        self.running_instance[instance_name] = None
                    inst = LucteriosInstance(instance_name)
                    inst.read()
                    self.instance_txt.insert(END, "\t\t\t%s\n\n" % inst.name)
                    self.instance_txt.insert(
                        END, ugettext("Database\t\t%s\n") % inst.get_database_txt())
                    self.instance_txt.insert(
                        END, ugettext("Appli\t\t%s\n") % inst.get_appli_txt())
                    self.instance_txt.insert(
                        END, ugettext("Modules\t\t%s\n") % inst.get_module_txt())
                    self.instance_txt.insert(
                        END, ugettext("Extra\t\t%s\n") % inst.get_extra_txt())
                    self.instance_txt.insert(END, '\n')
                    if self.running_instance[instance_name] is not None and self.running_instance[instance_name].is_running():
                        self.instance_txt.insert(END, ugettext(
                            "=> Running in http://%(ip)s:%(port)d\n") % {'ip': self.running_instance[instance_name].lan_ip, 'port': self.running_instance[instance_name].port})
                        self.btninstframe.winfo_children()[0]["text"] = ugettext(
                            "Stop")
                    else:
                        self.running_instance[instance_name] = None
                        self.instance_txt.insert(END, ugettext("=> Stopped\n"))
                        self.btninstframe.winfo_children()[0]["text"] = ugettext(
                            "Launch")
                else:
                    self.btninstframe.winfo_children()[0]["text"] = ugettext(
                        "Launch")
                self.btninstframe.winfo_children()[0].disabled = (
                    instance_name == '')
                self.btninstframe.winfo_children()[1].disabled = (
                    instance_name == '')
                self.btninstframe.winfo_children()[2].disabled = (
                    instance_name == '')
                self.btninstframe.winfo_children()[3].disabled = (
                    instance_name == '')
                self.btninstframe.winfo_children()[4].disabled = (
                    instance_name == '')
                self.instance_txt.configure(state=DISABLED)
            finally:
                setup_from_none()
                self.instance_list.config(state=NORMAL)

    @ThreadRun
    def add_modif_inst_result(self, result, to_create):
        inst = LucteriosInstance(result[0])
        inst.set_extra("LANGUAGE_CODE='%s'" % result[5])
        inst.set_appli(result[1])
        inst.set_module(result[2])
        inst.set_database(result[4])
        if to_create:
            inst.add()
        else:
            inst.modif()
        inst = LucteriosInstance(result[0])
        inst.set_extra(result[3])
        inst.security()
        self.refresh(result[0])

    def add_inst(self):
        self.enabled(False)
        try:
            self.do_progress(False)
            ist_edt = InstanceEditor()
            ist_edt.execute()
            ist_edt.transient(self)
            self.wait_window(ist_edt)
        finally:
            self.enabled(True)
        if ist_edt.result is not None:
            self.add_modif_inst_result(ist_edt.result, True)

    def modify_inst(self):
        self.enabled(False)
        try:
            self.do_progress(False)
            ist_edt = InstanceEditor()
            ist_edt.execute(self.get_selected_instance_name())
            ist_edt.transient(self)
            self.wait_window(ist_edt)
        finally:
            self.enabled(True)
        if ist_edt.result is not None:
            self.add_modif_inst_result(ist_edt.result, False)

    @ThreadRun
    def delete_inst_name(self, instance_name):
        inst = LucteriosInstance(instance_name)
        inst.delete()
        self.refresh()

    def delete_inst(self):
        setup_from_none()
        instance_name = self.get_selected_instance_name()
        if askokcancel(None, ugettext("Do you want to delete '%s'?") % instance_name):
            self.delete_inst_name(instance_name)
        else:
            self.refresh()

    @ThreadRun
    def open_inst(self):
        instance_name = self.get_selected_instance_name()
        if instance_name != '':
            try:
                if instance_name not in self.running_instance.keys():
                    self.running_instance[instance_name] = None
                if self.running_instance[instance_name] is None:
                    port = FIRST_HTTP_PORT
                    for inst_obj in self.running_instance.values():
                        if (inst_obj is not None) and (inst_obj.port >= port):
                            port = inst_obj.port + 1
                    self.running_instance[instance_name] = RunServer(
                        instance_name, port)
                    self.running_instance[instance_name].start()
                else:
                    self.running_instance[instance_name].stop()
                    self.running_instance[instance_name] = None
            finally:
                self.set_select_instance_name(instance_name)

    @ThreadRun
    def save_instance(self, instance_name, file_name):
        inst = LucteriosInstance(instance_name)
        inst.filename = file_name
        if inst.archive():
            showinfo(ugettext("Lucterios installer"), ugettext(
                "Instance saved to %s") % file_name)
        else:
            showerror(
                ugettext("Lucterios installer"), ugettext("Instance not saved!"))
        self.refresh(instance_name)

    def save_inst(self):
        instance_name = self.get_selected_instance_name()
        if instance_name != '':
            file_name = asksaveasfilename(
                parent=self, filetypes=[('lbk', '.lbk'), ('*', '.*')])
            if file_name != '':
                self.save_instance(instance_name, file_name)

    @ThreadRun
    def restore_instance(self, instance_name, file_name):
        if file_name[-4:] == '.bkf':
            rest_inst = MigrateFromV1(instance_name, withlog=True)
        else:
            rest_inst = LucteriosInstance(instance_name)
        rest_inst.filename = file_name
        if rest_inst.restore():
            showinfo(ugettext("Lucterios installer"), ugettext(
                "Instance restore from %s") % file_name)
        else:
            showerror(
                ugettext("Lucterios installer"), ugettext("Instance not restored!"))
        self.refresh(instance_name)

    def restore_inst(self):
        instance_name = self.get_selected_instance_name()
        if instance_name != '':
            file_name = askopenfilename(
                parent=self, filetypes=[('lbk', '.lbk'), ('bkf', '.bkf'), ('*', '.*')])
            if file_name != '':
                self.restore_instance(instance_name, file_name)

    def execute(self):
        self.refresh()
        center(self, (700, 300))
        self.mainloop()
class DrtGlueDemo(object):
    def __init__(self, examples):
        # Set up the main window.
        self._top = Tk()
        self._top.title("DRT Glue Demo")

        # Set up key bindings.
        self._init_bindings()

        # Initialize the fonts.self._error = None
        self._init_fonts(self._top)

        self._examples = examples
        self._readingCache = [None for example in examples]

        # The user can hide the grammar.
        self._show_grammar = IntVar(self._top)
        self._show_grammar.set(1)

        # Set the data to None
        self._curExample = -1
        self._readings = []
        self._drs = None
        self._drsWidget = None
        self._error = None

        self._init_glue()

        # Create the basic frames.
        self._init_menubar(self._top)
        self._init_buttons(self._top)
        self._init_exampleListbox(self._top)
        self._init_readingListbox(self._top)
        self._init_canvas(self._top)

        # Resize callback
        self._canvas.bind("<Configure>", self._configure)

    #########################################
    ##  Initialization Helpers
    #########################################

    def _init_glue(self):
        tagger = RegexpTagger(
            [
                ("^(David|Mary|John)$", "NNP"),
                ("^(walks|sees|eats|chases|believes|gives|sleeps|chases|persuades|tries|seems|leaves)$", "VB"),
                ("^(go|order|vanish|find|approach)$", "VB"),
                ("^(a)$", "ex_quant"),
                ("^(every)$", "univ_quant"),
                ("^(sandwich|man|dog|pizza|unicorn|cat|senator)$", "NN"),
                ("^(big|gray|former)$", "JJ"),
                ("^(him|himself)$", "PRP"),
            ]
        )

        depparser = MaltParser(tagger=tagger)
        self._glue = DrtGlue(depparser=depparser, remove_duplicates=False)

    def _init_fonts(self, root):
        # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html>
        self._sysfont = Font(font=Button()["font"])
        root.option_add("*Font", self._sysfont)

        # TWhat's our font size (default=same as sysfont)
        self._size = IntVar(root)
        self._size.set(self._sysfont.cget("size"))

        self._boldfont = Font(family="helvetica", weight="bold", size=self._size.get())
        self._font = Font(family="helvetica", size=self._size.get())
        if self._size.get() < 0:
            big = self._size.get() - 2
        else:
            big = self._size.get() + 2
        self._bigfont = Font(family="helvetica", weight="bold", size=big)

    def _init_exampleListbox(self, parent):
        self._exampleFrame = listframe = Frame(parent)
        self._exampleFrame.pack(fill="both", side="left", padx=2)
        self._exampleList_label = Label(self._exampleFrame, font=self._boldfont, text="Examples")
        self._exampleList_label.pack()
        self._exampleList = Listbox(
            self._exampleFrame,
            selectmode="single",
            relief="groove",
            background="white",
            foreground="#909090",
            font=self._font,
            selectforeground="#004040",
            selectbackground="#c0f0c0",
        )

        self._exampleList.pack(side="right", fill="both", expand=1)

        for example in self._examples:
            self._exampleList.insert("end", ("  %s" % example))
        self._exampleList.config(height=min(len(self._examples), 25), width=40)

        # Add a scrollbar if there are more than 25 examples.
        if len(self._examples) > 25:
            listscroll = Scrollbar(self._exampleFrame, orient="vertical")
            self._exampleList.config(yscrollcommand=listscroll.set)
            listscroll.config(command=self._exampleList.yview)
            listscroll.pack(side="left", fill="y")

        # If they select a example, apply it.
        self._exampleList.bind("<<ListboxSelect>>", self._exampleList_select)

    def _init_readingListbox(self, parent):
        self._readingFrame = listframe = Frame(parent)
        self._readingFrame.pack(fill="both", side="left", padx=2)
        self._readingList_label = Label(self._readingFrame, font=self._boldfont, text="Readings")
        self._readingList_label.pack()
        self._readingList = Listbox(
            self._readingFrame,
            selectmode="single",
            relief="groove",
            background="white",
            foreground="#909090",
            font=self._font,
            selectforeground="#004040",
            selectbackground="#c0f0c0",
        )

        self._readingList.pack(side="right", fill="both", expand=1)

        # Add a scrollbar if there are more than 25 examples.
        listscroll = Scrollbar(self._readingFrame, orient="vertical")
        self._readingList.config(yscrollcommand=listscroll.set)
        listscroll.config(command=self._readingList.yview)
        listscroll.pack(side="right", fill="y")

        self._populate_readingListbox()

    def _populate_readingListbox(self):
        # Populate the listbox with integers
        self._readingList.delete(0, "end")
        for i in range(len(self._readings)):
            self._readingList.insert("end", ("  %s" % (i + 1)))
        self._readingList.config(height=min(len(self._readings), 25), width=5)

        # If they select a example, apply it.
        self._readingList.bind("<<ListboxSelect>>", self._readingList_select)

    def _init_bindings(self):
        # Key bindings are a good thing.
        self._top.bind("<Control-q>", self.destroy)
        self._top.bind("<Control-x>", self.destroy)
        self._top.bind("<Escape>", self.destroy)
        self._top.bind("n", self.next)
        self._top.bind("<space>", self.next)
        self._top.bind("p", self.prev)
        self._top.bind("<BackSpace>", self.prev)

    def _init_buttons(self, parent):
        # Set up the frames.
        self._buttonframe = buttonframe = Frame(parent)
        buttonframe.pack(fill="none", side="bottom", padx=3, pady=2)
        Button(buttonframe, text="Prev", background="#90c0d0", foreground="black", command=self.prev).pack(side="left")
        Button(buttonframe, text="Next", background="#90c0d0", foreground="black", command=self.next).pack(side="left")

    def _configure(self, event):
        self._autostep = 0
        (x1, y1, x2, y2) = self._cframe.scrollregion()
        y2 = event.height - 6
        self._canvas["scrollregion"] = "%d %d %d %d" % (x1, y1, x2, y2)
        self._redraw()

    def _init_canvas(self, parent):
        self._cframe = CanvasFrame(
            parent,
            background="white",
            # width=525, height=250,
            closeenough=10,
            border=2,
            relief="sunken",
        )
        self._cframe.pack(expand=1, fill="both", side="top", pady=2)
        canvas = self._canvas = self._cframe.canvas()

        # Initially, there's no tree or text
        self._tree = None
        self._textwidgets = []
        self._textline = None

    def _init_menubar(self, parent):
        menubar = Menu(parent)

        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label="Exit", underline=1, command=self.destroy, accelerator="q")
        menubar.add_cascade(label="File", underline=0, menu=filemenu)

        actionmenu = Menu(menubar, tearoff=0)
        actionmenu.add_command(label="Next", underline=0, command=self.next, accelerator="n, Space")
        actionmenu.add_command(label="Previous", underline=0, command=self.prev, accelerator="p, Backspace")
        menubar.add_cascade(label="Action", underline=0, menu=actionmenu)

        optionmenu = Menu(menubar, tearoff=0)
        optionmenu.add_checkbutton(
            label="Remove Duplicates",
            underline=0,
            variable=self._glue.remove_duplicates,
            command=self._toggle_remove_duplicates,
            accelerator="r",
        )
        menubar.add_cascade(label="Options", underline=0, menu=optionmenu)

        viewmenu = Menu(menubar, tearoff=0)
        viewmenu.add_radiobutton(label="Tiny", variable=self._size, underline=0, value=10, command=self.resize)
        viewmenu.add_radiobutton(label="Small", variable=self._size, underline=0, value=12, command=self.resize)
        viewmenu.add_radiobutton(label="Medium", variable=self._size, underline=0, value=14, command=self.resize)
        viewmenu.add_radiobutton(label="Large", variable=self._size, underline=0, value=18, command=self.resize)
        viewmenu.add_radiobutton(label="Huge", variable=self._size, underline=0, value=24, command=self.resize)
        menubar.add_cascade(label="View", underline=0, menu=viewmenu)

        helpmenu = Menu(menubar, tearoff=0)
        helpmenu.add_command(label="About", underline=0, command=self.about)
        menubar.add_cascade(label="Help", underline=0, menu=helpmenu)

        parent.config(menu=menubar)

    #########################################
    ##  Main draw procedure
    #########################################

    def _redraw(self):
        canvas = self._canvas

        # Delete the old DRS, widgets, etc.
        if self._drsWidget is not None:
            self._drsWidget.clear()

        if self._drs:
            self._drsWidget = DrsWidget(self._canvas, self._drs)
            self._drsWidget.draw()

        if self._error:
            self._drsWidget = DrsWidget(self._canvas, self._error)
            self._drsWidget.draw()

    #########################################
    ##  Button Callbacks
    #########################################

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

    def prev(self, *e):
        selection = self._readingList.curselection()
        readingListSize = self._readingList.size()

        # there are readings
        if readingListSize > 0:
            # if one reading is currently selected
            if len(selection) == 1:
                index = int(selection[0])

                # if it's on (or before) the first item
                if index <= 0:
                    self._select_previous_example()
                else:
                    self._readingList_store_selection(index - 1)

            else:
                # select its first reading
                self._readingList_store_selection(readingListSize - 1)

        else:
            self._select_previous_example()

    def _select_previous_example(self):
        # if the current example is not the first example
        if self._curExample > 0:
            self._exampleList_store_selection(self._curExample - 1)
        else:
            # go to the last example
            self._exampleList_store_selection(len(self._examples) - 1)

    def next(self, *e):
        selection = self._readingList.curselection()
        readingListSize = self._readingList.size()

        # if there are readings
        if readingListSize > 0:
            # if one reading is currently selected
            if len(selection) == 1:
                index = int(selection[0])

                # if it's on (or past) the last item
                if index >= (readingListSize - 1):
                    self._select_next_example()
                else:
                    self._readingList_store_selection(index + 1)

            else:
                # select its first reading
                self._readingList_store_selection(0)

        else:
            self._select_next_example()

    def _select_next_example(self):
        # if the current example is not the last example
        if self._curExample < len(self._examples) - 1:
            self._exampleList_store_selection(self._curExample + 1)
        else:
            # go to the first example
            self._exampleList_store_selection(0)

    def about(self, *e):
        ABOUT = "NLTK Discourse Representation Theory (DRT) Glue Semantics Demo\n" + "Written by Daniel H. Garrette"
        TITLE = "About: NLTK DRT Glue Demo"
        try:
            from tkMessageBox import Message

            Message(message=ABOUT, title=TITLE).show()
        except:
            ShowText(self._top, TITLE, ABOUT)

    def postscript(self, *e):
        self._autostep = 0
        self._cframe.print_to_file()

    def mainloop(self, *args, **kwargs):
        """
        Enter the Tkinter mainloop.  This function must be called if
        this demo is created from a non-interactive program (e.g.
        from a secript); otherwise, the demo will close as soon as
        the script completes.
        """
        if in_idle():
            return
        self._top.mainloop(*args, **kwargs)

    def resize(self, size=None):
        if size is not None:
            self._size.set(size)
        size = self._size.get()
        self._font.configure(size=-(abs(size)))
        self._boldfont.configure(size=-(abs(size)))
        self._sysfont.configure(size=-(abs(size)))
        self._bigfont.configure(size=-(abs(size + 2)))
        self._redraw()

    def _toggle_remove_duplicates(self):
        self._glue.remove_duplicates = not self._glue.remove_duplicates

        self._exampleList.selection_clear(0, "end")
        self._readings = []
        self._populate_readingListbox()
        self._readingCache = [None for ex in self._examples]
        self._curExample = -1
        self._error = None

        self._drs = None
        self._redraw()

    def _exampleList_select(self, event):
        selection = self._exampleList.curselection()
        if len(selection) != 1:
            return
        self._exampleList_store_selection(int(selection[0]))

    def _exampleList_store_selection(self, index):
        self._curExample = index
        example = self._examples[index]

        self._exampleList.selection_clear(0, "end")
        if example:
            cache = self._readingCache[index]
            if cache:
                if isinstance(cache, list):
                    self._readings = cache
                    self._error = None
                else:
                    self._readings = []
                    self._error = cache
            else:
                try:
                    self._readings = self._glue.parse_to_meaning(example)
                    self._error = None
                    self._readingCache[index] = self._readings
                except Exception as e:
                    self._readings = []
                    self._error = DrtVariableExpression(Variable("Error: " + str(e)))
                    self._readingCache[index] = self._error

                    # add a star to the end of the example
                    self._exampleList.delete(index)
                    self._exampleList.insert(index, ("  %s *" % example))
                    self._exampleList.config(height=min(len(self._examples), 25), width=40)

            self._populate_readingListbox()

            self._exampleList.selection_set(index)

            self._drs = None
            self._redraw()

    def _readingList_select(self, event):
        selection = self._readingList.curselection()
        if len(selection) != 1:
            return
        self._readingList_store_selection(int(selection[0]))

    def _readingList_store_selection(self, index):
        reading = self._readings[index]

        self._readingList.selection_clear(0, "end")
        if reading:
            self._readingList.selection_set(index)

            self._drs = reading.simplify().normalize().resolve_anaphora()

            self._redraw()
Esempio n. 43
0
class LogUI(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
        self.parent = parent
        
        self.filemodels = []
        filemodel1 = FileModel("C:/Users/chen_xi/test1.csv", searchconds=[], relation="and", joincondtuples=[])
        filemodel2 = FileModel("C:/Users/chen_xi/test2.csv", searchconds=[], relation="and", joincondtuples=[])
        self.filemodels = [filemodel1, filemodel2]
        
        self._initUI()
        self.selectedfileindex = -1
        
        
    def _initUI(self):
        self.parent.title("Log Processor")
        self.pack()
        
        self._initfilepanel()
        self._initsearchcondpanel()
        self._initjoincondpanel()
        self._initconsole()
        
        self._inflatefilelist()
        
        
    def _initfilepanel(self):
        frame = Frame(self)
        frame.grid(row=0, column=0, sticky=E + W + S + N)
        
        label = Label(frame, text="File List: ")
        label.grid(sticky=N + W)
        
        self.filelist = Listbox(frame, width=40)
        self.filelist.grid(row=1, column=0, rowspan=2, columnspan=3)
        
        vsl = Scrollbar(frame, orient=VERTICAL)
        vsl.grid(row=1, column=3, rowspan=2, sticky=N + S + W)
        
        hsl = Scrollbar(frame, orient=HORIZONTAL)
        hsl.grid(row=3, column=0, columnspan=3, sticky=W + E + N)
        
        self.filelist.config(yscrollcommand=vsl.set, xscrollcommand=hsl.set)
        self.filelist.bind('<<ListboxSelect>>', self._onfilelistselection)
        
        hsl.config(command=self.filelist.xview)
        vsl.config(command=self.filelist.yview)
        
        upbtn = Button(frame, text="Up", width=7, command=self._upfile)
        upbtn.grid(row=1, column=4, padx=5, pady=5)
        
        downbtn = Button(frame, text="Down", width=7, command=self._downfile)
        downbtn.grid(row=2, column=4, padx=5, pady=5)
        
        newbtn = Button(frame, text="New", width=7, command=self._addfile)
        newbtn.grid(row=4, column=1, pady=5, sticky=E + S)
        
        delbtn = Button(frame, text="Delete", width=7, command=self._deletefile)
        delbtn.grid(row=4, column=2, padx=5, pady=5, sticky=W + S)
        
            
    def _inflatefilelist(self):
        self.filelist.delete(0, END)
        for filemodel in self.filemodels:
            self.filelist.insert(END, filemodel.filename)
            
        
    def _initsearchcondpanel(self):
        frame = Frame(self)
        frame.grid(row=0, column=1, sticky=E + W + S + N, padx=5)
        
        label = Label(frame, text="Search Condition: ")
        label.grid(row=0, column=0, columnspan=1, sticky=W)
        
        relationlable = Label(frame, text="Relation")
        relationlable.grid(row=0, column=1, columnspan=1, sticky=E)
        
        self.condrelationvar = StringVar(frame)
        relationinput = Combobox(frame, textvariable=self.condrelationvar, values=["and", "or"])
        relationinput.grid(row=0, column=2, padx=5, sticky=E)
        relationinput.bind('<<ComboboxSelected>>', self._onrelationchange)
        
        self.searchcondlist = Listbox(frame)
        self.searchcondlist.grid(row=1, rowspan=1, columnspan=3, sticky=E + W + S + N)
        
        vsl = Scrollbar(frame, orient=VERTICAL)
        vsl.grid(row=1, column=3, rowspan=1, sticky=N + S + W)
        
        hsl = Scrollbar(frame, orient=HORIZONTAL)
        hsl.grid(row=2, column=0, columnspan=3, sticky=W + E + N)
        
        self.searchcondlist.config(yscrollcommand=vsl.set, xscrollcommand=hsl.set)
        
        hsl.config(command=self.searchcondlist.xview)
        vsl.config(command=self.searchcondlist.yview)
        
        newbtn = Button(frame, text="New", width=7, command=self._addsearchcondition)
        newbtn.grid(row=3, column=0, padx=5, pady=5, sticky=E)
        
        delbtn = Button(frame, text="Delete", width=7, command=self._deletesearchcondition)
        delbtn.grid(row=3, column=1, sticky=E)
        
        modbtn = Button(frame, text="Update", width=7, command=self._modifysearchcondition)
        modbtn.grid(row=3, column=2, padx=5, pady=5, sticky=W)
        
    
    def _onrelationchange(self, evt):
        selectedmodel = self._getselectedfile()
        selectedmodel.relation = self.condrelationvar.get()
    
            
    def _inflatesearchcondlist(self, filemodel):
        self.condrelationvar.set(filemodel.relation)
        conds = filemodel.searchconds
        self.searchcondlist.delete(0, END)
        for cond in conds:
            self.searchcondlist.insert(END, cond.tostring())
        
        
    def _initjoincondpanel(self):
        frame = Frame(self)
        frame.grid(row=0, column=2, sticky=E + W + S + N, padx=5)
        
        label = Label(frame, text="Join Condition: ")
        label.grid(sticky=N + W)
        
        self.joincondlist = Listbox(frame)
        self.joincondlist.grid(row=1, rowspan=1, columnspan=3, sticky=E + W + S + N)
        
        vsl = Scrollbar(frame, orient=VERTICAL)
        vsl.grid(row=1, column=3, rowspan=1, sticky=N + S + W)
        
        hsl = Scrollbar(frame, orient=HORIZONTAL)
        hsl.grid(row=2, column=0, columnspan=3, sticky=W + E + N)
        
        self.joincondlist.config(yscrollcommand=vsl.set, xscrollcommand=hsl.set)
        
        hsl.config(command=self.joincondlist.xview)
        vsl.config(command=self.joincondlist.yview)
        
        newbtn = Button(frame, text="New", width=7, command=self._addjoincondition)
        newbtn.grid(row=3, column=0, padx=5, pady=5, sticky=E)
        
        delbtn = Button(frame, text="Delete", width=7, command=self._deletejoincondition)
        delbtn.grid(row=3, column=1, sticky=E)
        
        modbtn = Button(frame, text="Update", width=7, command=self._modifyjoincondition)
        modbtn.grid(row=3, column=2, padx=5, pady=5, sticky=W)
        
    
    def _inflatejoincondlist(self, condtuples):
        self.joincondlist.delete(0, END)
        for condtuple in condtuples:
            cond = condtuple[0]
            tofilename = condtuple[1]
            self.joincondlist.insert(END, cond.tostring() + " in " + tofilename)
        
    
    def _initconsole(self):
        
        separator = Separator(self, orient=HORIZONTAL)
        separator.grid(row=1, columnspan=3, sticky=W + E, padx=5, pady=5)
        
        self.console = Text(self)
        self.console.grid(row=2, columnspan=3, sticky=W + E, padx=5, pady=5)
        
        vsl = Scrollbar(self, orient=VERTICAL)
        vsl.grid(row=2, column=3, sticky=N + S + W)
        
        hsl = Scrollbar(self, orient=HORIZONTAL)
        hsl.grid(row=3, column=0, columnspan=3, sticky=W + E + N)
        
        hsl.config(command=self.console.xview)
        vsl.config(command=self.console.yview)
        
        resbtn = Button(self, text="Search", width=7, comman=self._showsearchresult)
        resbtn.grid(row=4, column=2, padx=5, pady=5, sticky=E)
        
    
    def _showsearchresult(self):
        try:
            res = self._searchresult()
            formatres = self._formatsearchresult(res)
        except Exception:
            formatres = "Error!\r\n" + traceback.format_exc()
        
        self.console.delete("0.0", END)
        self.console.insert("0.0", formatres)
    
    
    def _searchresult(self):
        filesearchs = []
        joinsearchs = []
        for filemodel in self.filemodels:
            filename = filemodel.filename
            
            singlesearch = SingleFileSearch(filename, DictReader(open(filename)), filemodel.searchconds, filemodel.relation)
            filesearchs.append(singlesearch)
            
            joindict = {}
            for joincondtuple in filemodel.joincondtuples:
                tofilename = joincondtuple[1]
                joincond = joincondtuple[0]
                if tofilename not in joindict:
                    joindict[tofilename] = []
                joindict[tofilename].append(joincond)
            
            for tofilename in joindict:
                joinsearch = JoinFileSearch(filename, DictReader(open(filename)), tofilename, DictReader(open(tofilename)), joindict[tofilename])
                joinsearchs.append(joinsearch)
                
        search = Search(filesearchs, joinsearchs)
        return search.process()
    
    
    def _formatsearchresult(self, searchresult):
        formatres = self._formatsummary(searchresult) + "\r\n"
        fileresults = searchresult.results
        for filemodel in self.filemodels:
            filename = filemodel.filename
            fileresult = fileresults[filename]
            formatres += self._formatfileresult(fileresult)
            formatres += "\r\n"
        return formatres
    
    
    def _formatsummary(self, searchresult):
        res = "Summary\r\n"
        res += "Time Cost: " + str(searchresult.timecost) + " Seconds\r\n"
        fileresults = searchresult.results
        for filemodel in self.filemodels:
            filename = filemodel.filename
            fileresult = fileresults[filename]
            res += filename + "    Size: " + str(len(fileresult.result)) + "\r\n"
        return res
        
    
    def _formatfileresult(self, fileresult):
        res = ""
        filename = fileresult.filename
        res += filename + "    Size: " + str(len(fileresult.result)) + "\r\n"
        fields = csvhandler.getfields(filename)
        
        for (i, field) in enumerate(fields):
            res += field
            if i < (len(fields) - 1):
                res += ","
            else:
                res += "\r\n"
                
        for rowdict in fileresult.result:
            for (i, field) in enumerate(fields):
                res += rowdict[field]
                if i < (len(fields) - 1):
                    res += ","
                else:
                    res += "\r\n"
        return res
                
             
        
    def _addfile(self):
        filetypes = [('csv files', '*.csv'), ('All files', '*')]
        
        selectedfile = askopenfilename(filetypes=filetypes)
        if selectedfile is not None:
            newmodel = FileModel(selectedfile, searchconds=[], relation="and", joincondtuples=[])
            self.filemodels.append(newmodel)
            self.filelist.insert(END, newmodel.filename)
            self._setselectedfileindex(len(self.filemodels) - 1)
        
        
    def _deletefile(self):
        index = self._getselectedfileindex()
        if index >= 0:
            self.filelist.delete(index)
            del self.filemodels[index]
            self._setselectedfileindex(-1)
        
        
    def _upfile(self):
        if self._getselectedfileindex() <= 0:
            return
        index = self._getselectedfileindex()
        selectedfilename = self._getselectedfile().filename
        
        if index > 0:
            self.filelist.insert((index - 1), selectedfilename)
            self.filelist.delete(index + 1)
            
            self.filemodels[index - 1], self.filemodels[index] = self.filemodels[index], self.filemodels[index - 1]
            self._setselectedfileindex(index - 1)
            
            
    def _downfile(self):
        if self._getselectedfileindex() < 0:
            return
        index = self._getselectedfileindex()
        selectedfilename = self._getselectedfile().filename
        
        if index < (len(self.filemodels) - 1):
            self.filelist.insert((index + 2), selectedfilename)
            self.filelist.delete(index)
            
            self.filemodels[index], self.filemodels[index + 1] = self.filemodels[index + 1], self.filemodels[index]
            self._setselectedfileindex(index + 1)
         
         
    def _onfilelistselection(self, evt):
        if len(self.filelist.curselection()) == 0:
            return
        
        self._setselectedfileindex(self.filelist.curselection()[0])
        selectedfile = self._getselectedfile()
        
        self._inflatesearchcondlist(selectedfile)
        
        joincondtuples = selectedfile.joincondtuples
        self._inflatejoincondlist(joincondtuples)
        
    def _addsearchcondition(self):
        if self._getselectedfileindex() < 0:
            return
        
        self._popupsearchcondwindow()
        
    
    def _deletesearchcondition(self):
        index = self._getselectedsearchcondindex()
        if index < 0:
            return
        
        selectedfile = self._getselectedfile()
        del selectedfile.searchconds[index]
        self.searchcondlist.delete(index)
    
    
    def _modifysearchcondition(self):
        if self._getselectedsearchcondindex() < 0:
            return
        
        self._popupsearchcondwindow(self._getselectedsearchcondindex())
        
    
    def _addjoincondition(self):
        if self._getselectedfileindex() < 0:
            return
        
        self._popupjoincondwindow()
        
    
    def _deletejoincondition(self):
        index = self._getselectedjoincondindex()
        if index < 0:
            return
        
        selectedfile = self._getselectedfile()
        del selectedfile.joincondtuples[index]
        self.joincondlist.delete(index)
    
    
    def _modifyjoincondition(self):
        if self._getselectedjoincondindex() < 0:
            return
        
        self._popupjoincondwindow(self._getselectedjoincondindex())
         
         
    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)
        
        
    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)
        
        
    def _getselectedfile(self):
        if self._getselectedfileindex() < 0:
            return None
        return self.filemodels[self._getselectedfileindex()]
    
    
    def _getselectedfileindex(self):
        return self.selectedfileindex
    
    
    def _setselectedfileindex(self, index):
        self.selectedfileindex = index
        if index >= 0:
            self.filelist.selection_set(index)
            
    def _getselectedsearchcondindex(self):
        if len(self.searchcondlist.curselection()) > 0:
            return self.searchcondlist.curselection()[0]
        return -1
    
    def _getselectedjoincondindex(self):
        if len(self.joincondlist.curselection()) > 0:
            return self.joincondlist.curselection()[0]
        return -1