Exemplo n.º 1
2
def draw_automata(turing_machine=None):

    w = len(turing_machine.states)
    h = len(turing_machine.rules)

    root = Tk()
    frame = Frame(root, width=800, height=600)
    frame.grid(row=0, column=0)
    canvas = Canvas(frame, bg='#FFFFFF', width=800, height=600,
                    scrollregion=(0, -h * 15, w * 100, h * 15*3))
    hbar = Scrollbar(frame, orient=HORIZONTAL)
    hbar.pack(side=BOTTOM, fill=X)
    hbar.config(command=canvas.xview)
    vbar = Scrollbar(frame, orient=VERTICAL)
    vbar.pack(side=RIGHT, fill=Y)
    vbar.config(command=canvas.yview)
    canvas.config(width=800, height=600)
    canvas.config(xscrollcommand=hbar.set, yscrollcommand=vbar.set)
    canvas.pack(side=LEFT, expand=True, fill=BOTH)

    for position, state in enumerate(turing_machine.states):
        state_position[state] = position
        loop_occurrences[position] = 0
        canvas_id = canvas.create_text(10 + 80 * position, 400, anchor="nw")
        canvas.itemconfig(canvas_id, text="state-")
        canvas.insert(canvas_id, 12, "%d" % state)

    counter = 1
    for rule in turing_machine.rules:
        counter = draw_arrow(state_position[rule.current_state],
                             state_position[rule.next_state],
                             canvas, counter, rule)

    root.mainloop()
    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)
Exemplo n.º 3
0
 def _init_results_box(self, parent):
     innerframe = Frame(parent)
     i1 = Frame(innerframe)
     i2 = Frame(innerframe)
     vscrollbar = Scrollbar(i1, borderwidth=1)
     hscrollbar = Scrollbar(i2, borderwidth=1, orient="horiz")
     self.results_box = Text(
         i1,
         font=tkinter.font.Font(family="courier", size="16"),
         state="disabled",
         borderwidth=1,
         yscrollcommand=vscrollbar.set,
         xscrollcommand=hscrollbar.set,
         wrap="none",
         width="40",
         height="20",
         exportselection=1,
     )
     self.results_box.pack(side="left", fill="both", expand=True)
     self.results_box.tag_config(self._HIGHLIGHT_WORD_TAG, foreground=self._HIGHLIGHT_WORD_COLOUR)
     self.results_box.tag_config(self._HIGHLIGHT_LABEL_TAG, foreground=self._HIGHLIGHT_LABEL_COLOUR)
     vscrollbar.pack(side="left", fill="y", anchor="e")
     vscrollbar.config(command=self.results_box.yview)
     hscrollbar.pack(side="left", fill="x", expand=True, anchor="w")
     hscrollbar.config(command=self.results_box.xview)
     # there is no other way of avoiding the overlap of scrollbars while using pack layout manager!!!
     Label(i2, text="   ", background=self._BACKGROUND_COLOUR).pack(side="left", anchor="e")
     i1.pack(side="top", fill="both", expand=True, anchor="n")
     i2.pack(side="bottom", fill="x", anchor="s")
     innerframe.pack(side="top", fill="both", expand=True)
Exemplo n.º 4
0
 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 _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()
Exemplo n.º 6
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)
Exemplo n.º 7
0
    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)
Exemplo n.º 8
0
    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)
Exemplo n.º 9
0
 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)
Exemplo n.º 10
0
    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)
Exemplo n.º 11
0
    def __init__(self,master,cmap=None):
        Toplevel.__init__(self,master)
        # update title
        self.title("Choose a colormap")
        # create frame
        frm = Frame(self)
        # create listbox
        self.clist = Listbox(frm)
        # bind double click
        self.clist.bind('<Button-1>',self.cmapSelect)
        # get all colormaps
        for ci,(kk,_) in enumerate(filter(lambda x : isinstance(x[1],Colormap),vars(matplotlib.cm).items())):
            self.clist.insert(ci,kk)
        # scrollbar
        scroll = Scrollbar(frm,orient='vertical')
        scroll.config(command=self.clist.yview)
        # currently selected colormap
        # if nothing is given, get matplotlib default
        if cmap == None:
            self.curr_cmap = getattr(matplotlib.cm,matplotlib.rcParams['image.cmap'])
        else:
            # if user specifies a string
            if type(cmap) == str:
                # attempt to get index of colormap from list
                # if it fails, reverts to default
                try:
                    idx = self.self.clist.get(0,END).index(cmap)
                    self.self.clist.select(idx)
                    self.curr_cmap = getattr(matplotlib.cm,self.self.clist.get(0,END)[idx])
                except ValueError:
                    self.curr_cmap = getattr(matplotlib.cm,matplotlib.rcParams['image.cmap'])
            # if the user passs a Colormap directly, store that
            elif isinstance(cmap,Colormap):
                self.curr_cmap = cmap
            # if it's something else
            # print error message and set current colormap to None
            else:
                print(f"Unsupported colormap value {cmap}!",file=sys.stderr)
                self.curr_cmap = None
        # add buttons
        btt_frm = Frame(self)
        select_btt = Button(btt_frm,text="Select",command=self.enter_handler)
        cancel_btt = Button(btt_frm,text="Cancel",command=self.cancel_handler)

        # keyboard handlers for if the button is currently selected
        select_btt.bind('<KeyPress-Return>', func=self.enter_handler)
        cancel_btt.bind('<KeyPress-Return>', func=self.cancel_handler)
        ## pack
        self.clist.grid(row=0,column=0,sticky='nswe')
        scroll.grid(row=0,column=1,sticky='ns')
        
        frm.grid(row=0,column=0,sticky='nswe')
        
        select_btt.grid(row=0,column=0,sticky='ew')
        cancel_btt.grid(row=0,column=1,sticky='ew')
        
        btt_frm.grid(row=1,column=0,columnspan=2,sticky='ew')
Exemplo n.º 12
0
  def __init__(self, *, multiple_runner_class, input_spec, left_name,
               right_name):
    """Sets up windows and the instance of RunMultipleTimes that will do the actual work."""
    #: The input_spec is an iterable of
    #: :py:class:`farg.core.read_input_spec.SpecificationForOneRun`.
    self.input_spec = input_spec
    #: Class responsible for the actual running multiple times.
    self.multiple_runner_class = multiple_runner_class
    #: Main window
    self.mw = mw = Tk()
    #: Statistics thus far, grouped by input.
    self.stats = AllStats(left_name=left_name, right_name=right_name)

    #: Are we in the process of quitting?
    self.quitting = False

    self.status_label = Label(
        mw, text='Not Started', font=('Times', 20), foreground='#000000')
    self.status_label_text = self.status_label.cget('text')
    self.status_label.pack(side=TOP, expand=True, fill=X)

    #: Has a run started? Used to ensure single run.
    self.run_started = False

    details_frame = Frame(mw)
    details_frame.pack(side=TOP)
    #: listbox on left listing inputs.
    frame = Frame(details_frame)
    scrollbar = Scrollbar(frame, orient=VERTICAL)
    listbox = Listbox(
        frame,
        yscrollcommand=scrollbar.set,
        height=25,
        width=70,
        selectmode=SINGLE)
    scrollbar.config(command=listbox.yview)
    scrollbar.pack(side=RIGHT, fill=Y)
    listbox.pack(side=LEFT, fill=BOTH, expand=1)
    listbox.bind('<ButtonRelease-1>', self.SelectForDisplay, '+')
    frame.pack(side=LEFT)
    self.listbox = listbox
    #: Canvas on right for details
    self.canvas = Canvas(
        details_frame,
        width=kCanvasWidth,
        height=kCanvasHeight,
        background='#FFFFFF')
    self.canvas.pack(side=LEFT)
    #: which input are we displaying the details of?
    self.display_details_for = None

    #: Thread used for running
    self.thread = None
    self.mw.bind('<KeyPress-q>', lambda e: self.Quit())
    self.mw.bind('<KeyPress-r>', lambda e: self.KickOffRun())
    self.Refresher()
    self.mw.after(1000, self.KickOffRun)
Exemplo n.º 13
0
 def initScrollText(self, frm, txt, contents):
     scl = Scrollbar(frm)
     scl.config(command=txt.yview)
     scl.pack(side="right", fill="y")
     txt.pack(side="left", expand=True, fill="x")
     txt.config(yscrollcommand=scl.set)
     txt.insert("1.0", contents)
     frm.pack(fill="x")
     Frame(height=2, bd=1, relief="ridge").pack(fill="x")
Exemplo n.º 14
0
    def information(self):
        ########################################################################
        #                  Information                                         #
        ########################################################################
        # Renvoie les spécialite offerte par l'école en fonction du choix de l'utilisateur

        window = Toplevel(self.root)
        window.resizable(True, True)
        vsb = Scrollbar(window, orient="vertical")
        vsb.grid(row=0, column=1, sticky="ns")
        hsb = Scrollbar(window, orient="horizontal")
        hsb.grid(row=1, column=0, sticky="ew")
        ca = Canvas(window, yscrollcommand=vsb.set, xscrollcommand=hsb.set)
        ca.grid(row=0, column=0, sticky="news")
        vsb.config(command=ca.yview)
        hsb.config(command=ca.xview)
        window.grid_rowconfigure(0, weight=1)
        window.grid_columnconfigure(0, weight=1)
        fr = Frame(ca)

        i=1
        for a in ["Nom","Admission","Region","Alternance","Specialite"]:
            Label(fr, text=a).grid(row=0, column=i)
            i+=2

        if self.choix["specialites"] == None:
            ListeSpe = list(self.specialites.get(0, "end"))
        else:
            ListeSpe = [
                self.specialites.get(i) for i in self.specialites.curselection()
            ]

        if self.choix["alternance"] == None:
            alternance = ["Oui", "Non"]

        else:
            alternance = [self.choix["alternance"][0]]

        ligne = 1
        for ecole in self.ecolesselect.values():
            if ecole["var"].get() == 1:
                for i in [value for (key,value) in self.ecolesselect.items() if value['nom']==ecole['nom'] and value["Spe"] in ListeSpe and value["Alternance"] in alternance ]:
                    j=1
                    for texte in [i["nom"],i["admission"],i["region"],i["Alternance"],i["Spe"]] :
                        a = Entry(fr,width=60)
                        a.insert(0,texte)
                        a.grid(row=ligne, column=j)
                        j+=2

                        a.config(state="disabled")
                        

                    ligne += 1

        ca.create_window(0, 0, window=fr)
        fr.update_idletasks()
        ca.config(scrollregion=ca.bbox("all"))
Exemplo n.º 15
0
    def __init__(self, parent, list_model_factory, label_text):
        Frame.__init__(self, parent)

        scrollbar = Scrollbar(self, orient=VERTICAL)
        Label(self, text=label_text).pack()
        self.check_list_box = ProgressListBox(self, scrollbar, list_model_factory)
        scrollbar.config(command=self.check_list_box.yview)
        scrollbar.pack(side=RIGHT, fill=Y)
        self.check_list_box.pack(side=LEFT, fill=BOTH, expand=1)
    def __init__(self, *, multiple_runner_class, input_spec, left_name,
                 right_name):
        """Sets up windows and the instance of RunMultipleTimes that will do the actual work."""
        #: The input_spec is an iterable of
        #: :py:class:`farg.core.read_input_spec.SpecificationForOneRun`.
        self.input_spec = input_spec
        #: Class responsible for the actual running multiple times.
        self.multiple_runner_class = multiple_runner_class
        #: Main window
        self.mw = mw = Tk()
        #: Statistics thus far, grouped by input.
        self.stats = AllStats(left_name=left_name, right_name=right_name)

        #: Are we in the process of quitting?
        self.quitting = False

        self.status_label = Label(mw,
                                  text='Not Started',
                                  font=('Times', 20),
                                  foreground='#000000')
        self.status_label_text = self.status_label.cget('text')
        self.status_label.pack(side=TOP, expand=True, fill=X)

        #: Has a run started? Used to ensure single run.
        self.run_started = False

        details_frame = Frame(mw)
        details_frame.pack(side=TOP)
        #: listbox on left listing inputs.
        frame = Frame(details_frame)
        scrollbar = Scrollbar(frame, orient=VERTICAL)
        listbox = Listbox(frame,
                          yscrollcommand=scrollbar.set,
                          height=25,
                          width=70,
                          selectmode=SINGLE)
        scrollbar.config(command=listbox.yview)
        scrollbar.pack(side=RIGHT, fill=Y)
        listbox.pack(side=LEFT, fill=BOTH, expand=1)
        listbox.bind('<ButtonRelease-1>', self.SelectForDisplay, '+')
        frame.pack(side=LEFT)
        self.listbox = listbox
        #: Canvas on right for details
        self.canvas = Canvas(details_frame,
                             width=kCanvasWidth,
                             height=kCanvasHeight,
                             background='#FFFFFF')
        self.canvas.pack(side=LEFT)
        #: which input are we displaying the details of?
        self.display_details_for = None

        #: Thread used for running
        self.thread = None
        self.mw.bind('<KeyPress-q>', lambda e: self.Quit())
        self.mw.bind('<KeyPress-r>', lambda e: self.KickOffRun())
        self.Refresher()
        self.mw.after(1000, self.KickOffRun)
Exemplo n.º 17
0
def log():
    log = Text(root, width=50, height=10)
    log.insert('end', logtxt)
    scroll = Scrollbar(root)
    scroll.config(command=log.yview)
    log.config(yscrollcommand=scroll.set, state='disabled')
    log.grid(row=9, column=1, columnspan=9)
    scroll.grid(row=9, column=10, sticky='NSE')
    log.yview_pickplace('end')
def ViewForm():

    global tree
    TopViewForm = Frame(viewform, width=600, bd=1, relief=SOLID)
    TopViewForm.pack(side=TOP, fill=X)
    LeftViewForm = Frame(viewform, width=600)
    LeftViewForm.pack(side=LEFT, fill=Y)
    MidViewForm = Frame(viewform, width=600)
    MidViewForm.pack(side=RIGHT)
    lbl_text = Label(TopViewForm,
                     text="Inventory Explorer",
                     font=('arial', 18),
                     width=600)
    lbl_text.pack(fill=X)
    lbl_txtsearch = Label(LeftViewForm, text="Search", font=('arial', 15))
    lbl_txtsearch.pack(side=TOP, anchor=CENTER)
    search = Entry(LeftViewForm,
                   textvariable=SEARCH,
                   font=('arial', 15),
                   width=10)
    search.pack(side=TOP, padx=10, fill=X)
    btn_search = Button(LeftViewForm, text="Search", command=Search)
    btn_search.pack(side=TOP, padx=10, pady=10, fill=X)
    btn_reset = Button(LeftViewForm, text="Reset Product View", command=Reset)
    btn_reset.pack(side=BOTTOM, padx=10, pady=10, fill=X)
    btn_add = Button(LeftViewForm, text="Add", command=ShowAddNew)
    btn_add.pack(side=TOP, padx=10, pady=10, fill=X)
    btn_update = Button(LeftViewForm, text="Edit", command=ShowUpdate)
    btn_update.pack(side=TOP, padx=10, pady=10, fill=X)
    btn_delete = Button(LeftViewForm, text="Delete", command=Delete)
    btn_delete.pack(side=TOP, padx=10, pady=10, fill=X)
    btn_export = Button(LeftViewForm, text="Export Data", command=Export)
    btn_export.pack(side=TOP, padx=10, pady=10, fill=X)
    scrollbarx = Scrollbar(MidViewForm, orient=HORIZONTAL)
    scrollbary = Scrollbar(MidViewForm, orient=VERTICAL)
    tree = ttk.Treeview(MidViewForm,
                        columns=("Product Name", "Product Qty",
                                 "Product Price", "ID / Barcode"),
                        selectmode="extended",
                        height=100,
                        yscrollcommand=scrollbary.set,
                        xscrollcommand=scrollbarx.set)
    scrollbary.config(command=tree.yview)
    scrollbary.pack(side=RIGHT, fill=Y)
    scrollbarx.config(command=tree.xview)
    scrollbarx.pack(side=BOTTOM, fill=X)
    tree.heading('Product Name', text="Product Name", anchor=W)
    tree.heading('Product Qty', text="Qty", anchor=W)
    tree.heading('Product Price', text="Price", anchor=W)
    tree.heading('ID / Barcode', text="ID / Barcode", anchor=W)
    tree.column('#0', stretch=True, minwidth=0, width=0)
    tree.column('#1', stretch=True, minwidth=0, width=200)
    tree.column('#2', stretch=True, minwidth=0, width=75)
    tree.column('#3', stretch=True, minwidth=0, width=75)
    tree.column('#4', stretch=True, minwidth=0, width=175)
    tree.pack()
    DisplayData()
Exemplo n.º 19
0
 def populateSelectedStreamsFrame(self):
     labelSelectedStreamsFrame = Label(self.selectedStreamsFrame, text=LabelConstants.SELECTED_STREAMS)
     labelSelectedStreamsFrame.grid(row=0, column=0, sticky=W, columnspan=2, padx=4, pady=4)
     scrollbarSelectedStreams = Scrollbar(self.selectedStreamsFrame)
     scrollbarSelectedStreams.grid(row=1, column=1, sticky="NWS")
     self.selectedStreamsListbox = Listbox(self.selectedStreamsFrame, selectmode=MULTIPLE, yscrollcommand=scrollbarSelectedStreams.set, activestyle=NONE, width=33)
     scrollbarSelectedStreams.config(command=self.selectedStreamsListbox.yview)
     self.selectedStreamsListbox.grid(row=1, column=0, sticky=NSEW, padx=(4, 0))
     self.selectedStreamsListbox.configure(exportselection=False)
Exemplo n.º 20
0
 def addInactiveListbox(self):
     labelInactiveListbox = Label(self.inactiveFrame, text=LabelConstants.INACTIVE_TAGS)
     labelInactiveListbox.grid(row=0, column=0, sticky=W, padx=4, pady=4)
     scrollbarInactive = Scrollbar(self.inactiveFrame)
     scrollbarInactive.grid(row=1, column=1, sticky="NWS")
     self.inactiveListbox = Listbox(self.inactiveFrame, selectmode=EXTENDED, yscrollcommand=scrollbarInactive.set, activestyle=NONE, width=70)
     scrollbarInactive.config(command=self.inactiveListbox.yview)
     self.inactiveListbox.bind('<<ListboxSelect>>', self.onSelectInactiveListbox)
     self.inactiveListbox.grid(row=1, column=0, sticky=NSEW, padx=(4, 0))
Exemplo n.º 21
0
class RSVisCanvasFrame(Frame):

    #   method --------------------------------------------------------------
    # -----------------------------------------------------------------------
    def __init__(
        self, 
        parent,
        images, 
        data,
        **kwargs
    ):
        super(RSVisCanvasFrame, self).__init__(parent)

        self.columnconfigure(2, weight=1)
        self.rowconfigure(0, weight=1)
        self.scrollbar = Scrollbar(self, orient="vertical", width=16)
        self.listbox = Listbox(self, yscrollcommand=self.scrollbar.set, width=37, activestyle=UNDERLINE)
        self.scrollbar.config(command=self.listbox.yview)
        self.scrollbar.grid(row=0, column=0, sticky=N+S)
        self.listbox.grid(row=0, column=1, sticky=N+S)
        for count, item in enumerate(images):
            self.listbox.insert(END, pathlib.Path(item[0].path).stem)
        self.listbox.bind("<<ListboxSelect>>", self.listbox_event)

        self._canvas = rsviscv.RSVisCanvas(self, images, data, **kwargs)
        self._canvas.set_container()
        self._canvas.grid(row=0, column=2, sticky=N+S+E+W)

        # parent.bind("<a>", self.key_a)
        # parent.bind("<d>", self.key_d)  

    #   method --------------------------------------------------------------
    # -----------------------------------------------------------------------
    def listbox_event(self,event):
        try:
            self._canvas._idx_list(index=self.listbox.curselection()[0])
            self._canvas.set_container()
        except IndexError:
            pass

    #   method --------------------------------------------------------------
    # -----------------------------------------------------------------------
    def update_listbox(self, event):
        self.listbox.activate(self._canvas.get_idx_list())

    #   method --------------------------------------------------------------
    # -----------------------------------------------------------------------
    def key_a(self, event, **kwargs):
        """Show the previous image in given image list (see listbox)."""
        self.update_listbox(event)

    #   method --------------------------------------------------------------
    # -----------------------------------------------------------------------
    def key_d(self, event, **kwargs):
        """Show the next image in given image list (see listbox)."""
        self.update_listbox(event)
Exemplo n.º 22
0
    class FieldCanvas:
        def __init__(self, master, scale):
            self.scale = scale
            self.cells = None
            self.height = None
            self.width = None
            # self.canvas = Canvas(master, bg='white', borderwidth=0, highlightthickness=0)
            self.canvas = Canvas(master, bg='white', bd=0, highlightthickness=0, width=0, height=0)
            self.h_bar = Scrollbar(master, orient=HORIZONTAL)
            self.v_bar = Scrollbar(master, orient=VERTICAL)
            self.h_bar.pack(side=BOTTOM, fill=X)
            self.h_bar.config(command=self.canvas.xview)
            self.v_bar.pack(side=RIGHT, fill=Y)
            self.v_bar.config(command=self.canvas.yview)
            self.canvas.config(xscrollcommand=self.h_bar.set, yscrollcommand=self.v_bar.set)

            self.canvas.bind("<MouseWheel>", self._scroll_vertical)
            self.canvas.bind('<Shift-MouseWheel>', self._scroll_horizontal)
            self.canvas.pack(fill="none", expand=True)

        def _scroll_vertical(self, event):
            self.canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")

        def _scroll_horizontal(self, event):
            self.canvas.xview_scroll(int(-1 * (event.delta / 120)), "units")

        def draw_grid(self, width, height):
            self.cells = []
            self.canvas.delete("all")
            self.width = width
            self.height = height
            scaled_width = width * self.scale
            scaled_height = height * self.scale
            self.canvas.config(width=scaled_width, height=scaled_height,
                               scrollregion=(0, 0, scaled_width, scaled_height))
            for j in range(height):
                self.cells.append([])
                for i in range(width):
                    x = i * self.scale
                    y = j * self.scale
                    self.cells[j].append(
                        self.canvas.create_rectangle(x, y, x + self.scale, y + self.scale, fill='white'))

        def update_field(self, field_array):
            # print(field_array)
            for j in range(self.height):
                for i in range(self.width):
                    # print(j, i)
                    value = field_array[j][i]
                    self.update_cell(i, j, value)

        def update_cell(self, i, j, value):
            if value:
                self.canvas.itemconfig(self.cells[j][i], fill='black')
            else:
                self.canvas.itemconfig(self.cells[j][i], fill='white')
Exemplo n.º 23
0
 def populateAppliedFilterFrame(self):
     labelAppliedFilters = Label(self.appliedFilterFrame, text=LabelConstants.SEARCH_TAG)
     labelAppliedFilters.grid(row=0, column=0, sticky=W, columnspan=2, padx=4, pady=4)
     scrollbarAppliedFilters = Scrollbar(self.appliedFilterFrame)
     scrollbarAppliedFilters.grid(row=1, column=1, sticky="NWS")
     self.appliedFiltersListbox = Listbox(self.appliedFilterFrame, selectmode=MULTIPLE, yscrollcommand=scrollbarAppliedFilters.set, activestyle=NONE, width=33)
     scrollbarAppliedFilters.config(command=self.appliedFiltersListbox.yview)
     self.populateTwitchTagsListbox()
     self.appliedFiltersListbox.grid(row=1, column=0, sticky=NSEW, padx=(4, 0))
     self.appliedFiltersListbox.configure(exportselection=False)
Exemplo n.º 24
0
class Chatbot:
    def __init__(self, window):
        window.title('Iris Assitant')
        window.geometry('405x400')
        window.resizable(0, 0)
        self.message_session = Text(window,
                                    bd=3,
                                    relief="flat",
                                    font=("Times", 10),
                                    undo=True,
                                    wrap="word")
        self.message_session.config(width=45,
                                    height=15,
                                    bg="#596",
                                    fg="white",
                                    state='disabled')
        self.overscroll = Scrollbar(window, command=self.message_session.yview)
        self.overscroll.config(width=20)
        self.message_session["yscrollcommand"] = self.overscroll.set
        self.message_position = 1.5
        self.send_button = Button(window,
                                  text='send',
                                  fg='white',
                                  bg='blue',
                                  width=9,
                                  font=('Times', 12),
                                  relief='flat',
                                  command=self.reply_to_you)
        self.Message_Entry = Entry(window, width=40, font=('Times', 12))
        self.Message_Entry.bind('<Return>', self.reply_to_you)
        self.message_session.place(x=20, y=20)
        self.overscroll.place(x=370, y=50)
        self.send_button.place(x=0, y=360)
        self.Message_Entry.place(x=135, y=365)
        self.Brain = json.load(open('knowledge.json'))

    def add_chat(self, message):
        self.message_position += 1.5
        print(self.message_position)
        self.Message_Entry.delete(0, 'end')
        self.message_session.config(state='normal')
        self.message_session.insert(self.message_position, message)
        self.message_session.see('end')
        self.message_session.config(state='disabled')

    def reply_to_you(self, event=None):
        message = self.Message_Entry.get().lower()
        message = 'you: ' + message + '\n'
        close_match = get_close_matches(message, self.Brain.keys())
        if close_match:
            reply = 'Iris: ' + self.Brain[close_match[0]][0] + '\n'
        else:
            reply = 'Iris: ' + 'Cant it in my knowledge base\n'
        self.add_chat(message)
        self.add_chat(reply)
  def __init__(self): 
        
      # create root window 
      root = Tk() 
 
      # create a horizontal scrollbar by 
      # setting orient to horizontal 
      h = Scrollbar(root, orient = 'horizontal') 
 
      # attach Scrollbar to root window at  
      # the bootom 
      h.pack(side = BOTTOM, fill = X) 
 
      # create a vertical scrollbar-no need 
      # to write orient as it is by 
      # default vertical 
      v = Scrollbar(root) 
 
      # attach Scrollbar to root window on  
      # the side 
      v.pack(side = RIGHT, fill = Y) 
         
 
      # create a Text widget with 15 chars 
      # width and 15 lines height 
      # here xscrollcomannd is used to attach Text 
      # widget to the horizontal scrollbar 
      # here yscrollcomannd is used to attach Text 
      # widget to the vertical scrollbar 
      t = Text(root, width = 15, height = 15, wrap = NONE, 
               xscrollcommand = h.set,  
               yscrollcommand = v.set) 
 
      # insert some text into the text widget 
      for i in range(20): 
          t.insert(END,"this is some text\n") 
 
      # attach Text widget to root window at top 
      t.pack(side=TOP, fill=X) 
 
      # here command represents the method to 
      # be executed xview is executed on 
      # object 't' Here t may represent any 
      # widget 
      h.config(command=t.xview) 
 
      # here command represents the method to 
      # be executed yview is executed on 
      # object 't' Here t may represent any 
      # widget 
      v.config(command=t.yview) 
 
      # the root window handles the mouse 
      # click event 
      root.mainloop() 
Exemplo n.º 26
0
 def createOutputFrame(self):
     frame_output = Frame(self, bd=1)
     scrollbar = Scrollbar(frame_output, orient=VERTICAL)
     self.text = Text(master=frame_output,
                      state="disable",
                      font=("宋体", 12),
                      yscrollcommand=scrollbar.set)
     scrollbar.pack(side=RIGHT, fill=Y)
     scrollbar.config(command=self.text.yview)
     self.text.pack()
     frame_output.pack(expand=True, fill="both")
Exemplo n.º 27
0
 def addTeamMemberListbox(self):
     frameTeamMemberListbox = Frame(self.streamFrame)
     frameTeamMemberListbox.grid(row=0, column=2, sticky=NSEW, pady=(0, 4))
     labelLiveListBox = Label(frameTeamMemberListbox, text=LabelConstants.TEAM_MEMBERS)
     labelLiveListBox.grid(row=0, column=0, padx=4, sticky=W)
     scrollbar = Scrollbar(frameTeamMemberListbox)
     scrollbar.grid(row=1, column=1, sticky="NWS")
     self.teamMemberListbox = Listbox(frameTeamMemberListbox, selectmode=SINGLE, yscrollcommand=scrollbar.set, activestyle=NONE)
     scrollbar.config(command=self.teamMemberListbox.yview)
     self.teamMemberListbox.bind('<<ListboxSelect>>', self.onSelectTeamMemberListbox)
     self.teamMemberListbox.grid(row=1, column=0, sticky=NSEW, padx=(4, 0))
Exemplo n.º 28
0
    def init_ui(self):
        self.parent.title("Hormiga de Lagnton")
        self.pack(fill=tk.BOTH, expand=1)

        self.canvas = Canvas(self, relief='raised', width=1000, height=1000)
        scroll = Scrollbar(self, orient=tk.VERTICAL)
        scroll.pack(side=tk.RIGHT, fill=tk.Y)
        scroll.config(command=self.canvas.yview)

        self.canvas.config(yscrollcommand=scroll.set)
        self.canvas.pack(side=tk.LEFT)

        Label(self, text="Tamaño:", font=(20, )).pack(side=tk.TOP)
        self.input_tam = Entry(self, fg="black", bg="white")
        self.input_tam.insert(10, "100")
        self.input_tam.pack(side=tk.TOP)

        Label(self, text="Porcentaje de hormigas",
              font=(20, )).pack(side=tk.TOP)
        self.barra = Scale(self,
                           from_=0,
                           to=100,
                           orient=tk.HORIZONTAL,
                           tickinterval=50)
        self.barra.set(5)
        self.barra.pack(side=tk.TOP)

        self.btn_color = Button(self,
                                text="Color de la hormiga",
                                command=self.get_color,
                                bg=self.default_color)
        self.btn_color.pack(side=tk.TOP)

        btn_iniciar = Button(self,
                             text="Iniciar/Reiniciar",
                             command=self.iniciar,
                             font=(20, ))
        btn_iniciar.pack(side=tk.TOP)

        btn_pausa = Button(self,
                           text="Reanudar/Pausa",
                           command=self.empezar_detener,
                           font=(20, ))
        btn_pausa.pack(side=tk.TOP)

        Label(self,
              text="Relación de colores y \n posicion de las hormiga:",
              font=(20, )).pack(side=tk.TOP)
        Label(self, text="Abajo", bg="blue", font=(20, )).pack(side=tk.TOP)
        Label(self, text="Arriba", bg="red", font=(20, )).pack(side=tk.TOP)
        Label(self, text="Izquierda", bg="green",
              font=(20, )).pack(side=tk.TOP)
        Label(self, text="Derecha", bg="yellow", fg="black",
              font=(20, )).pack(side=tk.TOP)
Exemplo n.º 29
0
 def addFreeAgentListbox(self):
     frameFreeAgentListBox = Frame(self.streamFrame)
     frameFreeAgentListBox.grid(row=0, column=0, sticky=NSEW, padx=4, pady=(0, 4))
     labelFreeAgentListBox = Label(frameFreeAgentListBox, text=LabelConstants.FREE_AGENTS)
     labelFreeAgentListBox.grid(row=0, column=0, padx=4, sticky=W)
     scrollbar = Scrollbar(frameFreeAgentListBox)
     scrollbar.grid(row=1, column=1, sticky="NWS")
     self.freeAgentListbox = Listbox(frameFreeAgentListBox, selectmode=MULTIPLE, yscrollcommand=scrollbar.set, activestyle=NONE)
     scrollbar.config(command=self.freeAgentListbox.yview)
     self.freeAgentListbox.bind('<<ListboxSelect>>', self.onSelectFreeAgentListbox)
     self.freeAgentListbox.grid(row=1, column=0, sticky=NSEW, padx=(4, 0))
Exemplo n.º 30
0
    def init_gui(self):
        self.top_level.geometry("600x750")

        self.name_entry = Entry(self.top_level)
        self.name_entry.grid(row=0, column=0, columnspan=2, sticky=W + E)
        self.name_entry.insert(0, 'Product name')
        self.name_entry.bind("<FocusIn>",
                             lambda args: self.name_entry.delete('0', 'end'))

        # shop_choices = ['Emag', 'Altex', 'Media Galaxy']
        shop_choices = ['Emag']
        self.shops_combo = Combobox(self.top_level, values=shop_choices)
        self.shops_combo.grid(row=1, column=0, sticky=W + E)
        self.shops_combo.current(0)

        # Make it configurable from config file
        category_choices = [
            'Laptops', 'Phones', 'Tablets', 'Tvs', 'Portable speakers',
            'Headphones', 'Consoles'
        ]
        self.category_combo = Combobox(self.top_level, values=category_choices)
        self.category_combo.grid(row=1, column=1, sticky=W + E)
        self.category_combo.current(0)

        # Search bu
        self.search_button = Button(self.top_level,
                                    text='Search',
                                    command=self.on_search_event)
        self.search_button.grid(row=2,
                                column=0,
                                columnspan=2,
                                sticky=W + E + S + N)

        # Frame to encapsulate the listbox and scrollbar
        frame = Frame(self.top_level, bd=2, relief=SUNKEN)

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

        self.listbox = Listbox(frame, bd=0, yscrollcommand=scrollbar.set)

        self.listbox.bind('<Double-Button-1>', self.on_product_inspect)
        self.listbox.bind('<Return>', self.on_product_inspect)

        self.listbox.pack(fill=BOTH, expand=1)
        frame.grid(row=3, column=0, columnspan=2, sticky=W + E + N + S)

        scrollbar.config(command=self.listbox.yview)

        for x in range(3):
            Grid.rowconfigure(self.top_level, x, pad=10)
        Grid.rowconfigure(self.top_level, 3, weight=1)
        for x in range(2):
            Grid.columnconfigure(self.top_level, x, weight=1)
def search_by_fecha():
    def mostrar_lista(event):
        lb.delete(0, END)  # borra toda la lista
        ix = open_dir(DIR_INDEX)
        locale.setlocale(locale.LC_ALL, 'es_ES')
        parameter = str(en.get().strip())
        print(parameter)
        meses = {
            "Ene": 1,
            "Feb": 2,
            "Mar": 3,
            "Abr": 4,
            "May": 5,
            "Jun": 6,
            "Jul": 7,
            "Ago": 8,
            "Sep": 9,
            "Oct": 10,
            "Nov": 11,
            "Dic": 12
        }
        fecha_rexep = re.match(r'(\d{2}) de (\w{3}) de (\d{4})', parameter)
        year = int(fecha_rexep.group(3))
        month = meses[fecha_rexep.group(2)]
        dia = int(fecha_rexep.group(1))

        fecha_parameter = (datetime(year, month, dia)).strftime('%Y%m%d')

        with ix.searcher() as searcher:
            query = QueryParser("fecha_inicio",
                                ix.schema).parse(f"[to {fecha_parameter}]")
            results = searcher.search(query, limit=None)
            for r in results:
                lb.insert(END, f"Título: {r['titulo']}")
                lb.insert(
                    END,
                    f"Rango de fechas: {r['fecha_inicio']} - {r['fecha_fin']}")
                lb.insert(END, '')

    v = Toplevel()
    v.title("Búsqueda por fecha")
    f = Frame(v)
    f.pack(side=TOP)
    l = Label(f, text="Introduzca una fecha en formato DD de MMM de YYYY:")
    l.pack(side=LEFT)
    en = Entry(f)
    en.bind("<Return>", mostrar_lista)
    en.pack(side=LEFT)
    sc = Scrollbar(v)
    sc.pack(side=RIGHT, fill=Y)
    lb = Listbox(v, yscrollcommand=sc.set)
    lb.pack(side=BOTTOM, fill=BOTH)
    sc.config(command=lb.yview)
Exemplo n.º 32
0
def show_window():
    evaluate_line()

    root = Tk()

    root.title("中文电子病历的命名实体识别系统")

    # 设置窗口大小
    width, height = 600, 600

    # 窗口居中显示
    root.geometry('%dx%d+%d+%d' % (width, height,
                                   (root.winfo_screenwidth() - width) / 2,
                                   (root.winfo_screenheight() - height) / 2))

    frame = Frame(root)
    frame.place(x=130, width=350, height=500)

    Label(frame, height=1, text="请输入测试句子:", compound='left').pack()

    global entry
    entry = Text(frame, height=7, width=50)
    entry.pack()
    # 绑定全选快捷键
    entry.bind_all("<Command-a>", selectText)

    # command绑定回调函数
    button = Button(frame, text="Run", command=runTest)
    button.pack()

    scrollBar = Scrollbar(frame)
    scrollBar.pack(side=RIGHT, fill=Y)

    global tree
    tree = ttk.Treeview(frame,
                        columns=("名称", "起点", "终点", "类型"),
                        show="headings",
                        yscrollcommand=scrollBar.set)

    tree.column("名称", width=150, anchor='center')
    tree.column("起点", width=50, anchor='center')
    tree.column("终点", width=50, anchor='center')
    tree.column("类型", width=80, anchor='center')

    tree.heading("名称", text="命名实体名称")
    tree.heading("起点", text="起始位置")
    tree.heading("终点", text="结束位置")
    tree.heading("类型", text="命名实体类型")
    tree.pack(side=LEFT, fill=Y)

    scrollBar.config(command=tree.yview)
    # 进入消息循环
    root.mainloop()
Exemplo n.º 33
0
	def _addUpperTemplate(self) :
		lblFrame = LabelFrame(self,text=" Documents ")
		lblFrame.grid(row=0,column=0,sticky="new",padx=15,pady=15,columnspan=2);

		frame = Frame(lblFrame);
		Label(frame,text="Limit Documents").grid(row=0,column=0,sticky="w",pady=5,padx=10);
		self.combo = ttk.Combobox(frame,values=["None"] + [i for i in range(1,20)] , state="readonly");
		def chooseLim(event) : self.combo.config(state="disabled");self.docsLim=self.combo.get();print(self.docsLim);
		self.combo.bind("<<ComboboxSelected>>", chooseLim);
		self.combo.grid(row=0,column=1,sticky="w")
		self.combo.current(0)
		frame.grid(row=0,column=0,sticky="w")

		frame = Frame(lblFrame)
		xscrollbar = Scrollbar(frame , orient="horizontal")
		xscrollbar.grid(row=1, column=0, sticky="snew")

		yscrollbar = Scrollbar(frame)
		yscrollbar.grid(row=0, column=1, sticky="snew")

		self.text = Text(frame , height=10 , font=("Consolas",12) , wrap="none" , xscrollcommand=xscrollbar.set , yscrollcommand=yscrollbar.set)
		self.text.grid(row=0,column=0,sticky="snew")

		xscrollbar.config(command=self.text.xview)
		yscrollbar.config(command=self.text.yview)		
		frame.grid(row=1,column=0,sticky="snew",padx=10,pady=(5,0))
	
		self.fileChoose = Label(lblFrame,text="Import from a text file",font=("consolas",10),fg="blue",cursor="hand2");
		self.fileChoose.grid(row=2,column=0,sticky="w",padx=10)
		self.fileChoose.bind("<Button-1>",lambda event : self._importText());

		rightFrame = Frame(lblFrame);
		Button(rightFrame,text="Add as a Document",relief="groove",command=self._addDoc).grid(row=0,column=0,ipady=4,padx=(5,15),pady=2,sticky="we")
		Button(rightFrame,text="Remove all Documents",relief="groove",command=self._removeDocs).grid(row=1,column=0,ipady=4,padx=(5,15),pady=2,sticky="we")
		Button(rightFrame,text="Past a Document",relief="groove",command=self._pastDoc).grid(row=2,column=0,ipady=4,padx=(5,15),pady=2,sticky="we")
		Button(rightFrame,text="Show Documents",relief="groove",command=self._showDocs).grid(row=3,column=0,ipady=4,padx=(5,15),pady=2,sticky="we");

		rightFrame.grid(row=1,column=1)

		frame2 = Frame(lblFrame);
		Label(frame2,text="Search Engine Mode").grid(row=0,column=0,sticky="w",pady=5,padx=10);
		self.combo2 = ttk.Combobox(frame2,values=["Boolean Retrival Model","Inverted Index Model","Vector Space Model"] , state="readonly");
		self.combo2.grid(row=0,column=1,sticky="we",columnspan=2,padx=(10,10))
		self.combo2.current(0)
		frame2.grid(row=3,column=0,sticky="snew",pady=15);
		frame2.columnconfigure(2,weight=1)

		frame.columnconfigure(0,weight=1);
		self.columnconfigure(0,weight=1);
		self.rowconfigure(0,weight=1);
		frame.rowconfigure(0,weight=1);
		lblFrame.rowconfigure(0,weight=4);
		lblFrame.columnconfigure(0,weight=1);
Exemplo n.º 34
0
    def __init__(self, tk: Tk):
        tk.title("Layered Polygons")

        menubar = Menu(tk)

        menu_file = Menu(menubar, tearoff=0)
        menu_file.add_command(label="New...", command=self._new_scene)
        menu_file.add_command(label="Open...", command=self._open_scene)
        menu_file.add_separator()
        menu_file.add_command(label="Save", command=self._save_scene)
        menu_file.add_command(label="Save As...", command=self._save_scene_as)
        menu_file.add_separator()
        menu_export = Menu(menu_file, tearoff=0)
        menu_export.add_command(label="Wavefront (.obj)...",
                                command=self._export_obj)
        menu_file.add_cascade(label="Export As", menu=menu_export)
        menu_file.add_separator()
        menu_file.add_command(label="Quit", command=self._quit_app)
        menubar.add_cascade(label="File", menu=menu_file)

        tk.config(menu=menubar)

        paned = PanedWindow(tk, relief=RAISED)
        paned.pack(fill=BOTH, expand=1)

        frame = Frame(paned)
        paned.add(frame)
        self._canvas = LayPolyCanvas(frame)
        bar_x = Scrollbar(frame, orient=HORIZONTAL)
        bar_x.pack(side=BOTTOM, fill=X)
        bar_x.config(command=self._canvas.xview)
        bar_y = Scrollbar(frame, orient=VERTICAL)
        bar_y.pack(side=RIGHT, fill=Y)
        bar_y.config(command=self._canvas.yview)
        self._canvas.config(xscrollcommand=bar_x.set, yscrollcommand=bar_y.set)
        self._canvas.pack(side=LEFT, expand=True, fill=BOTH)
        # Thanks to the two guys on Stack Overflow for that!
        # ( http://stackoverflow.com/a/7734187 )

        self._layer_list = Listbox(paned, selectmode=SINGLE)
        paned.add(self._layer_list)

        self._scene = None
        self._current_layer = None
        self._is_drawing_polygon = False
        self._tk = tk

        self._canvas.bind("<Button-1>", self._canvas_left_click)
        self._canvas.bind("<Button-3>", self._canvas_right_click)
        self._canvas.bind("<Motion>", self._canvas_mouse_moved)
        self._layer_list.bind("<<ListboxSelect>>", self._layer_change)

        self._current_path = None
Exemplo n.º 35
0
    def __init__(self, tk: Tk):
        tk.title("Layered Polygons")

        menubar = Menu(tk)

        menu_file = Menu(menubar, tearoff=0)
        menu_file.add_command(label="New...", command=self._new_scene)
        menu_file.add_command(label="Open...", command=self._open_scene)
        menu_file.add_separator()
        menu_file.add_command(label="Save", command=self._save_scene)
        menu_file.add_command(label="Save As...", command=self._save_scene_as)
        menu_file.add_separator()
        menu_export = Menu(menu_file, tearoff=0)
        menu_export.add_command(label="Wavefront (.obj)...",
                                command=self._export_obj)
        menu_file.add_cascade(label="Export As", menu=menu_export)
        menu_file.add_separator()
        menu_file.add_command(label="Quit", command=self._quit_app)
        menubar.add_cascade(label="File", menu=menu_file)

        tk.config(menu=menubar)

        paned = PanedWindow(tk, relief=RAISED)
        paned.pack(fill=BOTH, expand=1)

        frame = Frame(paned)
        paned.add(frame)
        self._canvas = LayPolyCanvas(frame)
        bar_x = Scrollbar(frame, orient=HORIZONTAL)
        bar_x.pack(side=BOTTOM, fill=X)
        bar_x.config(command=self._canvas.xview)
        bar_y = Scrollbar(frame, orient=VERTICAL)
        bar_y.pack(side=RIGHT, fill=Y)
        bar_y.config(command=self._canvas.yview)
        self._canvas.config(xscrollcommand=bar_x.set, yscrollcommand=bar_y.set)
        self._canvas.pack(side=LEFT, expand=True, fill=BOTH)
        # Thanks to the two guys on Stack Overflow for that!
        # ( http://stackoverflow.com/a/7734187 )

        self._layer_list = Listbox(paned, selectmode=SINGLE)
        paned.add(self._layer_list)

        self._scene = None
        self._current_layer = None
        self._is_drawing_polygon = False
        self._tk = tk

        self._canvas.bind("<Button-1>", self._canvas_left_click)
        self._canvas.bind("<Button-3>", self._canvas_right_click)
        self._canvas.bind("<Motion>", self._canvas_mouse_moved)
        self._layer_list.bind("<<ListboxSelect>>", self._layer_change)

        self._current_path = None
Exemplo n.º 36
0
 def __init__(self):
     root = Toplevel()
     root.title('Help')
     scroll = Scrollbar(root)
     mainframe = Text(root, width=100)
     scroll.pack(side='right', fill='y')
     mainframe.pack(side='left', fill='y')
     scroll.config(command=mainframe.yview)
     mainframe.config(yscroll=scroll.set)
     text = get_text_from_file()
     mainframe.insert('end', text)
     mainframe.pack()
    def __init__(self, title, message, user_enum):
        self.master = Tk()
        self.value = None
        self._user_presented_list = list(user_enum.keys())
        self._short_bubble_sort()
        self._user_enum = user_enum
        self._current_font_type = 'Times'
        self._current_font_size = 10
        self.font_obj = font.Font(font=(self._current_font_type,
                                        self._current_font_size))

        # self.modalPane = Toplevel(self.master)
        self.modalPane = self.master

        # self.modalPane.transient(self.master)
        self.modalPane.grab_set()

        self.modalPane.bind("<Return>", self._choose)
        self.modalPane.bind("<Escape>", self._cancel)

        if title:
            self.modalPane.title(title)

        if message:
            self.message_label = \
                Label(self.modalPane, text=message)
            self.message_label.pack(padx=5, pady=5)

        listFrame = Frame(self.modalPane)
        listFrame.pack(side=TOP, padx=5, pady=5)

        scrollBar = Scrollbar(listFrame)
        scrollBar.pack(side=RIGHT, fill=Y)
        self.listBox = Listbox(listFrame, selectmode=SINGLE)
        self.listBox.pack(side=LEFT, fill=Y)
        scrollBar.config(command=self.listBox.yview)
        self.listBox.config(yscrollcommand=scrollBar.set)
        # self.list.sort()
        for item in self._user_presented_list:
            self.listBox.insert(END, item)

        buttonFrame = Frame(self.modalPane)
        buttonFrame.pack(side=BOTTOM)

        chooseButton = Button(buttonFrame, text="Choose", command=self._choose)
        chooseButton.pack()

        cancelButton = Button(buttonFrame, text="Cancel", command=self._cancel)
        cancelButton.pack(side=RIGHT)

        self.set_font_size('Times', 10)
        self.autowidth(500)
Exemplo n.º 38
0
class TextExtension(Frame):
    """Extends Frame.  Intended as a container for a Text field.  Better related data handling
    and has Y scrollbar."""
    def __init__(self, master, textvariable=None, *args, **kwargs):

        super(TextExtension, self).__init__(master)
        # Init GUI

        self._y_scrollbar = Scrollbar(self, orient=VERTICAL)

        self._text_widget = Text(self,
                                 yscrollcommand=self._y_scrollbar.set,
                                 *args,
                                 **kwargs)
        self._text_widget.pack(side=LEFT, fill=BOTH, expand=1)

        self._y_scrollbar.config(command=self._text_widget.yview)
        self._y_scrollbar.pack(side=RIGHT, fill=Y)

        if textvariable is not None:
            if not (isinstance(textvariable, Variable)):
                raise TypeError("tkinter.Variable type expected, " +
                                str(type(textvariable)) +
                                " given.".format(type(textvariable)))
            self._text_variable = textvariable
            self.var_modified()
            self._text_trace = self._text_widget.bind('<<Modified>>',
                                                      self.text_modified)
            self._var_trace = textvariable.trace("w", self.var_modified)

    def text_modified(self, *args):
        if self._text_variable is not None:
            self._text_variable.trace_vdelete("w", self._var_trace)
            self._text_variable.set(self._text_widget.get(1.0, END))
            self._var_trace = self._text_variable.trace("w", self.var_modified)
            self._text_widget.edit_modified(False)

    def var_modified(self, *args):
        self.set_text(self._text_variable.get())
        self._text_widget.edit_modified(False)

    def unhook(self):
        if self._text_variable is not None:
            self._text_variable.trace_vdelete("w", self._var_trace)

    def clear(self):
        self._text_widget.delete(1.0, END)

    def set_text(self, _value):
        self.clear()
        if (_value is not None):
            self._text_widget.insert(END, _value)
Exemplo n.º 39
0
    def __init__(self, game):

        root = Tk()
        console_frame = Frame(master=root)
        vertical_scrollbar = Scrollbar(console_frame)
        text = Text(console_frame, height=2, width=130, wrap=WORD)
        text.config(yscrollcommand=vertical_scrollbar.set)
        vertical_scrollbar.config(command=text.yview)
        label = Label(console_frame, text="Console: ", anchor="w")
        console_frame.pack(side=RIGHT, fill=BOTH, expand=1)
        label.pack(side=TOP, fill=X)
        vertical_scrollbar.pack(side=RIGHT, fill=Y)
        text.pack(side=RIGHT, fill=BOTH, expand=1)

        self.game_model = game
        self.solve_model = SudokuBoard(list(chain.from_iterable(game.board)))
        self.user_board = UserBoard(game, poss_dict=game.possible_values)
        self.console = text
        self.console_scrollbar = vertical_scrollbar
        Frame.__init__(self, root)

        self.row, self.col = 0, 0
        root.title("Sudoku Solver")
        self.pack(fill=BOTH, side=LEFT)
        self.canvas = Canvas(self, width=WIDTH, height=HEIGHT)
        self.canvas.pack(fill=BOTH, side=TOP)

        clear_button = Button(self, text="Clear Answers", command=self.clear_answers)
        clear_button.pack(fill=BOTH, side=BOTTOM)

        self.hint_button = Button(self, text="Hint", command=self.hint)
        self.hint_button['state'] = 'disabled'
        self.hint_button.pack(fill=BOTH, side=BOTTOM)

        self.solve_button = Button(self, text="Solve", command=self.solve)
        self.solve_button['state'] = 'disabled'
        self.solve_button.pack(fill=BOTH, side=BOTTOM)

        new_puzzle_button = Button(self, text="New Puzzle", command=self.new_puzzle)
        new_puzzle_button.pack(fill=BOTH, side=BOTTOM)

        self.draw_grid()
        self.draw_puzzle()

        self.canvas.bind("<Button-1>", self.cell_clicked)
        self.canvas.bind("<Key>", self.key_pressed)
        self.canvas.bind("<FocusOut>", self.clear_cursor)
        self.moves = []
        thread = Thread(target=self.async_solve_model)
        thread.start()
        root.mainloop()
        thread.join()
Exemplo n.º 40
0
def Randomly(NProxy):
    #try:
    data = open('resources/data.dat', 'r')  #opening data file
    #except IOError as e:
    #	message=Toplevel()
    #	Label(message,text="Data File Not Found",justify=LEFT).pack(expand=YES, padx=10,pady=10)
    out = open('result.txt', 'w')  #opening output File
    Randomlist = []
    BranchCode = ''
    counter = 0
    RandomNumber = 0
    Record = ''

    for i in range(NProxy):  #Loop for Getting N Random Numbers
        RandomNumber = random.choice(range(996))
        Randomlist.append(RandomNumber)

    while True:
        LineRead = data.readline()  #reading data file line by line
        RollNumber = LineRead[:8]  #Extracting RollNumber
        JEERank = LineRead[9:16]  #Extracting Rank
        NameinData = LineRead[17:]
        counter += 1  #Counter for Getting N numbered Proxy Data
        if counter in Randomlist:
            LineRead.rstrip()  #stripping \n fromm the line
            Record = Record + RollNumber + '\t' + NameinData
            BranchCode = GetBranchCode(RollNumber)  #Get BranchCode
            UserID = BranchCode + RollNumber  #Make UserID
            Pwd = JEERank + 'XYZ'  #Make  Password
            out.write(UserID + '\t' + Pwd + '\n')
        if not LineRead:
            break
    data.close()
    message = Toplevel()
    message.title("Results")
    if not counter:
        out.write('Invalid  Details')  #not found case
        Label(message, text="Not Found", justify=LEFT).pack(expand=YES,
                                                            padx=10,
                                                            pady=10)
    else:
        ResultFrame = Frame(message, height=100, width=40)
        ResultScroll = Scrollbar(ResultFrame)
        ResultText = Text(ResultFrame)
        ResultScroll.pack(side=RIGHT, fill=Y)
        ResultText.pack(side=LEFT, fill=Y)
        ResultFrame.pack()
        ResultScroll.config(command=ResultText.yview)
        ResultText.config(yscrollcommand=ResultScroll.set)
        ResultText.insert(
            END, Record + "Check Out Result.txt for Proxy UserID and Password")
    out.close()
Exemplo n.º 41
0
 def init_UI(self):
     self.title("Книги по жанру")
     self.protocol("WM_DELETE_WINDOW", self.on_closing)
     Scroll = Scrollbar(self, orient=tk.VERTICAL)
     self.List = tk.Listbox(self,
                            yscrollcommand=Scroll.set,
                            height=20,
                            width=100,
                            font=("TkDefaultFont", 12))
     self.List.bind("<<ListboxSelect>>", self.open_book_info)
     Scroll.config(command=self.List.yview)
     Scroll.grid(sticky=tk.E + tk.N + tk.S, column=1, row=0, padx=3, pady=5)
     self.List.grid(sticky=tk.W + tk.E, column=0, row=0, padx=3, pady=5)
Exemplo n.º 42
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])
 def results(self):
     #Checks over all possible combinations
     self.win = Toplevel(master=self.window, height=500, width=500)
     self.win.title('Results')
     scroll = Scrollbar(self.win)
     scroll.pack(side='right', fill='y')
     self.listbox = tkinter.Listbox(self.win, width=25)
     self.listbox.config(yscrollcommand=scroll.set)
     scroll.config(command=self.listbox.yview)
     for u in range(0, 18):
         for v in range(u, 18):
             self.combo = self.A[:, u] + self.A[:, v]
             for t in range(0, 18):
                 if self.combo[t] < 0:
                     self.combo[t] = -1
                 elif self.combo[t] > 0:
                     self.combo[t] = 1
                 else:
                     continue
             bin = ''
             for t in range(0, len(self.q)):
                 if t == 0:
                     bin += '[self.cbv[' + str(t) + '].get()'
                 elif t <= (len(self.q) - 1):
                     bin += ',self.cbv[' + str(t) + '].get()'
                 if t == len(self.q) - 1:
                     bin += ']'
             bin = eval(bin)
             h = [
             ]  #h the array containing the indices of q corresponding to which boxes are checked
             for t in range(len(bin)):
                 if bin[t] == 1:
                     h.append(t)
                 else:
                     continue
             cond = ''
             for t in range(0, len(h)):
                 cond += 'self.combo[self.q[h[' + str(
                     t) + ']]]==-self.poke[self.q[h[' + str(t) + ']]]'
                 if t < (len(h) - 1):
                     cond += ' and '
             if eval(cond):
                 if u == v:
                     self.listbox.insert(1, self.value[u])
                 else:
                     self.listbox.insert(
                         1, self.value[u] + " " + self.value[v])
     self.listbox.insert(tkinter.END, ' ')
     self.listbox.insert(tkinter.END, 'End of Results')
     self.listbox.pack()
     self.menu()
Exemplo n.º 44
0
    def __init__(self, parent, *args, **kw):
        Frame.__init__(self, parent, *args, **kw)

        # create a canvas object and a vertical scrollbar for scrolling it
        vscrollbar = Scrollbar(self, orient=VERTICAL)
        vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
        canvas = Canvas(self, bd=0, highlightthickness=0,
                        yscrollcommand=vscrollbar.set)
        self._canvas = canvas
        canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
        vscrollbar.config(command=canvas.yview)

        # reset the view
        canvas.xview_moveto(0)
        canvas.yview_moveto(0)

        # create a frame inside the canvas which will be scrolled with it
        self.interior = interior = Frame(canvas)
        interior_id = canvas.create_window(0, 0, window=interior,
                                           anchor=NW)

        # track changes to the canvas and frame width and sync them,
        # also updating the scrollbar
        def _configure_interior(event):
            # update the scrollbars to match the size of the inner frame
            size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
            canvas.config(scrollregion="0 0 %s %s" % size)
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the canvas's width to fit the inner frame
                canvas.config(width=interior.winfo_reqwidth())
            if interior.winfo_reqheight() != canvas.winfo_height():
                # update the canvas's height to fit the inner frame
                canvas.config(height=interior.winfo_reqheight())

        interior.bind('<Configure>', _configure_interior)

        def _configure_canvas(event):
            """
            This function is called when the canvas is configured, that is on resize and so on,
            """
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the inner frame's width to fill the canvas
                canvas.itemconfigure(interior_id, width=canvas.winfo_width())
            if interior.winfo_reqheight() != canvas.winfo_height():
                # update the inner frame's height to fill the canvas
                canvas.itemconfigure(interior_id, height=canvas.winfo_height())

        canvas.bind('<Configure>', _configure_canvas)

        return
Exemplo n.º 45
0
class TextExtension(Frame):
    """Extends Frame.  Intended as a container for a Text field.  Better related data handling
    and has Y scrollbar."""


    def __init__(self, master, textvariable=None, *args, **kwargs):

        super(TextExtension, self).__init__(master)
        # Init GUI

        self._y_scrollbar = Scrollbar(self, orient=VERTICAL)

        self._text_widget = Text(self, yscrollcommand=self._y_scrollbar.set, *args, **kwargs)
        self._text_widget.pack(side=LEFT, fill=BOTH, expand=1)


        self._y_scrollbar.config(command=self._text_widget.yview)
        self._y_scrollbar.pack(side=RIGHT, fill=Y)

        if textvariable is not None:
            if not (isinstance(textvariable, Variable)):
                raise TypeError("tkinter.Variable type expected, " + str(type(textvariable)) + " given.".format(type(textvariable)))
            self._text_variable = textvariable
            self.var_modified()
            self._text_trace = self._text_widget.bind('<<Modified>>', self.text_modified)
            self._var_trace = textvariable.trace("w", self.var_modified)

    def text_modified(self, *args):
            if self._text_variable is not None:
                self._text_variable.trace_vdelete("w", self._var_trace)
                self._text_variable.set(self._text_widget.get(1.0, END))
                self._var_trace = self._text_variable.trace("w", self.var_modified)
                self._text_widget.edit_modified(False)

    def var_modified(self, *args):
        self.set_text(self._text_variable.get())
        self._text_widget.edit_modified(False)

    def unhook(self):
        if self._text_variable is not None:
            self._text_variable.trace_vdelete("w", self._var_trace)


    def clear(self):
        self._text_widget.delete(1.0, END)

    def set_text(self, _value):
        self.clear()
        if (_value is not None):
            self._text_widget.insert(END, _value)
Exemplo n.º 46
0
    def __init__(self, parent, list_model, label_text):
        Frame.__init__(self, parent)

        self._list_model = list_model
        self._list_objects = []
        self._selected_items = []
        scrollbar = Scrollbar(self, orient=VERTICAL)
        Label(self, text=label_text).pack()
        self.listbox = Listbox(self, selectmode=EXTENDED, exportselection=0, yscrollcommand=scrollbar.set, borderwidth=0, highlightthickness=0)
        scrollbar.config(command=self.listbox.yview)
        scrollbar.pack(side=RIGHT, fill=Y)
        self.listbox.pack(side=LEFT, fill=BOTH, expand=1)
        self.listbox.bind('<<ListboxSelect>>', self._on_select)
        self._list_model.list_items_model.add_listener(self._list_items_changed)
        self._list_model.selected_items_model.add_listener(self._selected_items_changed)
        self._update_list_items()
Exemplo n.º 47
0
 def __init__(self, master=None,**args):
     Frame.__init__(self, master,**args)
     scrollbar = Scrollbar(self, orient=VERTICAL) #нужен для отображения длинных списков
     scrollbar.unbind("<Key-Up>")
     scrollbar.unbind("<Key-Down>")
     scrollbar.unbind("<Key-Left>")
     scrollbar.unbind("<Key-Right>")
     scrollbar.pack(side=RIGHT, fill=Y)
     
     self.lst = Listbox(self, yscrollcommand=scrollbar.set, bg="grey", selectmode=SINGLE) 
     self.lst.insert(END,"Hide All")
     self.lst.insert(END,"Show All")
     self.lst.select_set(0)
     self.lst.pack(side=LEFT, fill=BOTH, expand=1)
     
     scrollbar.config(command=self.lst.yview)
Exemplo n.º 48
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")
Exemplo n.º 49
0
class LB( Listbox ):
    def __init__(self, parent):
        Listbox.__init__(self, parent, background = "#ffffff", selectbackground = "#363636", selectforeground = "#fafafa" )
        self.scbar = Scrollbar( parent )
        self.config( yscrollcommand = self.scbar.set )
        self.scbar.config( command = self.yview )
    def insertList(self, list):
        for item in list:
            self.insert( END, item["email"] )
    def deleteList(self):
        self.delete(0, END)
    def savePlaceData(self):
        self.placeData = self.place_info()
    def show(self):
        self.place( self.placeData )
        self.scbar.place( self.scbar.pi )
    def hide(self):
        self.place_forget()
        self.scbar.place_forget()
Exemplo n.º 50
0
    def __init__(self, master, valves):
        Frame.__init__(self, master)

        scrollbar = Scrollbar(self)
        scrollbar.pack(side='right', fill='y')
        scrollbar.config(background='red', activebackground='DarkRed', width=40)

        text = Text(self, wrap='word', yscrollcommand=scrollbar.set, width=52, height=14, padx=10)
        text.config(font=('Lucida Console', 30), bg='sky blue', fg='RoyalBlue4')
        text.pack()

        index = 1
        for each in valves:
            text.insert('end', 'VALVE ' + str(index) + '\n\n')
            text.insert('end', each)
            text.insert('end', '-------------------------------------------------------\n')
            index += 1

        scrollbar.config(command=text.yview)
Exemplo n.º 51
0
 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)
Exemplo n.º 52
0
def new_random_swiss(main):
    players = []
    def add_player(event):
        if e.get() is "":
            return
        players.append(e.get())
        Lb.delete(0,END)
        for x in players:
            Lb.insert(0,x)
        e.delete(0,END)

    def remove_player():
        l=len(players)-1
        if Lb.curselection():
            for x in Lb.curselection():
                Lb.delete(x)
                players.pop(l-x)
        else:
            Lb.delete(0)
            players.pop(-1)
        Lb.delete(0,END)
        for x in players:
            Lb.insert(0,x)


    top = Toplevel(main)
    top.title("New Random Swiss")
    top.bind("<Return>",add_player)
    center_size(top,360,180)
    Label(top, text='Name:').grid(row=0,column=0)
    e = Entry(top,width=12)
    e.grid(row=0,column=1)
    e.focus_force()
    Button(top,text='Add',	command=lambda:add_player(None)			).grid(row=1,column=0)
    Button(top,text='Remove',	command=remove_player				).grid(row=1,column=1)
    Button(top,text='Cancel',	command=top.destroy				).grid(row=2,column=0)
    Button(top,text='Finish',	command=lambda:create_single_swiss(players,main)).grid(row=2,column=1)
    Sb = Scrollbar(top)
    Sb.grid(row=0,column=3,rowspan=3)
    Lb = Listbox(top,selectmode=EXTENDED,yscrollcommand=Sb.set)
    Lb.grid(row=0,rowspan=3,column=2)
    Sb.config(command=Lb.yview)
Exemplo n.º 53
0
    def __init__(self, master, model):
        self.f = 0

        master.rowconfigure(0, weight=1)
        master.columnconfigure(0, weight=1)

        self.frame = tk.Frame(master)
        self.frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)

        self.frame.grid(sticky=NSEW)
        self.frame.rowconfigure(0, weight=1)
        self.frame.columnconfigure(0, weight=1)

        self.scroll_canvas = Canvas(self.frame)
        self.scroll_canvas.grid(row=0, column=0, sticky=NSEW)

        xScrollbar = Scrollbar(self.frame, orient=HORIZONTAL)
        yScrollbar = Scrollbar(self.frame)

        xScrollbar.grid(row=1, column=0, sticky=EW)
        yScrollbar.grid(row=0, column=1, sticky=NS)

        self.scroll_canvas.config(xscrollcommand=xScrollbar.set)
        xScrollbar.config(command=self.scroll_canvas.xview)
        self.scroll_canvas.config(yscrollcommand=yScrollbar.set)
        yScrollbar.config(command=self.scroll_canvas.yview)

        self.create_plot(model)

        self.figure_canvas = FigureCanvasTkAgg(self.f, master=self.scroll_canvas)
        self.canvas = self.figure_canvas.get_tk_widget()
        self.canvas.pack(side=tk.TOP, fill=tk.BOTH, padx=5, pady=5, expand=1)

        self.scroll_canvas.create_window(0, 0, window=self.canvas)
        self.scroll_canvas.config(scrollregion=self.scroll_canvas.bbox(ALL))
        self.figure_canvas.show()

        self.toolbar = NavigationToolbar2TkAgg(self.figure_canvas, self.scroll_canvas)
        self.toolbar.pack()
        self.toolbar.update()

        """
Exemplo n.º 54
0
 def _init_results_box(self, parent):
     innerframe = Frame(parent)
     i1 = Frame(innerframe)
     i2 = Frame(innerframe)
     vscrollbar = Scrollbar(i1, borderwidth=1)
     hscrollbar = Scrollbar(i2, borderwidth=1, orient='horiz')
     self.results_box = Text(i1,
                 font=tkinter.font.Font(family='courier', size='16'),
                 state='disabled', borderwidth=1,
                 yscrollcommand=vscrollbar.set,
                 xscrollcommand=hscrollbar.set, wrap='none', width='40', height = '20', exportselection=1)
     self.results_box.pack(side='left', fill='both', expand=True)
     vscrollbar.pack(side='left', fill='y', anchor='e')
     vscrollbar.config(command=self.results_box.yview)
     hscrollbar.pack(side='left', fill='x', expand=True, anchor='w')
     hscrollbar.config(command=self.results_box.xview)
     #there is no other way of avoiding the overlap of scrollbars while using pack layout manager!!!
     Label(i2, text='   ', background=self._BACKGROUND_COLOUR).pack(side='left', anchor='e')
     i1.pack(side='top', fill='both', expand=True, anchor='n')
     i2.pack(side='bottom', fill='x', anchor='s')
     innerframe.pack(side='top', fill='both', expand=True)
Exemplo n.º 55
0
    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()
Exemplo n.º 56
0
    def __init__(self):
        self.action = None
        self.root = root = Tk()
        root.title('Never gonna fold you up')
        root.protocol("WM_DELETE_WINDOW", self.close)

        root.pack_propagate(True)

        scrollbar = Scrollbar(root, orient=tkinter.VERTICAL)
        self.problem_list = Listbox(root, exportselection=False, yscrollcommand=scrollbar.set)
        self.problem_list.pack(expand=True, fill=tkinter.BOTH, side=tkinter.LEFT)
        scrollbar.config(command=self.problem_list.yview)
        scrollbar.pack(side=tkinter.LEFT, fill=tkinter.Y)
        self.problem_list.bind('<<ListboxSelect>>', lambda evt: self.populate_problem_canvas())

        self.problem_canvas = Canvas(root, bd=1, relief=tkinter.SUNKEN, width=500, height=500)
        self.problem_canvas.pack(expand=True, fill=tkinter.BOTH, side=tkinter.LEFT)
        self.problem_canvas.bind("<Configure>", lambda evt: self.populate_problem_canvas())

        button_frame = Frame(root)
        button_frame.pack(fill=tkinter.Y, side=tkinter.LEFT)

        # Reposition the figure so it's center of mass is at 0.5, 0.5
        v = IntVar()
        self.center_cb = Checkbutton(button_frame, text="center", variable=v, command=lambda: self.populate_problem_canvas())
        self.center_cb.var = v
        self.center_cb.pack(side=tkinter.TOP)

        # Use meshes.reconstruct_facets instead of polygon/hole logic.
        v = IntVar()
        self.reconstruct_cb = Checkbutton(button_frame, text="reconstruct", variable=v, command=lambda: self.populate_problem_canvas())
        self.reconstruct_cb.var = v
        self.reconstruct_cb.pack(side=tkinter.TOP)

        self.populate_problems()
        self.current_problem_name = None
        self.current_problem = None
Exemplo n.º 57
0
 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)
Exemplo n.º 58
0
    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)
Exemplo n.º 59
0
    def initUI(self):
        self.parent.title("TVstream manager")
        self.stytle = ttk.Style()
        self.pack(fill=BOTH, expand=1)        
        self.columnconfigure(0, weight=1, pad=2)
        self.columnconfigure(2, weight=1, pad=2)
        self.columnconfigure(4,  pad=7)
        #self.rowconfigure(3, weight=1)
        #self.rowconfigure(4, weight=1, pad=7)

        lbll = Label(self, text="Lingua")
        lbll.grid(row=0,column=0,sticky=W, pady=4, padx=5)

        lble = Label(self, text="Emittenti")
        lble.grid(row=0,column=2,sticky=W, pady=1, padx=5)

        global langlst
        scrollang = Scrollbar(self)
        langlst = Listbox(self,font='Arial 9',yscrollcommand=scrollang.set)
        scrollang.config(command = langlst.yview)
        
        for i in lingue:
            langlst.insert(END, i)
        langlst.focus_set()
        
        langlst.bind("<<ListboxSelect>>", self.onSelectLang)  
        langlst.grid(row=1,column=0, columnspan=2, padx=6,sticky=E+W+S+N)
        scrollang.grid(row=1,column=1, sticky=E+S+N)

        global emitlst
        scrollemit = Scrollbar(self)
        emitlst = Listbox(self,font='Arial 9',yscrollcommand=scrollemit.set)
        scrollemit.config(command = emitlst.yview )
        emitlst.bind("<<ListboxSelect>>", self.onSelectEmittente)
        emitlst.grid(row=1,column=2, columnspan=2, padx=5,sticky=E+W+S+N)
        scrollemit.grid(row=1,column=3,sticky=E+S+N)

        lbltxt = Label(self, text="Output log")
        lbltxt.grid(row=2,column=0, columnspan=3, sticky=W, pady=4, padx=5)
        
        global area
        area = Text(self,height=10,font='Arial 9')
        area.grid(row=3, column=0, columnspan=5, rowspan=1, padx=5, sticky=E+W+S+N)
        scrolltxt = Scrollbar(self)
        scrolltxt.config(command = area.yview)
        scrolltxt.grid(row=3,column=4, columnspan=1, rowspan=1, sticky=E+N+S)
        
        play = Button(self, text='Play', command=self.playUrl,
               bg='gray', fg='black')
        play.grid(row=1,column=4,padx=4,sticky=E+W)
Exemplo n.º 60
0
class CFGEditor(object):
    """
    A dialog window for creating and editing context free grammars.
    ``CFGEditor`` imposes the following restrictions:

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

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

        self._highlight_matching_nonterminals = 1

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

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

        self._textwidget.focus()

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

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

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

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

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

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

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

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

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

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

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

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

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

        self._analyze()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        return productions

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

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

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

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

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

    def _help(self, *e):
        # The default font's not very legible; try using 'fixed' instead.
        try:
            ShowText(self._parent, 'Help: Chart Parser Demo',
                     (_CFGEditor_HELP).strip(), width=75, font='fixed')
        except:
            ShowText(self._parent, 'Help: Chart Parser Demo',
                     (_CFGEditor_HELP).strip(), width=75)