Exemplo n.º 1
0
      def underline(self, *args):
          """Toggles underline for selected text."""
          try:
              current_tags = self.text.tag_names("sel.first")
              if "underline" in current_tags:
                  self.text.tag_remove("underline", "sel.first", "sel.last")
              else:
                  self.text.tag_add("underline", "sel.first", "sel.last")
                  underline_font = Font(self.text, self.text.cget("font"))
                  underline_font.configure(underline=1)
                  self.text.tag_configure("underline", font=underline_font)
          except TclError:
              pass
              """Accelerator bindings. The cut, copy, and paste functions are not
 #                               bound to keyboard shortcuts because Windows already binds them, so if
 #                               Tkinter bound them as well whenever you typed ctrl+v the text would be
 #                               pasted twice."""
              self.bind_all("<Control-b>", self.bold)
              self.bind_all("<Control-i>", self.italic)
              self.bind_all("<Control-u>", self.underline)
 
              self.text = ScrolledText(self, state='normal', height=30, wrap='word', font=Font, pady=2, padx=3,
                                      undo=True)
              self.text.grid(column=0, row=0, sticky='NSEW')
 
              # Frame configuration
              self.grid_columnconfigure(0, weight=1)
              self.resizable(True, True)
 #
              if __name__ == "__main__":
                  app = Notepad()
                  app.title("Abhishek - Notepad")
                  app.option_add('*tearOff', False)
                  app.mainloop()
Exemplo n.º 2
0
 def adjust_fonts(self, event):
   new_font = Font(**self.fonts['normal'].configure())
   size = orig_size = new_font['size']
   desired_total_height = event.height
   orig_row_height = new_font.metrics('linespace')
   orig_row_height += self.LS_EXTRA
   orig_total_height = self.N_ROWS * orig_row_height
   if orig_total_height < desired_total_height:
     a, compfname, final_neg_adjust = 1, '__gt__', True
   elif orig_total_height > desired_total_height:
     a, compfname, final_neg_adjust = -1, '__lt__', False
   else:
     return
   prev_total_height = orig_total_height
   while True:
     if a < 0 and size <= self.MIN_FONT_SIZE:
       size = self.MIN_FONT_SIZE
       break
     size += a
     new_font.configure(size=size)
     new_row_height = new_font.metrics('linespace')
     new_row_height += self.LS_EXTRA
     new_total_height = self.N_ROWS * new_row_height
     if new_total_height == prev_total_height:
       size -= a
       break
     compf = getattr(new_total_height, compfname)
     if compf(desired_total_height):
       if final_neg_adjust and size > self.MIN_FONT_SIZE:
         size -= a
       break
     prev_total_height = new_total_height
   if size != orig_size:
     self.fonts['normal'].configure(size=size)
     self.fonts['bold'].configure(size=size)
 def append_length(self):
     if self.length_title_label == None:
         self.length_title_label = tkinter.Label(self,
                                            text="Lengths")
         self.length_title_label.place(x=50, y=50)
         f = Font(self.length_title_label,
                  self.length_title_label.cget("font"))
         f.configure(underline = True)
         self.length_title_label.configure(font=f)
         
     
     y_val = 75 + self.get_N() * 20
     l_label = tkinter.Label(self,
                           text="L" + str(self.get_N()+1) + ":")
     l_label.place(x=20, y=y_val)
     l_box = tkinter.Entry(self, width=10, justify="center",
                         validate='key',
                         validatecommand=self.length_vcmd)
     l_box.place(x=50, y=y_val)
     l_box.insert(0, str(DEFAULT_LENGTH))
     l_box.bind("<FocusOut>", self.update_parameters)
     l_box.bind("<Return>", self.update_parameters)
     
     remove_event = lambda self=self: self.remove_length(self.get_N())
     remove_button = tkinter.Button(self, fg="#ff0000",
                                    text="X", padx=0, pady=0,
                                    command=remove_event)
     remove_button.place(x=140, y=y_val)
     
     self.length_labels.append(l_label)
     self.length_boxes.append(l_box)
     self.remove_buttons.append(remove_button)
 def append_weight(self):
     index = self.get_N() - 2
     if self.weight_title_label == None:
         self.weight_title_label = tkinter.Label(self,
                                            text="Weights")
         self.weight_title_label.place(x=470, y=50)
         f = Font(self.weight_title_label,
                  self.weight_title_label.cget("font"))
         f.configure(underline = True)
         self.weight_title_label.configure(font=f)
         
     weight_y_val = 75 + (index) * 20
     w_label = tkinter.Label(self,
                             text="W"+str(index)+":")
     w_label.place(x=440, y=weight_y_val)
     w_box = tkinter.Entry(self, width=10,
                           justify="center",
                           validate='key',
                           validatecommand=self.weight_vcmd)
     w_box.place(x=470, y=weight_y_val)
     w_box.insert(0, str(DEFAULT_WEIGHT))
     w_box.bind("<FocusOut>", self.update_parameters)
     w_box.bind("<Return>", self.update_parameters)
     self.weight_labels.append(w_label)
     self.weight_boxes.append(w_box)
Exemplo n.º 5
0
class Linkbutton(ttk.Button):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # Obtener el nombre de la fuente utilizada para ttk.Label.
        label_font = nametofont("TkDefaultFont").cget("family")
        self.font = Font(family=label_font, size=9)

        # Crear un nuevo estilo.
        style = ttk.Style()
        style.configure("Link.TLabel", foreground="#357fde", font=self.font)

        # Aplicarlo al enlace.
        self.configure(style="Link.TLabel", cursor="hand2")

        # Configurar eventos.
        self.bind("<Enter>", self.on_mouse_enter)
        self.bind("<Leave>", self.on_mouse_leave)

    def on_mouse_enter(self, event):
        # Aplicar subrayado.
        self.font.configure(underline=True)

    def on_mouse_leave(self, event):
        # Quitar subrayado.
        self.font.configure(underline=False)
Exemplo n.º 6
0
class TickTock(Frame):
    def __init__(self, parent, time=0, scaledown=1):
        Frame.__init__(self, parent)

        self.parent = parent
        self.time = time
        self.scaledown = scaledown
        self.run = True

        self.time_str = StringVar()
        self._format_time()
        self.font = Font(family="Source Code Pro")

        Label(self, textvariable=self.time_str, font=self.font).pack()

        self.bind('<Configure>', self._resize)

    def get_time(self):

        return self.time

    def _format_time(self):
        self.time_str.set("{:02d}:{:02d}".format(*divmod(self.time, 60)))
        return

    def _resize(self, event):
        height = (self.winfo_width()) // (-4 * self.scaledown)
        print(height)
        self.font.configure(size=height)
        return
Exemplo n.º 7
0
    def decreaseFontSize(self):

        curr_editor = self._get_current_editor() # FIXME
        curr_font = Font(curr_editor, curr_editor.cget("font"))
        curr_size = curr_font.cget('size')
        if curr_size > 1:
            new_size = curr_size-1
            curr_font.configure(size=new_size)
Exemplo n.º 8
0
    def increaseFontSize(self):

        curr_editor = self._get_current_editor() # FIXME
        curr_font = Font(curr_editor, curr_editor.cget("font"))
        curr_size = curr_font.cget('size')
        new_size = curr_size+1
        curr_font.configure(size=new_size)
        new_font = curr_font
        curr_editor.configure(font=new_font)
 def bold(self, *args):  # Works only if text is selected
     try:
         current_tags = self.text.tag_names("sel.first")
         if "bold" in current_tags:
             self.text.tag_remove("bold", "sel.first", "sel.last")
         else:
             self.text.tag_add("bold", "sel.first", "sel.last")
             bold_font = Font(self.text, self.text.cget("font"))
             bold_font.configure(weight="bold")
             self.text.tag_configure("bold", font=bold_font)
     except:
         pass
 def italic(self, *args):  # Works only if text is selected
     try:
         current_tags = self.text.tag_names("sel.first")
         if "italic" in current_tags:
             self.text.tag_remove("italic", "sel.first", "sel.last")
         else:
             self.text.tag_add("italic", "sel.first", "sel.last")
             italic_font = Font(self.text, self.text.cget("font"))
             italic_font.configure(slant="italic")
             self.text.tag_configure("italic", font=italic_font)
     except:
         pass
 def underline(self, *args):  # Works only if text is selected
     try:
         current_tags = self.text.tag_names("sel.first")
         if "underline" in current_tags:
             self.text.tag_remove("underline", "sel.first", "sel.last")
         else:
             self.text.tag_add("underline", "sel.first", "sel.last")
             underline_font = Font(self.text, self.text.cget("font"))
             underline_font.configure(underline=1)
             self.text.tag_configure("underline", font=underline_font)
     except:
         pass
Exemplo n.º 12
0
def italic():
    try:
        current_tags = textArea.tag_names("sel.first")
        if "italic" in current_tags:
            textArea.tag_remove("italic", "sel.first", "sel.last")
        else:
            textArea.tag_add("italic", "sel.first", "sel.last")
            italic_font = Font(textArea, textArea.cget("font"))
            italic_font.configure(slant="italic")
            textArea.tag_configure("italic", font=italic_font)
    except TclError:
        pass
 def overstrike(self, *args):  # Works only if text is selected
     try:
         current_tags = self.text.tag_names("sel.first")
         if "overstrike" in current_tags:
             self.text.tag_remove("overstrike", "sel.first", "sel.last")
         else:
             self.text.tag_add("overstrike", "sel.first", "sel.last")
             overstrike_font = Font(self.text, self.text.cget("font"))
             overstrike_font.configure(overstrike=1)
             self.text.tag_configure("overstrike", font=overstrike_font)
     except:
         pass
Exemplo n.º 14
0
def underline():
    try:
        current_tags = textArea.tag_names("sel.first")
        if "underline" in current_tags:
            textArea.tag_remove("underline", "sel.first", "sel.last")
        else:
            textArea.tag_add("underline", "sel.first", "sel.last")
            underline_font = Font(textArea, textArea.cget("font"))
            underline_font.configure(underline=1)
            textArea.tag_configure("underline", font=underline_font)
    except TclError:
        pass
Exemplo n.º 15
0
def bold():
    try:
        current_tags = textArea.tag_names("sel.first")
        if "bold" in current_tags:
            textArea.tag_remove("bold", "sel.first", "sel.last")
        else:
            textArea.tag_add("bold", "sel.first", "sel.last")
            bold_font = Font(textArea, textArea.cget("font"))
            bold_font.configure(weight="bold")
            textArea.tag_configure("bold", font=bold_font)
    except TclError:
        pass
Exemplo n.º 16
0
    def __init__(self, master, client, queue, send_command):
        super(ClientUI, self).__init__()
        self.client = client
        self.queue = queue
        self.send_command = send_command
        self.master = master
        self.plugin_manager = PluginManager(self.send_command_with_prefs,
                                            self.echo)
        self.interrupt_input = False
        self.interrupt_buffer = deque()
        self.input_buffer = []
        self.input_cursor = 0
        self.list_depth = 0
        self.MAP_OFFSET = 60

        menu_bar = tk.Menu(master)
        self.menu_file = tk.Menu(menu_bar, tearoff=0)
        self.menu_file.add_command(label="Preferences",
                                   command=self.show_preferences)
        self.menu_file.add_command(label="Disconnect",
                                   command=self.client.shutdown)
        self.menu_file.add_command(label="Quit", command=self.client.quit)
        menu_bar.add_cascade(label="Client", menu=self.menu_file)

        self.create_plugin_menu(menu_bar)

        self.master.config(menu=menu_bar)

        self.master.grid()
        tk.Grid.rowconfigure(self.master, 0, weight=1)
        tk.Grid.columnconfigure(self.master, 0, weight=1)
        self.status = dict()
        self.create_widgets()

        self.side_bar = master.children['side_bar']
        self.output_panel = master.children['output_frame'].children['output']
        self.output_panel.configure(state="normal")
        self.output_panel.bind('<Key>', lambda e: 'break')
        self.input = master.children['input']
        self.context_menu = master.children['context_menu']

        self.char_width = Font(self.output_panel,
                               self.output_panel.cget("font")).measure('0')
        self.line_length = self.calc_line_length(
            self.output_panel.cget("width"))
        italic_font = Font(self.output_panel, self.output_panel.cget("font"))
        italic_font.configure(slant='italic')
        self.output_panel.tag_configure("italic", font=italic_font)
        bold_font = Font(self.output_panel, self.output_panel.cget("font"))
        bold_font.configure(weight='bold')
        self.output_panel.tag_configure('bold', font=bold_font)
        self.output_panel.tag_configure("center", justify=tk.CENTER)
Exemplo n.º 17
0
 def underline(self, event=None, *args):
     """Set Underline in Font or remove Underline in Font"""
     try:
         current_tag = self.text.tag_names("sel.first")
         if "underline" in current_tag:
             self.text.tag_remove("underline", "sel.first", "sel.last")
         else:
             self.text.tag_add("underline", "sel.first", "sel.last")
             underline_font = Font(self.text, self.text.cget("font"))
             underline_font.configure(underline=1)
             self.text.tag_configure("underline", font=underline_font)
     except TclError:
         pass
Exemplo n.º 18
0
 def bold(self, *args):
     """Toggles bold for selected text."""
     try:
         current_tags = self.text.tag_names("sel.first")
         if "bold" in current_tags:
             self.text.tag_remove("bold", "sel.first", "sel.last")
         else:
             self.text.tag_add("bold", "sel.first", "sel.last")
             bold_font = Font(self.text, self.text.cget("font"))
             bold_font.configure(weight="bold")
             self.text.tag_configure("bold", font=bold_font)
     except TclError:
         pass
Exemplo n.º 19
0
 def italic(self, *args):
     """Toggles italic for selected text."""
     try:
         current_tags = self.text.tag_names("sel.first")
         if "italic" in current_tags:
             self.text.tag_remove("italic", "sel.first", "sel.last")
         else:
             self.text.tag_add("italic", "sel.first", "sel.last")
             italic_font = Font(self.text, self.text.cget("font"))
             italic_font.configure(slant="italic")
             self.text.tag_configure("italic", font=italic_font)
     except TclError:
         pass
Exemplo n.º 20
0
 def underline(self, *args):
     """Toggles underline for selected text."""
     try:
         current_tags = self.text.tag_names("sel.first")
         if "underline" in current_tags:
             self.text.tag_remove("underline", "sel.first", "sel.last")
         else:
             self.text.tag_add("underline", "sel.first", "sel.last")
             underline_font = Font(self.text, self.text.cget("font"))
             underline_font.configure(underline=1)
             self.text.tag_configure("underline", font=underline_font)
     except TclError:
         pass
Exemplo n.º 21
0
 def underline(self, *args):
     """Toggles underline for selected text."""
     try:
         current_tags = self.__thisTextArea.tag_names("sel.first")
         if "underline" in current_tags:
             self.__thisTextArea.tag_remove("underline", "sel.first", "sel.last")
         else:
             self.__thisTextArea.tag_add("underline", "sel.first", "sel.last")
             underline_font = Font(self.__thisTextArea, self.__thisTextArea.cget("font"))
             underline_font.configure(underline=1)
             self.__thisTextArea.tag_configure("underline", font=underline_font)
     except TclError:
         pass
Exemplo n.º 22
0
 def overstrike(self, *args):
     """Toggles overstrike for selected text."""
     try:
         current_tags = self.text.tag_names("sel.first")
         if "overstrike" in current_tags:
             self.text.tag_remove("overstrike", "sel.first", "sel.last")
         else:
             self.text.tag_add("overstrike", "sel.first", "sel.last")
             overstrike_font = Font(self.text, self.text.cget("font"))
             overstrike_font.configure(overstrike=1)
             self.text.tag_configure("overstrike", font=overstrike_font)
     except TclError:
         pass
Exemplo n.º 23
0
    def break_tag(self):

        text = '**{50}**'
        self.text.insert(INSERT, text)  # add at current insert cursor
        self.text.tag_remove(SEL, '1.0', END)
        self.text.tag_add(SEL, INSERT + '-%dc' % len(text), INSERT)

        self.text.tag_add("bold", "sel.first", "sel.last")
        bold_font = Font(self.text, self.text.cget("font"))
        size = int(self.text.cget("font").split(' ')[1])

        bold_font.configure(weight="bold", size=size - 2, slant="italic")
        self.text.tag_configure("bold", font=bold_font)
Exemplo n.º 24
0
 def bold(self, *args):
     """Toggles bold for selected text."""
     try:
         current_tags = self.text.tag_names("sel.first")
         if "bold" in current_tags:
             self.text.tag_remove("bold", "sel.first", "sel.last")
         else:
             self.text.tag_add("bold", "sel.first", "sel.last")
             bold_font = Font(self.text, self.text.cget("font"))
             bold_font.configure(weight="bold")
             self.text.tag_configure("bold", font=bold_font)
     except TclError:
         pass
Exemplo n.º 25
0
 def bold(self, event=None, *args):
     """Change Font in Bold or Bold to normal"""
     try:
         current_tag = self.text.tag_names("sel.first")
         if "bold" in current_tag:
             self.text.tag_remove("bold", "sel.first", "sel.last")
         else:
             self.text.tag_add("bold", "sel.first", "sel.last")
             bold_tag = Font(self.text, self.text.cget("font"))
             bold_tag.configure(weight="bold")
             self.text.tag_configure("bold", font=bold_tag)
     except TclError:
         pass
Exemplo n.º 26
0
 def overstrike(self, *args):
     """Toggles overstrike for selected text."""
     try:
         current_tags = self.text.tag_names("sel.first")
         if "overstrike" in current_tags:
             self.text.tag_remove("overstrike", "sel.first", "sel.last")
         else:
             self.text.tag_add("overstrike", "sel.first", "sel.last")
             overstrike_font = Font(self.text, self.text.cget("font"))
             overstrike_font.configure(overstrike=1)
             self.text.tag_configure("overstrike", font=overstrike_font)
     except TclError:
         pass
Exemplo n.º 27
0
 def overstrike(self, event=None, *args):
     """Set Overstrike in Font or remove Overstrike in Font"""
     try:
         current_tag = self.text.tag_names("sel.first")
         if "overstrike" in current_tag:
             self.text.tag_remove("overstrike", "sel.first", "sel.last")
         else:
             self.text.tag_add("overstrike", "sel.first", "sel.last")
             overstrike_font = Font(self.text, self.text.cget("font"))
             overstrike_font.configure(overstrike=1)
             self.text.tag_configure("overstrike", font=overstrike_font)
     except TclError:
         pass
Exemplo n.º 28
0
 def italic(self, event=None, *args):
     """Change Font in Italic or Italic to normal"""
     try:
         current_tag = self.text.tag_names("sel.first")
         if "italic" in current_tag:
             self.text.tag_remove("italic", "sel.first", "sel.last")
         else:
             self.text.tag_add("italic", "sel.first", "sel.last")
             italic_tag = Font(self.text, self.text.cget("font"))
             italic_tag.configure(slant="italic")
             self.text.tag_configure("italic", font=italic_tag)
     except TclError:
         pass
Exemplo n.º 29
0
    def _bolder(self, text, counter):

        self.text.insert(INSERT, text)  # add at current insert cursor
        self.text.tag_remove(SEL, '1.0', END)
        self.text.tag_add(SEL, INSERT + '-%dc' % len(text), INSERT)

        if counter != 1:
            self.text.tag_add("bold", "sel.first", "sel.last")
            bold_font = Font(self.text, self.text.cget("font"))
            size = int(self.text.cget("font").split(' ')[1])

            bold_font.configure(weight="bold", size=size - 2, slant="italic")
            self.text.tag_configure("bold", font=bold_font)
Exemplo n.º 30
0
 def italic(self, *args):
     """Toggles italic for selected text."""
     try:
         current_tags = self.text.tag_names("sel.first")
         if "italic" in current_tags:
             self.text.tag_remove("italic", "sel.first", "sel.last")
         else:
             self.text.tag_add("italic", "sel.first", "sel.last")
             italic_font = Font(self.text, self.text.cget("font"))
             italic_font.configure(slant="italic")
             self.text.tag_configure("italic", font=italic_font)
     except TclError:
         pass
Exemplo n.º 31
0
def main(root, text, menubar):
    objFormat = Format(text)

    fontoptions = families(root)
    font = Font(family="Arial", size=10)
    text.configure(font=font)

    formatMenu = Menu(menubar)

    fsubmenu = Menu(formatMenu, tearoff=0)
    ssubmenu = Menu(formatMenu, tearoff=0)

    for option in fontoptions:
        fsubmenu.add_command(
            label=option,
            command=lambda option=option: font.configure(family=option))
    for value in range(1, 31):
        ssubmenu.add_command(
            label=str(value),
            command=lambda value=value: font.configure(size=value))

    formatMenu.add_command(label="Change Background",
                           command=objFormat.changeBg)
    formatMenu.add_command(label="Change Font Color",
                           command=objFormat.changeFg)
    formatMenu.add_cascade(label="Font", underline=0, menu=fsubmenu)
    formatMenu.add_cascade(label="Size", underline=0, menu=ssubmenu)
    formatMenu.add_command(label="Bold",
                           command=objFormat.bold,
                           accelerator="Ctrl+B")
    formatMenu.add_command(label="Italic",
                           command=objFormat.italic,
                           accelerator="Ctrl+I")
    formatMenu.add_command(label="Underline",
                           command=objFormat.underline,
                           accelerator="Ctrl+U")
    formatMenu.add_command(label="Overstrike",
                           command=objFormat.overstrike,
                           accelerator="Ctrl+T")
    formatMenu.add_command(label="Add Date", command=objFormat.addDate)
    menubar.add_cascade(label="Format", menu=formatMenu)

    root.bind_all("<Control-b>", objFormat.bold)
    root.bind_all("<Control-i>", objFormat.italic)
    root.bind_all("<Control-u>", objFormat.underline)
    root.bind_all("<Control-T>", objFormat.overstrike)

    root.grid_columnconfigure(0, weight=1)
    root.resizable(True, True)

    root.config(menu=menubar)
    def __init__(self, text, root, mainWin):
        self.text = text
        self.root = root
        self.mainWin = mainWin

        fontoptions = families(root)
        font = Font(family="Verdana", size=10)
        formatMenu = tk.Menu(mainWin.menubar, tearoff=0)
        fsubmenu = tk.Menu(formatMenu, tearoff=0)
        ssubmenu = tk.Menu(formatMenu, tearoff=0)

        for option in fontoptions:
            fsubmenu.add_command(label=option,
                                 command=lambda: font.configure(family=option))
        for value in range(1, 31):
            ssubmenu.add_command(label=str(value),
                                 command=lambda: font.configure(size=value))

        formatMenu.add_command(label="Change Background",
                               command=self.change_bg)
        formatMenu.add_command(label="Change Font Color",
                               command=self.change_fg)
        formatMenu.add_cascade(label="Font", underline=0, menu=fsubmenu)
        formatMenu.add_cascade(label="Size", underline=0, menu=ssubmenu)
        formatMenu.add_command(label="Bold",
                               command=self.bold,
                               accelerator="Ctrl+B")
        formatMenu.add_command(label="Italic",
                               command=self.italic,
                               accelerator="Ctrl+I")
        formatMenu.add_command(label="Underline",
                               command=self.underline,
                               accelerator="Ctrl+U")
        formatMenu.add_command(label="Overstrike",
                               command=self.overstrike,
                               accelerator="Ctrl+T")
        formatMenu.add_command(label="Add Date", command=self.addDate)
        mainWin.menubar.add_cascade(label="Format", menu=formatMenu)

        root.bind_all("<Control-b>", self.bold)
        root.bind_all("<Control-i>", self.italic)
        root.bind_all("<Control-u>", self.underline)
        root.bind_all("<Control-T>", self.overstrike)

        root.grid_columnconfigure(0, weight=1)
        root.resizable(True, True)

        root.config(menu=mainWin.menubar)
Exemplo n.º 33
0
    def __init__(self, master, client, queue, send_command):
        super(ClientUI, self).__init__()
        self.client = client
        self.queue = queue
        self.send_command = send_command
        self.master = master
        self.plugin_manager = PluginManager(self.send_command_with_prefs, self.echo)
        self.interrupt_input = False
        self.interrupt_buffer = deque()
        self.input_buffer = []
        self.input_cursor = 0
        self.list_depth = 0
        self.MAP_OFFSET = 60

        menu_bar = tk.Menu(master)
        self.menu_file = tk.Menu(menu_bar, tearoff=0)
        self.menu_file.add_command(label="Preferences", command=self.show_preferences)
        self.menu_file.add_command(label="Disconnect", command=self.client.shutdown)
        self.menu_file.add_command(label="Quit", command=self.client.quit)
        menu_bar.add_cascade(label="Client", menu=self.menu_file)

        self.create_plugin_menu(menu_bar)

        self.master.config(menu=menu_bar)

        self.master.grid()
        tk.Grid.rowconfigure(self.master, 0, weight=1)
        tk.Grid.columnconfigure(self.master, 0, weight=1)
        self.status = dict()
        self.create_widgets()

        self.side_bar = master.children['side_bar']
        self.output_panel = master.children['output_frame'].children['output']
        self.output_panel.configure(state="normal")
        self.output_panel.bind('<Key>', lambda e: 'break')
        self.input = master.children['input']
        self.context_menu = master.children['context_menu']

        self.char_width = Font(self.output_panel, self.output_panel.cget("font")).measure('0')
        self.line_length = self.calc_line_length(self.output_panel.cget("width"))
        italic_font = Font(self.output_panel, self.output_panel.cget("font"))
        italic_font.configure(slant='italic')
        self.output_panel.tag_configure("italic", font=italic_font)
        bold_font = Font(self.output_panel, self.output_panel.cget("font"))
        bold_font.configure(weight='bold')
        self.output_panel.tag_configure('bold', font=bold_font)
        self.output_panel.tag_configure("center", justify=tk.CENTER)
 def append_limits(self):
     if self.lower_limits_title_label == None:
         self.lower_limits_title_label = tkinter.Label(self,
                                            text="Lower Limits")
         self.lower_limits_title_label.place(x=220, y=50)
         f = Font(self.lower_limits_title_label,
                  self.lower_limits_title_label.cget("font"))
         f.configure(underline = True)
         self.lower_limits_title_label.configure(font=f)
         self.upper_limits_title_label = tkinter.Label(self,
                                            text="Upper Limits")
         self.upper_limits_title_label.place(x=320, y=50)
         f = Font(self.upper_limits_title_label,
                  self.upper_limits_title_label.cget("font"))
         f.configure(underline = True)
         self.upper_limits_title_label.configure(font=f)
         
     y_val = 75 + self.get_N() * 20
     label = tkinter.Label(self, text="Lim"+str(self.get_N())+":")
     label.place(x=175, y=y_val)
     self.limits_labels.append(label)
     
     lower_lim_box = tkinter.Entry(self, width=10,
                         justify="center",
                         validate='key',
                         validatecommand=self.limit_vcmd)
     lower_lim_box.place(x=220, y=y_val)
     lower_lim_box.insert(0, str(DEFAULT_LOWER_LIMIT))
     lower_lim_box.bind("<FocusOut>", self.update_parameters)
     lower_lim_box.bind("<Return>", self.update_parameters)
     self.lower_limits_boxes.append(lower_lim_box)
     
     upper_lim_box = tkinter.Entry(self, width=10,
                         justify="center",
                         validate='key',
                         validatecommand=self.limit_vcmd)
     upper_lim_box.place(x=320, y=y_val)
     upper_lim_box.insert(0, str(DEFAULT_UPPER_LIMIT))
     upper_lim_box.bind("<FocusOut>", self.update_parameters)
     upper_lim_box.bind("<Return>", self.update_parameters)
     self.upper_limits_boxes.append(upper_lim_box)
Exemplo n.º 35
0
    def createTags(self):
        curr_editor = self._get_current_editor()
        bold_font = Font(curr_editor, curr_editor.cget("font"))
        bold_font.configure(weight='bold')

        italic_font = Font(curr_editor, curr_editor.cget("font"))
        italic_font.configure(slant='italic')

        bold_italic_font = Font(curr_editor, curr_editor.cget("font"))
        bold_italic_font.configure(weight='bold', slant='italic')

        style = get_style_by_name('default')
        for ttype, ndef in style:
            tag_font = None
            if ndef['bold'] and ndef['italic']:
                tag_font = bold_italic_font
            elif ndef['bold']:
                tag_font = bold_font
            elif ndef['italic']:
                tag_font = italic_font

            if ndef['color']:
                foreground = "#%s" % ndef['color']
            else:
                foreground = None

            curr_editor.tag_configure(str(ttype),
                                    foreground=foreground,
                                    font=tag_font)
Exemplo n.º 36
0
    def __init__(self, master, client, queue, send_command):
        super(ClientUI, self).__init__()
        self.client = client
        self.queue = queue
        self.send_command = send_command
        self.master = master
        self.interrupt_input = False
        self.interrupt_buffer = deque()
        self.input_buffer = []
        self.input_cursor = 0
        self.list_depth = 0

        menu_bar = tk.Menu(master)
        self.menu_file = tk.Menu(menu_bar, tearoff=0)
        self.menu_file.add_command(label="Preferences", command=self.show_preferences)
        self.menu_file.add_command(label="Disconnect", command=self.client.shutdown)
        self.menu_file.add_command(label="Quit", command=self.client.quit)
        menu_bar.add_cascade(label="Client", menu=self.menu_file)
        self.master.config(menu=menu_bar)

        self.master.grid()
        tk.Grid.rowconfigure(self.master, 0, weight=1)
        tk.Grid.columnconfigure(self.master, 0, weight=1)
        self.create_widgets()

        # pprint(vars(master))
        self.side_bar = master.children['side_bar']
        self.output_panel = master.children['output']
        self.input = master.children['input']

        self.char_width = Font(self.output_panel, self.output_panel.cget("font")).measure('0')
        self.line_length = self.calc_line_length(self.output_panel.cget("width"))
        italic_font = Font(self.output_panel, self.output_panel.cget("font"))
        italic_font.configure(slant='italic')
        self.output_panel.tag_configure("italic", font=italic_font)
        bold_font = Font(self.output_panel, self.output_panel.cget("font"))
        bold_font.configure(weight='bold')
        self.output_panel.tag_configure('bold', font=bold_font)
        self.output_panel.tag_configure("center", justify=tk.CENTER)
Exemplo n.º 37
0
 def __init__(self, master):
     BaseDiablog.__init__(self, master, "Preferences", exit_on_esc=True)
     self.startup_check = Config.config["startup_check"]
     self.general_label = ttk.Label(self.body,
                                    text="General")
     font = Font(self.general_label, self.general_label.cget("font"))
     font.configure(underline=True)
     self.general_label.configure(font=font)
     self.config_frame = ttk.Frame(self)
     self.startup_check_checkbtn = ttk.Checkbutton(self.config_frame,
                                                   text="Check for update at launch",
                                                   variable=PreferencesDialog.startup_check.raw_klass(self),
                                                   command=self._startup_check_clicked)
     self.buttons_frame = ttk.Frame(self)
     self.close_button = ttk.Button(self.buttons_frame,
                                    text="Close",
                                    command=self.destroy)
     options = dict(padx=5, pady=5)
     self.general_label.pack(side=LEFT, **options)
     self.config_frame.pack(fill=BOTH, expand=True, **options)
     self.startup_check_checkbtn.pack(side=LEFT, **options)
     self.buttons_frame.pack(side=BOTTOM, fill=BOTH, expand=True, **options)
     self.close_button.pack(side=RIGHT, expand=False)
Exemplo n.º 38
0
 def __init__(self, master):
     BaseDiablog.__init__(self, master, "Preferences", exit_on_esc=True)
     self.startup_check = Config.config["startup_check"]
     self.general_label = ttk.Label(self.body, text="General")
     font = Font(self.general_label, self.general_label.cget("font"))
     font.configure(underline=True)
     self.general_label.configure(font=font)
     self.config_frame = ttk.Frame(self)
     self.startup_check_checkbtn = ttk.Checkbutton(
         self.config_frame,
         text="Check for update at launch",
         variable=PreferencesDialog.startup_check.raw_klass(self),
         command=self._startup_check_clicked)
     self.buttons_frame = ttk.Frame(self)
     self.close_button = ttk.Button(self.buttons_frame,
                                    text="Close",
                                    command=self.destroy)
     options = dict(padx=5, pady=5)
     self.general_label.pack(side=LEFT, **options)
     self.config_frame.pack(fill=BOTH, expand=True, **options)
     self.startup_check_checkbtn.pack(side=LEFT, **options)
     self.buttons_frame.pack(side=BOTTOM, fill=BOTH, expand=True, **options)
     self.close_button.pack(side=RIGHT, expand=False)
Exemplo n.º 39
0
    def __init__(self):
        """Initialize widgets, methods."""

        tkinter.Tk.__init__(self)
        self.grid()

        fontoptions = families(self)
        font = Font(family="Verdana", size=10)

        menubar = tkinter.Menu(self)
        fileMenu = tkinter.Menu(menubar, tearoff=0)
        editMenu = tkinter.Menu(menubar, tearoff=0)
        fsubmenu = tkinter.Menu(editMenu, tearoff=0)
        ssubmenu = tkinter.Menu(editMenu, tearoff=0)

        # adds fonts to the font submenu and associates lambda functions
        for option in fontoptions:
            fsubmenu.add_command(label=option, command = lambda: font.configure(family=option))
        # adds values to the size submenu and associates lambda functions
        for value in range(1,31):
            ssubmenu.add_command(label=str(value), command = lambda: font.configure(size=value))

        # adds commands to the menus
        menubar.add_cascade(label="File",underline=0, menu=fileMenu)
        menubar.add_cascade(label="Edit",underline=0, menu=editMenu)
        fileMenu.add_command(label="New", underline=1,
                             command=self.new, accelerator="Ctrl+N")
        fileMenu.add_command(label="Open", command=self.open, accelerator="Ctrl+O")
        fileMenu.add_command(label="Save", command=self.save, accelerator="Ctrl+S")
        fileMenu.add_command(label="Exit", underline=1,
                             command=exit, accelerator="Ctrl+Q")
        editMenu.add_command(label="Copy", command=self.copy, accelerator="Ctrl+C")
        editMenu.add_command(label="Cut", command=self.cut, accelerator="Ctrl+X")
        editMenu.add_command(label="Paste", command=self.paste, accelerator="Ctrl+V")
        editMenu.add_cascade(label="Font", underline=0, menu=fsubmenu)
        editMenu.add_cascade(label="Size", underline=0, menu=ssubmenu)
        editMenu.add_command(label="Color", command=self.color)
        editMenu.add_command(label="Bold", command=self.bold, accelerator="Ctrl+B")
        editMenu.add_command(label="Italic", command=self.italic, accelerator="Ctrl+I")
        editMenu.add_command(label="Underline", command=self.underline, accelerator="Ctrl+U")
        editMenu.add_command(label="Overstrike", command=self.overstrike, accelerator="Ctrl+T")
        editMenu.add_command(label="Undo", command=self.undo, accelerator="Ctrl+Z")
        editMenu.add_command(label="Redo", command=self.redo, accelerator="Ctrl+Y")
        self.config(menu=menubar)

        """Accelerator bindings. The cut, copy, and paste functions are not
        bound to keyboard shortcuts because Windows already binds them, so if
        Tkinter bound them as well whenever you typed ctrl+v the text would be
        pasted twice."""
        self.bind_all("<Control-n>", self.new)
        self.bind_all("<Control-o>", self.open)
        self.bind_all("<Control-s>", self.save)
        self.bind_all("<Control-q>", self.exit)
        self.bind_all("<Control-b>", self.bold)
        self.bind_all("<Control-i>", self.italic)
        self.bind_all("<Control-u>", self.underline)
        self.bind_all("<Control-T>", self.overstrike)
        self.bind_all("<Control-z>", self.undo)
        self.bind_all("<Control-y>", self.redo)

        self.text = ScrolledText(self, state='normal', height=30, wrap='word', font = font, pady=2, padx=3, undo=True)
        self.text.grid(column=0, row=0, sticky='NSEW')

        # Frame configuration
        self.grid_columnconfigure(0, weight=1)
        self.resizable(True, True)
Exemplo n.º 40
0
class MainApplication(tk.Tk):
    """main application window

    Attributes:
        all_servers (list): returns list of all servers
        customFont (TYPE): defined two types of fonts for mac/win compatibility
        entry (entry field): enter number of the server that failed to render
        file_contents (list): the contents of the Backburner job file
        ip_address (txt): check if the render manager is available and fill it's ip address
        job_name (txt): Backburner job name
        L1 (UI label): label
        PRIORITY (txt): set priority for new Backburner job
        RENDER_MANAGER (txt): render manager name
        run_button (button): run program to create .bat-render file
        SCENE_LOOKUP (txt): path to the folder with .max files
        selected_server (txt): failed server name you have chosen
        server_frames_list (list): list of frames assigned to failed server to be re-rendered
        servers (list): list of servers in Backburner job
        text (txt): console text field
        the_csv_file (file): Backburner job exported file
        var (int): 1 - to call 'open result' function; 0 - to pass
        VERSION (txt): 3DsMax version
    """

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.geometry('+300+100')
        self.title('pyBurner')
        self.configure(bg=BGCOLOR)

        if os_name == 'Darwin':
            self.customFont = Font(family="Lucida Console", size=10)
            txt_area = [18, 53]
        elif os_name == 'Windows':
            txt_area = [18, 48]
            self.customFont = nametofont("TkDefaultFont")
            self.customFont.configure(size=9)
        # text area
        frame1 = tk.Frame(self)
        frame1.configure(background=BGCOLOR)
        frame1.grid(row=0, column=0, columnspan=2, sticky='w')

        scrollbar = tk.Scrollbar(frame1)
        self.text = MyTextSettings(
            frame1, height=txt_area[0], width=txt_area[1], yscrollcommand=scrollbar.set
        )
        self.text.pack(padx=(4, 0), side=tk.LEFT, expand=True)
        scrollbar.configure(command=self.text.yview)
        scrollbar.pack(side=tk.LEFT, fill=tk.Y, expand=False)

        # labels area
        l_frame = tk.Frame(self)
        l_frame.config(background=BGCOLOR)
        l_frame.grid(row=1, column=0, pady=5)
        self.L1 = MyLabel(l_frame, font=self.customFont)
        self.L1.pack()
        self.var = tk.IntVar()
        checkbutton1 = tk.Checkbutton(
            l_frame,
            font=self.customFont,
            background=BGCOLOR,
            activebackground=BGCOLOR,
            variable=self.var,
        )
        checkbutton1.pack(side=tk.LEFT)
        L2 = MyLabel(l_frame, bg="red", text="open result", font=self.customFont)
        L2.pack(side=tk.LEFT)

        # buttons area
        b_frame = tk.Frame(self)
        b_frame.config(bg=BGCOLOR)
        b_frame.grid(row=1, column=1, padx=(0, 20), sticky='e')
        submit_button = tk.Button(
            b_frame, text='submit', command=self.get_server_entry, font=self.customFont
        )
        submit_button.grid(row=1, column=3, padx=(0, 3), sticky='w')
        submit_button.configure(highlightbackground=BGCOLOR)
        self.bind('<Return>', self.get_server_entry)
        self.run_button = tk.Button(
            b_frame, text='run', command=self.run_app, font=self.customFont
        )
        self.run_button.configure(highlightbackground=BGCOLOR)
        self.run_button.grid(row=1, column=4, padx=(0, 3))
        self.bind('<Control-r>', self.run_app)
        reset_button = tk.Button(
            b_frame, text='reset', command=self.cleanup, font=self.customFont
        )
        reset_button.config(highlightbackground=BGCOLOR)
        reset_button.grid(row=1, column=5, sticky='we')
        self.showall_button = tk.Button(
            b_frame, text='all jobs', command=self.show_all, state=tk.DISABLED
        )
        self.showall_button.configure(highlightbackground=BGCOLOR, font=self.customFont)
        self.showall_button.grid(row=2, column=3, sticky='w')
        close_button = tk.Button(
            b_frame, text='close', command=self.quit_app, font=self.customFont
        )
        close_button.configure(highlightbackground=BGCOLOR)
        close_button.grid(row=2, column=4, columnspan=2, sticky='we')
        self.entry = tk.Entry(b_frame, width=6, font=self.customFont)
        self.entry.grid(row=1, column=2, sticky='w', padx=(0, 6))
        self.entry.configure(
            background="#535353", foreground=FGCOLOR, highlightthickness=0
        )

        # file menu
        menubar = tk.Menu(self)
        filemenu = tk.Menu(menubar, tearoff=0)
        self.config(menu=menubar)
        filemenu.add_command(label='Open', command=self.csv_open, accelerator="Ctrl+O")
        filemenu.add_command(label='Preferences', command=self.open_preferences)
        filemenu.add_separator()
        filemenu.add_command(label='Exit', command=self.quit_app, accelerator='Ctrl+Q')
        self.bind("<Control-o>", self.csv_open)
        self.bind("<Control-q>", self.quit_app)
        menubar.add_cascade(label='File', menu=filemenu)
        self.text.clear_help()
        self.load_defaults()

    def cleanup(self):
        self.text.clear_help()
        self.load_defaults()

    def load_defaults(self):
        self.var.set(1)
        self.L1.config(text='press CTRL+O to open file')
        self.entry.delete("0", tk.END)
        self.job_name = None
        self.selected_server = None
        self.file_contents = []
        self.servers = []
        self.all_servers = []
        self.the_csv_file = None
        self.read_config()
        self.showall_button.config(state=tk.DISABLED)

    def read_config(self):
        try:
            self.SCENE_LOOKUP = config_reader('settings')['path']
            self.PRIORITY = config_reader('settings')['priority']
            self.RENDER_MANAGER = config_reader('settings')['manager']
            self.VERSION = config_reader('settings')['version']
        except (configparser.NoSectionError, KeyError):
            sample_config = r'''[settings]
priority = 100
path = ~\Documents
version = 2016
manager = localhost'''
            with open('config.ini', 'w') as cfgfile:
                cfgfile.write(sample_config)

    def show_all(self):
        if self.the_csv_file:
            ShowAllWindow('all frames', file=self.the_csv_file)
        else:
            self.text.set_text('open file first')

    @staticmethod
    def open_preferences():
        OpenPrefs('Preferences')

    def csv_open(self, *args):
        self.text.clear_all()
        self.the_csv_file = filedialog.askopenfilename(
            initialdir='{}/Desktop'.format(os.path.expanduser('~')),
            filetypes=(
                ('Text File', '*.txt'), ('CSV file', '*.csv'), ('All Files', '*.*')
            ),
            title='Choose a file',
        )
        if self.the_csv_file:
            try:
                self.job_name = get_job_name(self.the_csv_file)
                if self.job_name is None:
                    self.text.set_text('Job name is empty, check file')
                    return

                else:
                    self.showall_button.config(state=tk.NORMAL)
            except (csv.Error, UnicodeDecodeError):
                self.text.set_text('This file is not valid, try another!')
                return

            self.all_servers = servers_sorted(self.the_csv_file)
            self.text.set_text('Job name: {}\n'.format(self.job_name))
            self.text.set_text(
                "Found {} servers in file:".format(len(self.all_servers))
            )
            for num, serv in enumerate(self.all_servers):
                self.text.set_text('{}) {}'.format(num + 1, serv))
            self.text.set_text('\nenter server number and submit (hit ENTER)')
            self.L1.config(
                text='Enter server number (1-{})'.format(len(self.all_servers))
            )
            self.entry.delete("0", tk.END)
            self.entry.focus()
        else:
            self.text.clear_help()

    def get_server_entry(self, event=None):
        try:
            server_num = int(self.entry.get().strip())
            if server_num > 0:
                self.server_frames_list = list(
                    return_frames(
                        self.the_csv_file, self.all_servers[int(server_num) - 1]
                    )
                )
                self.selected_server = self.all_servers[int(server_num) - 1]
                self.text.set_text('\nyou\'ve selected server #{}'.format(server_num))
                self.text.set_text("'{}'".format(self.selected_server))
                self.text.set_text(
                    'Now press RUN button (or hit "Space")\nand choose .max file'
                )
                self.run_button.focus()
            else:
                self.text.set_text('enter number greater than zero')
        except (ValueError, IndexError):
            self.text.set_text('Enter correct number!')

    def choose_max_file(self):
        open_maxfile = filedialog.askopenfilename(
            initialdir=self.SCENE_LOOKUP,
            filetypes=(('3dMax file', '*.max'), ('All Files', '*.*')),
            title='Choose MAX file',
        )
        if open_maxfile:
            return open_maxfile

        else:
            self.text.set_text('\nClick "run" and choose .max file!')
            return 0

    def run_app(self, event=None):
        if self.job_name and self.selected_server:
            self.read_config()
            max_file = self.choose_max_file()
            if max_file:
                self.text.set_text('\nThese frames will be rendered again:')
                self.text.set_text(", ".join(self.server_frames_list))
                self.text.set_text('\r')
                self.ip_address = test_network(
                    self.RENDER_MANAGER
                )  # test network path again just in case
                if self.ip_address:
                    norm_path = os.path.normpath(max_file)
                    self.make_bat(norm_path)
                else:
                    self.text.set_text(
                        '\nCheck server settings in Preferences and run again'
                    )
        elif not self.job_name:
            self.text.set_text("You should select jobs file first")
        elif not self.selected_server:
            self.text.set_text("Enter server number and submit!")

    @staticmethod
    def open_result(folder):
        # show the result folder in Windows Explorer or macOS Finder
        if os_name == 'Darwin':
            subprocess.Popen(['open', folder])
        elif os_name == 'Windows':
            subprocess.Popen('explorer /open, {}'.format(folder))
        else:
            pass

    def make_bat(self, max_path):
        max_version = '\"C:\\Program Files\\Autodesk\\3ds Max {}\\3dsmaxcmd.exe\"'.format(
            self.VERSION
        )
        quoted_max_file = add_quotes(max_path)
        max_folder, max_file = os.path.split(max_path)
        filename, _ = os.path.splitext(max_file)
        bat_file = os.path.join(
            max_folder, '{}_{}.bat'.format(filename, self.selected_server)
        )
        truncate_file(bat_file)
        with open(bat_file, 'a') as bat:
            print(max_version, quoted_max_file, file=bat, end=' ')
            print(
                '-frames:{}'.format(",".join(self.server_frames_list)),
                file=bat,
                end=' ',
            )
            # print(",".join(self.server_frames_list), file=bat, end=' ')
            print('-submit:', self.ip_address, file=bat, end=' ')
            print(
                '-jobname: {}_{}'.format(self.job_name, self.selected_server),
                file=bat,
                end=' ',
            )
            print('-priority:{}'.format(self.PRIORITY), file=bat)
        if self.var.get() == 1:
            self.text.set_text('Opening folder...\n')
            self.open_result(max_folder)
            self.var.set(0)  # uncheck button to prevent multiple windows when re-run
        else:
            pass
        self.text.set_text(
            'Done!\nCheck "{}" at {}'.format(os.path.split(bat_file)[1], max_folder)
        )
        self.entry.focus()

    @staticmethod
    def quit_app(event=None):
        sys.exit(0)
Exemplo n.º 41
0
class DrtGlueDemo(object):
    def __init__(self, examples):
        # Set up the main window.
        self._top = Tk()
        self._top.title("DRT Glue Demo")

        # Set up key bindings.
        self._init_bindings()

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

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

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

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

        self._init_glue()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        self._populate_readingListbox()

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

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

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

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

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

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

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

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

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

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

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

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

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

        parent.config(menu=menubar)

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

    def _redraw(self):
        canvas = self._canvas

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

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

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

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

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

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

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

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

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

        else:
            self._select_previous_example()

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

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

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

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

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

        else:
            self._select_next_example()

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

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

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

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

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

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

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

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

        self._drs = None
        self._redraw()

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

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

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

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

            self._populate_readingListbox()

            self._exampleList.selection_set(index)

            self._drs = None
            self._redraw()

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

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

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

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

            self._redraw()