Example #1
0
    def _init_menubar(self):
        menubar = Menu(self._top)

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

        zoommenu = Menu(menubar, tearoff=0)
        zoommenu.add_radiobutton(label='Tiny', variable=self._size,
                                 underline=0, value=10, command=self.resize)
        zoommenu.add_radiobutton(label='Small', variable=self._size,
                                 underline=0, value=12, command=self.resize)
        zoommenu.add_radiobutton(label='Medium', variable=self._size,
                                 underline=0, value=14, command=self.resize)
        zoommenu.add_radiobutton(label='Large', variable=self._size,
                                 underline=0, value=28, command=self.resize)
        zoommenu.add_radiobutton(label='Huge', variable=self._size,
                                 underline=0, value=50, command=self.resize)
        menubar.add_cascade(label='Zoom', underline=0, menu=zoommenu)

        self._top.config(menu=menubar)
Example #2
0
    def creatMenu(self):
        #主菜单
        menubar = Menu(self)
        #子菜单
        menufile = Menu(menubar)
        for item in ["新建", "打开", "保存", "另存为"]:
            menufile.add_radiobutton(label=item)
        menuedit = Menu(menubar)
        for item in ["复制", "黏贴", "剪切"]:
            menuedit.add_checkbutton(label=item)
        #子菜单与主菜单关联
        for name, submenu in zip(["文件", "编辑"], [menufile, menuedit]):
            menubar.add_cascade(label=name, menu=submenu)
        #最关键的一步,主菜单与app关联
        self.master.config(menu=menubar)
        #右键菜单
        menu = Menu(self.master)
        for i in ('One', 'Two', 'Three'):
            menu.add_command(label=i)
        #插入分割线
        menu.add_separator()

        for i in ('1', '2', '3'):
            menu.add_command(label=i)
        #绑定鼠标右键呼出
        if (self.master.tk.call('tk', 'windowingsystem') == 'aqua'):
            self.master.bind('<2>', lambda e: menu.post(e.x_root, e.y_root))
            self.master.bind('<Control-1>',
                             lambda e: menu.post(e.x_root, e.y_root))
        else:
            self.master.bind('<3>', lambda e: menu.post(e.x_root, e.y_root))
    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)
Example #4
0
File: tree.py Project: DrDub/nltk
    def _init_menubar(self):
        menubar = Menu(self._top)

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

        zoommenu = Menu(menubar, tearoff=0)
        zoommenu.add_radiobutton(label='Tiny', variable=self._size,
                                 underline=0, value=10, command=self.resize)
        zoommenu.add_radiobutton(label='Small', variable=self._size,
                                 underline=0, value=12, command=self.resize)
        zoommenu.add_radiobutton(label='Medium', variable=self._size,
                                 underline=0, value=14, command=self.resize)
        zoommenu.add_radiobutton(label='Large', variable=self._size,
                                 underline=0, value=28, command=self.resize)
        zoommenu.add_radiobutton(label='Huge', variable=self._size,
                                 underline=0, value=50, command=self.resize)
        menubar.add_cascade(label='Zoom', underline=0, menu=zoommenu)

        self._top.config(menu=menubar)
Example #5
0
    def createMenu(self):
        self.status_top = BooleanVar()
        self.status_top.set(True)

        self.language_choice = StringVar()
        self.language_choice.set("zh-cn")

        menubar = Menu(self)
        language = Menu(menubar, tearoff=0)
        option = Menu(menubar, tearoff=0)
        menubar.add_cascade(label="Language", menu=language)
        menubar.add_cascade(label="Option", menu=option)
        for label, value in self.all_language:
            language.add_radiobutton(
                label=label,
                variable=self.language_choice,
                value=value
            )
        option.add_checkbutton(
            label="Always on Top",
            variable=self.status_top,
            command=lambda : self.attributes("-topmost", self.status_top.get())
        )
        option.add_command(label="Exit", command=self.quit)
        self.config(menu=menubar)
Example #6
0
 def generate_debug_modes_menu(self, window):
     debugMenu = Menu(window, tearoff=0)
     radio_buttons_vec = []
     for index in range(0, len(DebugModes)):
         debugMenu.add_radiobutton(label=DebugModes[index],
                                   value=index,
                                   variable=self.selected_debug_mode,
                                   command=self.save_selection)
     return debugMenu
Example #7
0
    def _init_menubar(self):
        menubar = Menu(self._top)

        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(
            label="Print to Postscript",
            underline=0,
            command=self._cframe.print_to_file,
            accelerator="Ctrl-p",
        )
        filemenu.add_command(label="Exit",
                             underline=1,
                             command=self.destroy,
                             accelerator="Ctrl-x")
        menubar.add_cascade(label="File", underline=0, menu=filemenu)

        zoommenu = Menu(menubar, tearoff=0)
        zoommenu.add_radiobutton(
            label="Tiny",
            variable=self._size,
            underline=0,
            value=10,
            command=self.resize,
        )
        zoommenu.add_radiobutton(
            label="Small",
            variable=self._size,
            underline=0,
            value=12,
            command=self.resize,
        )
        zoommenu.add_radiobutton(
            label="Medium",
            variable=self._size,
            underline=0,
            value=14,
            command=self.resize,
        )
        zoommenu.add_radiobutton(
            label="Large",
            variable=self._size,
            underline=0,
            value=28,
            command=self.resize,
        )
        zoommenu.add_radiobutton(
            label="Huge",
            variable=self._size,
            underline=0,
            value=50,
            command=self.resize,
        )
        menubar.add_cascade(label="Zoom", underline=0, menu=zoommenu)

        self._top.config(menu=menubar)
Example #8
0
 def init_window(self):
     root = Tk()
     root.iconbitmap('favicon.ico')
     root.title('')
     menubar = Menu(root)
     root.config(menu=menubar)
     menu = Menu(menubar, tearoff=0)
     menu.add_radiobutton(label="4X4", command=lambda: self.resize(4))
     menu.add_radiobutton(label="5X5", command=lambda: self.resize(5))
     menu.add_radiobutton(label="6X6", command=lambda: self.resize(6))
     menu.add_command(label="Quitter", command=root.destroy)
     menubar.add_cascade(label="Réglages", menu=menu)
     return root
Example #9
0
    def build_gui(self):
        self.root = Tk()

        main_menu = Menu(self.root)
        game_menu = Menu(main_menu, tearoff=0)
        game_menu.add_command(label='New Game',
                              command=self.menu_change_difficulty)
        game_menu.add_command(label='High Scores',
                              command=self.show_high_scores)
        game_menu.add_separator()
        game_menu.add_command(label='Exit', command=self.root.quit)
        main_menu.add_cascade(label='Game', menu=game_menu)

        self.difficulty_idx = IntVar()
        difficulty_menu = Menu(main_menu, tearoff=0)
        for idx, item in enumerate(settings.storage['difficulty']):
            #difficulty_menu.add_radiobutton(label=item['name'], variable=self.current_difficulty, value=item, command=self.not_yet_implemented)
            difficulty_menu.add_radiobutton(
                label=item['name'],
                variable=self.difficulty_idx,
                value=idx,
                indicatoron=1,
                command=self.menu_change_difficulty)
            if item == self.current_difficulty:
                self.difficulty_idx.set(idx)
                print(f'Set Difficulty Index = {idx}')

        main_menu.add_cascade(label='Difficulty', menu=difficulty_menu)

        help_menu = Menu(main_menu, tearoff=0)
        help_menu.add_command(label='Index', command=self.show_help)
        help_menu.add_separator()
        help_menu.add_command(label='About', command=self.show_about)
        main_menu.add_cascade(label='Help', menu=help_menu)

        self.root.config(menu=main_menu)
        self.root.title('Minesweeper')

        self.init_icons()
        self.grid_frame = Frame()
        self.grid_frame.pack()

        self.change_difficulty()

        file_path = os.path.dirname(os.path.realpath(__file__))
        icon = PhotoImage(file=os.path.join(file_path, '../res/logo.gif'))
        self.root.icon = icon  # don't garbage collect me please.
        #self.icons['logo'] = icon
        self.root.tk.call('wm', 'iconphoto', self.root._w, self.icons['logo'])
Example #10
0
    def _init_menu(self):
        toplevel = self.winfo_toplevel()
        self._menu = Menu(toplevel)
        toplevel['menu'] = self._menu

        view = Menu(self._menu, tearoff=0)
        self._menu.add_cascade(label="View", menu=view)

        graph_view = Menu(view, tearoff=0)
        view.add_cascade(label="View graphs", menu=graph_view)

        graph_view.add_radiobutton(variable="graphframeview",
                                   label="Only one",
                                   value="onlyone")
        #        graph_view.add_radiobutton(label="In a row", value="row",
        #            variable=graph_view_var)
        graph_view.add_radiobutton(variable="graphframeview",
                                   label="In separate window",
                                   value="window")
Example #11
0
 def creatMenu(self):
     #主菜单
     menubar = Menu(self.master)
     #子菜单
     menufile = Menu(menubar)
     #多选菜单
     menuradio = Menu(menubar)
     #单选菜单
     menucheck = Menu(menubar)
     for item in ["1", "2", "3", "4"]:
         menufile.add_command(label=item)
     menubar.add_cascade(label="子菜单", menu=menufile)
     for i in ["a", "b", "c"]:
         menuradio.add_radiobutton(label=i)
     menubar.add_cascade(label="多选菜单", menu=menuradio)
     for i in ["a1", "b2", "c3"]:
         menucheck.add_checkbutton(label=i)
     menubar.add_cascade(label="单选菜单", menu=menucheck)
     return menubar
    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)
Example #13
0
    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)
Example #14
0
    def _init_menubar(self):
        self._result_size = IntVar(self.top)
        menubar = Menu(self.top)

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

        editmenu = Menu(menubar, tearoff=0)
        rescntmenu = Menu(editmenu, tearoff=0)
        rescntmenu.add_radiobutton(label='20',
                                   variable=self._result_size,
                                   underline=0,
                                   value=20,
                                   command=self.set_result_size)
        rescntmenu.add_radiobutton(label='50',
                                   variable=self._result_size,
                                   underline=0,
                                   value=50,
                                   command=self.set_result_size)
        rescntmenu.add_radiobutton(label='100',
                                   variable=self._result_size,
                                   underline=0,
                                   value=100,
                                   command=self.set_result_size)
        rescntmenu.invoke(1)
        editmenu.add_cascade(label='Result Count',
                             underline=0,
                             menu=rescntmenu)

        menubar.add_cascade(label='Edit', underline=0, menu=editmenu)
        self.top.config(menu=menubar)
Example #15
0
    def _init_menu(self):
        """Init menu bar content.
        """
        toplevel = self.winfo_toplevel()
        if toplevel['menu']:
            self._menu = self.nametowidget(name=toplevel['menu'])
        else:
            self._menu = Menu(toplevel)
            toplevel['menu'] = self._menu

        graph_options = Menu(self._menu, tearoff=0)
        self._menu.add_cascade(label="Graph", menu=graph_options)
        self._menu_index = self._menu.index("end")

        vertex_label_position_menu = Menu(graph_options, tearoff=0)
        graph_options.add_cascade(label="Label position", menu=vertex_label_position_menu)

        menu_var = self.winfo_name() + ".vertexlabelposition"
        vertex_label_position_menu.add_radiobutton(variable=menu_var, label="Auto", value="auto")
        vertex_label_position_menu.add_radiobutton(variable=menu_var, label="Center", value="center")

        graph_options.add_command(label="Save graph...", command=self.call_graph_save_dialog)

        self.bind("<Destroy>", self.__destroy_menu)
Example #16
0
def init(root,**kwargs):
    # Menu bar
    menu = Menu(root)

    # cypher type items
    cyphermenu = Menu(menu, tearoff=0)
    cyphermenu.add_radiobutton(label="Concealment", command=kwargs['concealment_cyphers'])
    cyphermenu.add_radiobutton(label="Transposition", command=kwargs['transposition_cyphers'])
    cyphermenu.add_radiobutton(label="Substitution", command=kwargs['substitution_cyphers'])
    menu.add_cascade(label="Cyphers", menu=cyphermenu)

    # mode menu items
    modemenu = Menu(menu, tearoff=0)
    modemenu.add_radiobutton(label="Decryption", command=kwargs['decryption_mode']) # make default checked
    modemenu.add_radiobutton(label="Encryption", command=kwargs['encryption_mode'])
    menu.add_cascade(label="Mode", menu=modemenu)
    
    return menu
Example #17
0
    def _create_menu(self):
        self.menu = Menu(self, tearoff=False)
        self.menu_sort = Menu(self.menu, tearoff=False)

        menu_pos = Menu(self.menu, tearoff=False)
        menu_pos.add_radiobutton(label=_('Normal'),
                                 value='normal',
                                 variable=self._position,
                                 command=self._change_position)
        menu_pos.add_radiobutton(label=_('Above'),
                                 value='above',
                                 variable=self._position,
                                 command=self._change_position)
        menu_pos.add_radiobutton(label=_('Below'),
                                 value='below',
                                 variable=self._position,
                                 command=self._change_position)
        self.menu.add_cascade(label=_('Sort'), menu=self.menu_sort)
        self.menu.add_cascade(label=_('Position'), menu=menu_pos)
        self.menu.add_command(label=_('Hide'), command=self.withdraw)
        self.menu.add_command(label=_('Open all'), command=self.open_all)
        self.menu.add_command(label=_('Close all'), command=self.close_all)
Example #18
0
    def _init_menubar(self):
        self._result_size = IntVar(self.top)
        menubar = Menu(self.top)

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

        editmenu = Menu(menubar, tearoff=0)
        rescntmenu = Menu(editmenu, tearoff=0)
        rescntmenu.add_radiobutton(label='20', variable=self._result_size,
                     underline=0, value=20, command=self.set_result_size)
        rescntmenu.add_radiobutton(label='50', variable=self._result_size,
                     underline=0, value=50, command=self.set_result_size)
        rescntmenu.add_radiobutton(label='100', variable=self._result_size,
                     underline=0, value=100, command=self.set_result_size)
        rescntmenu.invoke(1)
        editmenu.add_cascade(label='Result Count', underline=0, menu=rescntmenu)

        menubar.add_cascade(label='Edit', underline=0, menu=editmenu)
        self.top.config(menu=menubar)
Example #19
0
    def configure_menu(self):
        menu_bar = Menu(self)
        self.configure(menu=menu_bar)

        # controls command
        menu_bar.add_command(label='controls', command=self.popup_controls)

        # speed menu
        speed_menu = Menu(menu_bar)
        menu_bar.add_cascade(label='speed', menu=speed_menu)
        self.speed_index_int_var = IntVar()
        for speed_string, scalar in data.FREQ_SCALAR_KEYS.items():
            speed_menu.add_radiobutton(label=speed_string,
                                       value=scalar,
                                       variable=self.speed_index_int_var)
        speed_menu.invoke(speed_menu.index('1.00x'))

        # shapes menu
        shapes_menu = Menu(menu_bar)
        menu_bar.add_cascade(label='shapes', menu=shapes_menu)
        self.shapes_string_var = StringVar()
        self.shapes_string_var.set('default')
        for shape_set in data.SHAPES[self.shape_size].keys():
            shapes_menu.add_radiobutton(label=shape_set,
                                        value=shape_set,
                                        variable=self.shapes_string_var)
        shapes_menu.invoke(shapes_menu.index('default'))

        # color menu
        colors_menu = Menu(menu_bar)
        menu_bar.add_cascade(label='colors', menu=colors_menu)
        self.cs_string_var = StringVar()
        for scheme in data.COLOR_SCHEMES[self.shape_size].keys():
            colors_menu.add_radiobutton(label=scheme,
                                        value=scheme,
                                        variable=self.cs_string_var)
        colors_menu.invoke(colors_menu.index('default'))
Example #20
0
    def _init_menubar(self, parent):
        menubar = Menu(parent)

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

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

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

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

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


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

        parent.config(menu=menubar)
Example #21
0
color_schemes = {
    "Default": "#000000.#FFFFFF",
    "Greygarious": "#83406A.#D1D4D1",
    "Aquamarine": "#5B8340.#D1E7E0",
    "Bold Beige": "#4B4620.#FFF0E1",
    "Cobalt Blue": "#ffffBB.#3333aa",
    "Olive Green": "#D1E7E0.#5B8340",
    "Night Mode": "#FFFFFF.#000000",
}

theme_choice = StringVar()
theme_choice.set("Default")
for k in sorted(color_schemes):
    themes_menu.add_radiobutton(label=k,
                                variable=theme_choice,
                                command=change_theme)
menu_bar.add_cascade(label="View", menu=view_menu)

about_menu = Menu(menu_bar, tearoff=0)
about_menu.add_command(label="About", command=display_about_messagebox)
about_menu.add_command(label="Help", command=display_help_messagebox)
menu_bar.add_cascade(label="About", menu=about_menu)
root.config(menu=menu_bar)

shortcut_bar = Frame(root, height=25)
shortcut_bar.pack(expand="no", fill="x")

icons = (
    "new_file",
    "open_file",
Example #22
0
class MainApp():
    def __init__(self):
        self.File_name = None
        self.Programe_Name = "CHE-Editor"
        self.WDG = Tk()
        self.WDG.title(self.Programe_Name)
        self.WDG.iconbitmap("icons/icon_editor.ico")
        self.WDG.geometry("860x620")
        self.WDG.maxsize(width=1340, height=700)
        self.WDG.minsize(width=860, height=620)
        self.Main_UI()

    def Main_UI(self):
        self.MenuBar = Menu(self.WDG)

        #1      #MenuBar
        #File_menu
        self.File_menu = Menu(self.MenuBar, tearoff=0, title="File")
        self.MenuBar.add_cascade(label="File", menu=self.File_menu)
        #Edit_menu
        self.Edit_menu = Menu(self.MenuBar, tearoff=0, title="Edit")
        self.MenuBar.add_cascade(label="Edit", menu=self.Edit_menu)
        #View_menu
        self.View_menu = Menu(self.MenuBar, tearoff=0, title="View")
        self.MenuBar.add_cascade(label="View", menu=self.View_menu)
        #Theme_menu in View
        self.Theme_menu = Menu(self.View_menu, tearoff=0, title="Theme")
        self.View_menu.add_cascade(label="Theme", menu=self.Theme_menu)
        #Option_menu
        self.Options_menu = Menu(self.MenuBar, tearoff=0, title="Options")
        self.MenuBar.add_cascade(label="Options", menu=self.Options_menu)
        #Help_menu
        self.Help_menu = Menu(self.MenuBar, tearoff=0, title="Help")
        self.MenuBar.add_cascade(label="Help", menu=self.Help_menu)

        #2      #Icons Variables
        #Edit_Menu Icons
        Undo = PhotoImage(file="icons/Undo.gif")
        Redo = PhotoImage(file="icons/redo.gif")
        Paste = PhotoImage(file="icons/paste.gif")
        Copy = PhotoImage(file="icons/copy.gif")
        Cut = PhotoImage(file="icons/cut.gif")
        #Help_Menu_Icons
        Help = PhotoImage(file="icons/help.gif")
        About = PhotoImage(file="icons/about.gif")
        #File_Menu_Icons
        New = PhotoImage(file="icons/new.gif")
        Open = PhotoImage(file="icons/open.gif")
        Save = PhotoImage(file="icons/save.gif")
        Save_As = PhotoImage(file="icons/save_as.gif")
        Exit = PhotoImage(file="icons/exit.gif")

        #Appear menubar in app
        self.WDG.config(menu=self.MenuBar)
        #self.WDG.config(menu=self.IconBar)

        #3      #Set commands in menus
        #File_Menu
        self.File_menu.add_command(label="New",
                                   accelerator="Ctrl+N",
                                   compound="left",
                                   underline=0,
                                   command=self.New)
        self.File_menu.add_command(label="Open",
                                   accelerator="Ctrl+O",
                                   compound="left",
                                   underline=0,
                                   command=self.Open)
        self.File_menu.add_command(label="Save",
                                   accelerator="Ctrl+S",
                                   compound="left",
                                   underline=0,
                                   command=self.Save)
        self.File_menu.add_command(label="Save as",
                                   accelerator="Shift+Ctrl+S",
                                   compound="left",
                                   underline=0,
                                   command=self.Save_As)
        self.File_menu.add_separator()
        self.File_menu.add_command(label="Exit",
                                   accelerator="F4",
                                   compound="left",
                                   underline=0,
                                   command=self.Exit)
        #Edit_Menu
        self.Edit_menu.add_command(label="Undo",
                                   accelerator="Ctrl+Z",
                                   compound="left",
                                   underline=0,
                                   command=self.Undo)
        self.Edit_menu.add_command(label="Redo",
                                   accelerator='Ctrl+Y',
                                   compound='left',
                                   underline=0,
                                   command=self.Redo)
        self.Edit_menu.add_command(label="Select all",
                                   accelerator='Ctrl+A',
                                   compound='left',
                                   underline=0,
                                   command=self.Select)
        self.Edit_menu.add_command(label="Cut",
                                   accelerator='Ctrl+X',
                                   compound='left',
                                   underline=7,
                                   command=self.Cut)
        self.Edit_menu.add_command(label="Copy",
                                   accelerator='Ctrl+C',
                                   compound='left',
                                   underline=0,
                                   command=self.Copy)
        self.Edit_menu.add_command(label="Paste",
                                   accelerator='Ctrl+V',
                                   compound='left',
                                   underline=0,
                                   command=self.Paste)
        self.Edit_menu.add_command(label="Search",
                                   accelerator='Ctrl+F',
                                   compound='left',
                                   underline=0,
                                   command=self.Search)
        #Help_Menu
        self.Help_menu.add_command(label="Help",
                                   accelerator="F1",
                                   compound="left",
                                   underline=0,
                                   command=self.Help)
        self.Help_menu.add_command(label="About",
                                   compound="left",
                                   underline=0,
                                   command=self.About)
        #View_Menu
        self.Show_line_number = IntVar()
        self.Show_line_number.set(1)
        self.theme_name = StringVar()
        self.View_menu.add_checkbutton(label="Show Line Number",
                                       variable=self.Show_line_number)
        self.Highlightline = BooleanVar()
        self.View_menu.add_checkbutton(label='Highlight Current Line',
                                       onvalue=1,
                                       offvalue=0,
                                       variable=self.Highlightline,
                                       command=self.Toggle_highlight)
        self.cursorcoord = BooleanVar()
        self.View_menu.add_checkbutton(label='Show Cursor Location',
                                       variable=self.cursorcoord,
                                       command=self.Show_cursor_coord)
        self.Theme_menu.add_radiobutton(label="Default",
                                        variable=self.theme_name)

        #4      #add Shortcut_Bar & Row_Number_Bar
        #Shortcut_Bar
        self.Shortcut_Bar = Frame(self.WDG, height=25)
        self.Shortcut_Bar.pack(expand='no', fill='x')
        Icons = ['New', 'Open', 'Save', 'Copy', 'Cut', 'Paste', 'Undo', 'Redo']
        for i, icon in enumerate(Icons):
            Tool_icon = PhotoImage(file='icons/{}.gif'.format(icon))
            #c_var = 'self.{}'.format(icon)
            cmd = eval('self.{}'.format(icon))
            self.Tool_bar_btn = Button(self.Shortcut_Bar,
                                       image=Tool_icon,
                                       command=cmd)
            self.Tool_bar_btn.image = Tool_icon
            self.Tool_bar_btn.pack(side='left')
        #Row_Number_Bar
        self.Row_Number_Bar = Text(self.WDG,
                                   width=3,
                                   padx=3,
                                   takefocus=0,
                                   border=0,
                                   background='khaki',
                                   state='disabled',
                                   wrap='none')
        self.Row_Number_Bar.pack(side='left', fill='y')

        #5      #add Content_Text
        self.Content_Text = Text(self.WDG, wrap='word', undo=1)
        self.Content_Text.pack(expand='yes', fill='both')
        self.Content_Text.tag_configure('active_line', background='ivory2')
        self.Scroll_Bar = Scrollbar(self.Content_Text)
        self.Content_Text.configure(yscrollcommand=self.Scroll_Bar.set)
        self.Scroll_Bar.config(command=self.Content_Text.yview)
        self.Scroll_Bar.pack(side='right', fill='y')

        #6      #add_Cursor_Coord_Bar
        self.Cursor_Coord_Bar = Label(self.Content_Text,
                                      text='Row: 1 | Column: 1')
        self.Cursor_Coord_Bar.pack(fill=None,
                                   expand='no',
                                   side='right',
                                   anchor='se')

        #7      #Binding
        self.Content_Text.bind("<Control-o>", self.Open)
        self.Content_Text.bind("<Control-O>", self.Open)
        self.Content_Text.bind("<Control-s>", self.Save)
        self.Content_Text.bind("<Control-S>", self.Save)
        self.Content_Text.bind("<Shift-Control-KeyPress-s>", self.Save_As)
        self.Content_Text.bind("<Shift-Control-KeyPress-S>", self.Save_As)
        self.Content_Text.bind("<Control-n>", self.New)
        self.Content_Text.bind("<Control-N>", self.New)
        self.Content_Text.bind("<Control-z>", self.Undo)
        self.Content_Text.bind("<Control-Z>", self.Undo)
        self.Content_Text.bind("<Control-y>", self.Redo)
        self.Content_Text.bind("<Control-Y>", self.Redo)
        self.Content_Text.bind("<Control-x>", self.Cut)
        self.Content_Text.bind("<Control-X>", self.Cut)
        self.Content_Text.bind("<Control-a>", self.Select)
        self.Content_Text.bind("<Control-A>", self.Select)
        self.Content_Text.bind("<Control-c>", self.Copy)
        self.Content_Text.bind("<Control-C>", self.Copy)
        self.Content_Text.bind("<Control-v>", self.Paste)
        self.Content_Text.bind("<Control-V>", self.Paste)
        self.Content_Text.bind("<Control-f>", self.Search)
        self.Content_Text.bind("<Control-F>", self.Search)
        self.Content_Text.bind("<Any-KeyPress>", self.Content_changed)
        self.WDG.bind_all("<KeyPress-F1>", self.Help)
        self.WDG.bind_all("<KeyPress-F4>", self.Exit)


#8  #Built In Finctions
#File_Menu_Functions

    def New(self, event=None):
        self.Content_Text.delete(1., 'end')
        self.WDG.title('{} - {}'.format('Untitled', self.Programe_Name))

    ##
    def Open(self, event=None):
        self.Open_file_name = filedialog.askopenfilename(
            defaultextension=".txt",
            filetypes=[("All Files", "*.*"), ("Text Documents", "*.txt")])
        if self.Open_file_name:
            self.File_name = self.Open_file_name
            self.WDG.title("{} - {}".format(os.path.basename(self.File_name),
                                            self.Programe_Name))
            self.Content_Text.delete(1.0, 'end')
            with open(self.File_name) as _File:
                self.Content_Text.insert(1.0, _File.read())

    ##
    def Save(self, event=None):
        if not self.File_name:
            self.Save_As()
        else:
            self.Write_to_file(self.File_name)
        return "break"

    ##
    def Save_As(self, event=None):
        self.Save_file_name = filedialog.asksaveasfilename(
            defaultextension='.txt',
            filetypes=[('All Files', '*.*'), ('Text Documents', '*.txt')])
        if self.Save_file_name:
            self.File_name = self.Save_file_name
            self.Write_to_file(self.File_name)
            self.WDG.title('{} - {}'.format(os.path.basename(self.File_name),
                                            self.Programe_Name))
        return "break"

    ##
    def Write_to_file(self, filename):
        try:
            self.content = self.Content_Text.get(1.0, 'end')
            with open(self.File_name, 'w') as the_file:
                the_file.write(self.content)
        except IOError as er:
            print(er)

    ##
    def Exit(self, event=None):
        self.msg_exit = messagebox.askyesno('Exit Editor',
                                            'Do you want to exit?')
        if self.msg_exit:
            self.WDG.destroy()

    #Edit_Menu_Functions
    ##
    def Select(self, event=None):
        self.Content_Text.tag_add("sel", 1.0, "end")
        print("Done1")
        return "breake"

    ##
    def Cut(self, event=None):
        self.Content_Text.event_generate("<<Cut>>")
        return "breake"

    ##
    def Copy(self, event=None):
        self.Content_Text.event_generate("<<Copy>>")
        return "breake"

    ##
    def Paste(self, event=None):
        self.Content_Text.event_generate("<<Paste>>")
        return "breake"

    ##
    def Undo(self, event=None):
        self.Content_Text.event_generate("<<Undo>>")
        return "breake"

    ##
    def Redo(self, event=None):
        self.Content_Text.event_generate("<<Redo>>")
        return "breake"

    ##
    def Search(self, event=None):
        self.Search_Window = Toplevel(self.WDG)
        self.Search_Window.title("Search About...")
        self.Search_Window.transient(self.WDG)
        self.Search_Window.resizable(False, False)
        self.S_lbl_1 = Label(self.Search_Window, text='Search About :')
        self.S_lbl_1.grid(row=0, column=0, sticky='e')
        self.S_ent_1 = Entry(self.Search_Window, width=28)
        self.S_ent_1.grid(row=0, column=1, padx=2, pady=2, sticky='we')
        self.S_ent_1.focus_set()
        Ignore_case_value = IntVar()
        self.S_chk_1 = Checkbutton(self.Search_Window,
                                   text='Ignor Case',
                                   variable=Ignore_case_value)
        self.S_chk_1.grid(row=1, column=1, padx=2, pady=2, sticky='e')
        self.S_btn_1 = Button(
            self.Search_Window,
            text='Find',
            underline=0,
            command=lambda: self.Search_results(self.S_ent_1.get(
            ), Ignore_case_value.get(), self.Content_Text, self.Search_Window,
                                                self.S_ent_1))
        self.S_btn_1.grid(row=0, column=2, padx=2, pady=2, sticky='e' + 'w')
        self.S_btn_2 = Button(self.Search_Window,
                              text='Cancel',
                              underline=0,
                              command=self.Close_Search_Window)
        self.S_btn_2.grid(row=1, column=2, padx=2, pady=2, sticky='e' + 'w')

    ##
    def Search_results(self, Keyword, IfIgnoreCase, Content, Output, Input):
        Content.tag_remove('match', '1.0', 'end')
        matches_found = 0
        if Keyword:
            start_pos = '1.0'
            while True:
                start_pos = Content.search(Keyword,
                                           start_pos,
                                           nocase=IfIgnoreCase,
                                           stopindex='end')
                if not start_pos:
                    break
                end_pos = "{} + {}c".format(start_pos, len(Keyword))
                Content.tag_add('match', start_pos, end_pos)
                matches_found += 1
                start_pos = end_pos
            Content.tag_config('match', foreground='red', background='yellow')
            Input.focus_set()
            Output.title("{} matches found".format(matches_found))

    ##
    def Close_Search_Window(self):
        self.Content_Text.tag_remove('match', '1.0', 'end')
        self.Search_Window.destroy()
        #self.Search_Window.protocol('WM_DELETE_WINDOW',self.Close_Search_Window)
        return "break"

    #View_Menu_Functions
    ##
    def Content_changed(self, event=None):
        self.Update_line_numbers()
        self.Update_cursor_coord()

    ##
    def Get_line_numbers(self, event=None):
        self.Number = ""
        if self.Show_line_number.get():
            self.Row, self.Column = self.Content_Text.index('end').split('.')
            for i in range(1, int(self.Row)):
                self.Number += str(i) + "\n"
        return self.Number

    ##
    def Update_line_numbers(self):
        self.Line_Number = self.Get_line_numbers()
        self.Row_Number_Bar.config(state='normal')
        self.Row_Number_Bar.delete(1.0, 'end')
        self.Row_Number_Bar.insert(1.0, self.Line_Number)
        self.Row_Number_Bar.config(state='disabled')

    ##
    def Toggle_highlight(self, event=None):
        if self.Highlightline.get():
            self.Highlight_line()
        else:
            self.Undo_highlight()

    ##
    def Highlight_line(self, interval=100):
        self.Content_Text.tag_remove('active_line', 1.0, 'end')
        self.Content_Text.tag_add('active_line', "insert linestart",
                                  "insert lineend+1c")
        self.Content_Text.after(interval, self.Toggle_highlight)

    ##
    def Undo_highlight(self):
        self.Content_Text.tag_remove('active_line', 1.0, 'end')

    ##
    def Show_cursor_coord(self):
        self.cursor_coord_checked = self.cursorcoord.get()
        if self.cursor_coord_checked:
            self.Cursor_Coord_Bar.pack(expand='no',
                                       fill=None,
                                       side='right',
                                       anchor='se')
        else:
            self.Cursor_Coord_Bar.pack_forget()

    ##
    def Update_cursor_coord(self):
        self.Row_2, self.Column_2 = self.Content_Text.index('insert').split(
            '.')
        self.row_num, self.col_num = str(int(
            self.Row_2)), str(int(self.Column_2) + 1)
        self.Coord = "Row: {} | Column: {}".format(self.row_num, self.col_num)
        self.Cursor_Coord_Bar.config(text=self.Coord)

    #Help_Menu_Functions
    ##
    def About(self, event=None):
        messagebox.showinfo(
            'About', '{} {}'.format(self.Programe_Name,
                                    '\nDeveloped by \n TaReK'))

    ##
    def Help(self, event=None):
        messagebox.showinfo('Help',
                            'Text Editor building in python',
                            icon='question')
Example #23
0
class CimApp(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.file = None;
        self.master.title("Tiborcim")
        self.master.iconphoto(True, PhotoImage(file=ICON_PNG))
        self.files = []
        self.current_tab = StringVar()
        self.pack(expand=1, fill="both")
        self.master.minsize(300,300)
        self.master.geometry("500x500")

        self.menubar = Menu(self.master)
        self.fileMenu = Menu(self.master, tearoff=0)
        self.fileMenu.add_command(label="New", command=self.new_file,
                                  underline=0, accelerator="Ctrl+N")
        self.fileMenu.add_command(label="Open...", command=self.load_file,
                                  underline=0, accelerator="Ctrl+O")
        self.fileMenu.add_command(label="Save", command=self.file_save,
                                  underline=0, accelerator="Ctrl+S")
        self.fileMenu.add_command(label="Save As...", command=self.file_save_as,
                                  underline=5, accelerator="Ctrl+Alt+S")
        self.fileMenu.add_command(label="Close", command=self.close_file,
                                  underline=0, accelerator="Ctrl+W")
        self.fileMenu.add_separator()
        self.fileMenu.add_command(label="Exit", command=self.file_quit, underline=1)
        self.menubar.add_cascade(label="File", menu=self.fileMenu, underline=0)

        self.edit_program = Menu(self.master, tearoff=0)
        self.edit_program.add_command(label="Undo", command=self.edit_undo,
                                  underline=0, accelerator="Ctrl+Z")
        self.edit_program.add_command(label="Redo", command=self.edit_redo,
                                      underline=0, accelerator="Ctrl+Y")
        self.edit_program.add_separator()
        self.edit_program.add_command(label="Cut",
                                      command=self.edit_cut,
                                      underline=2,
                                      accelerator="Ctrl+X")
        self.edit_program.add_command(label="Copy",
                                      command=self.edit_copy,
                                      underline=0,
                                      accelerator="Ctrl+C")
        self.edit_program.add_command(label="Paste",
                                      command=self.edit_paste,
                                      underline=0,
                                      accelerator="Ctrl+V")
        self.menubar.add_cascade(label="Edit", menu=self.edit_program, underline=0)

        self.menu_program = Menu(self.master, tearoff=0)
        self.menu_program.add_command(label="Convert",
                                      command=self.convert_file,
                                      underline=0,
                                      accelerator="Ctrl+T")
        self.menu_program.add_command(label="Flash",
                                      command=self.flash_file,
                                      underline=0,
                                      accelerator="Ctrl+B")
        self.menu_program.add_separator()
        self.menubar.add_cascade(label="Program", menu=self.menu_program, underline=0)

        self.menu_view = Menu(self.master,
                              tearoff=0)
        self.viewmode = StringVar()
        self.viewmode.set("tiborcim")
        self.menu_view.add_radiobutton(label="Tiborcim",
                                       command=self.view_tiborcim,
                                       variable=self.viewmode,
                                       value="tiborcim",
                                       underline=0)
        self.menu_view.add_radiobutton(label="Python",
                                       command=self.view_python,
                                       variable=self.viewmode,
                                       value="python",
                                       underline=0)
        self.menubar.add_cascade(label="View",
                                 menu=self.menu_view,
                                 underline=0)

        self.menu_help = Menu(self.master,
                              tearoff=0)
        
        self.menu_samples = Menu(self.master, tearoff=0)
        samples = tiborcim.resources.samples_list()
        def add_sample (sample):
            self.menu_samples.add_command(label=sample,
                                          command=lambda: self.help_sample(sample))
        for sample in samples:
            add_sample(sample)
    
        self.menu_help.add_cascade(label="Samples",
                                   menu=self.menu_samples,
                                   underline=0)
        self.menu_help.add_separator()
        self.menu_help.add_command(label="README",
                                   command=self.help_readme,
                                   underline=0)
        self.menu_help.add_separator()
        self.menu_help.add_command(label="About",
                                   command=self.help_about,
                                   underline=0)
        self.menubar.add_cascade(label="Help",
                                 menu=self.menu_help,
                                 underline=0)

        self.master.config(width=450,
                           height=400,
                           menu=self.menubar)

        self.bind_all("<Control-o>", self.load_file)
        self.bind_all("<Control-s>", self.file_save)
        self.bind_all("<Control-Alt-s>", self.file_save_as)
        self.bind_all("<Control-t>", self.convert_file)
        self.bind_all("<Control-b>", self.flash_file)
        self.bind_all("<Control-w>", self.close_file)
        self.master.protocol("WM_DELETE_WINDOW", self.file_quit)

        self.file_tabs = Notebook(self)
        self.file_tabs.bind_all("<<NotebookTabChanged>>", self.file_changed)
        self.file_tabs.pack(expand=1, fill="both")

    def file_changed(self, event):
        if len(self.file_tabs.tabs()) <= 0:
            self.add_file()
            return
        title = str(event.widget.tab(event.widget.index("current"),"text")).upper().strip()
        self.menu_program.delete(3, END)
        for tab in self.file_tabs.tabs():
            tabtext = self.file_tabs.tab(self.file_tabs.index(tab),"text")
            if tabtext.upper().strip() == title:
                self.current_tab.set(tab)        
            self.menu_program.add_radiobutton(label=tabtext, command=self.program_switch,
                                  underline=1, value=tab, variable=self.current_tab)
        if title != "PYTHON" or title != "TIBORCIM":
            if self.current_file().filename is not None:
                self.master.title(self.current_file().get_file() + " - Tiborcim")
            else:
                self.master.title("Tiborcim")
            if str(self.current_file().tab(self.current_file().index("current"),"text")).upper().strip() == "TIBORCIM":
                self.menubar.entryconfig("Edit", state=NORMAL)
            else:
                self.menubar.entryconfig("Edit", state=DISABLED)
            self.viewmode.set(self.current_file().viewmode)
        if title == "PYTHON":
            self.menubar.entryconfig("Edit", state=DISABLED)
            self.current_file().viewmode = "python";
            self.viewmode.set("python");
        if title == "TIBORCIM":
            self.menubar.entryconfig("Edit", state=NORMAL)
            self.current_file().viewmode = "tiborcim";
            self.viewmode.set("tiborcim");

    def add_file(self, file=None):
        filepage = CimFilePage(self.file_tabs)
        if file is None:
            self.file_tabs.add(filepage, text="Unsaved Program")
        else:
            filepage.load_file(file)
            self.file_tabs.add(filepage, text=filepage.get_file())
        self.files.append(filepage)
        self.file_tabs.select(filepage)

    def view_tiborcim(self, event=None):
        self.current_file().view_tiborcim()

    def view_python(self, event=None):
        self.current_file().view_python()

    def program_switch(self):
        self.file_tabs.select(self.current_tab.get())

    def new_file(self, event=None):
        self.add_file()

    def load_file(self, event=None):
        fname = askopenfilename(filetypes=(("Tiborcim", "*.tibas"),("All files", "*.*") ), parent=self.master)
        if fname:
            self.add_file(fname)

    def file_save(self, event=None):
        self.current_file().save_file()
        self.file_tabs.tab(self.current_file(), text=self.current_file().get_file())

    def file_save_as(self, event=None):
        self.current_file().save_file_as()
        self.file_tabs.tab(self.current_file(), text=self.current_file().get_file())

    def convert_file(self, event=None):
        self.current_file().convert_file()

    def current_file(self, event=None):
        return self.files[int(self.file_tabs.index(self.file_tabs.select()))]

    def flash_file(self, event=None):
        from tiborcim.tibc import compiler as tibc
        from tiborcim.tibc import flash
        from tiborcim.tibc import TibcStatus as status
        com = tibc(self.current_file().text_tiborcim.get("1.0", "end"))
        res = flash(''.join(com.output))
        if res is status.SUCCESS:
            showinfo(title='Success', message='File Flashed', parent=self.master)
        else:
            showerror(title='Failure', message='An Error Occured. Code: %s' % res, parent=self.master)

    def close_file(self, event=None):
        logging.debug("Close File")
        file = self.current_file()
        if file.close():
            self.file_tabs.forget(file)
            self.files.remove(file)

    def edit_cut(self, event=None):
        self.current_file().text_tiborcim.event_generate('<Control-x>')

    def edit_copy(self, event=None):
        self.current_file().text_tiborcim.event_generate('<Control-c>')

    def edit_paste(self, event=None):
        self.current_file().text_tiborcim.event_generate('<Control-v>')

    def edit_redo(self, event=None):
        self.current_file().text_tiborcim.edit_redo()
        
    def edit_undo(self, event=None):
        self.current_file().text_tiborcim.edit_undo()

    def help_about(self, event=None):
        CimAbout.show(self)

    def help_readme(self, event=None):
        CimReadme.show(self)

    def help_sample(self, sam):
        print(sam)
        filepage = CimFilePage(self.file_tabs)
        filepage.load_file(tiborcim.resources.sample_path(sam))
        filepage.filename = None
        self.file_tabs.add(filepage, text="Unsaved Program")
        self.files.append(filepage)
        self.file_tabs.select(filepage)

    def file_quit(self, event=None):
        for ndx, member in enumerate(self.files):
            logging.debug(self.files[ndx].saved)
            if not self.files[ndx].close():
                return

        self.quit()
Example #24
0
    def BuildMainFrame(self): 
        from tkinter import Menu, IntVar, StringVar, Toplevel, Listbox, Frame, PanedWindow, Text, Scrollbar, Entry
        from tkinter import X, N, S, W, E, VERTICAL, TOP, END, DISABLED, RAISED

        menu = Menu(self.master,activeborderwidth=0,bd=0)
        self.master.config(menu=menu)
  
        filemenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0)
        menu.add_cascade(label="File", underline=0,  menu=filemenu)
        filemenu.add_command(label="New", accelerator='Ctrl+N',command=self.NewCommand)
        filemenu.add_command(label="Open...",accelerator='Ctrl+O', command=self.OpenCommand)
        filemenu.add_command(label="Save as...",accelerator='Ctrl+S', command=self.SaveCommand)
        filemenu.add_separator()
        filemenu.add_command(label="Quit",accelerator='Ctrl+Q', command=self.QuitCommand)

        self.log_on = IntVar()
        self.log_on.set(1)
  
        self.output_to_file = StringVar()
        self.output_to_file.set('n')
 
        scriptmenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0)
        modulenames = ['vmtkscripts']
        for modulename in modulenames:
            scriptsubmenu = self.BuildScriptMenu(menu,modulename)
            if scriptsubmenu:
                scriptmenu.add_cascade(label=modulename,menu=scriptsubmenu)
 
        editmenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0)
        menu.add_cascade(label="Edit",underline=0,  menu=editmenu)
        editmenu.add_cascade(label="Insert script",menu=scriptmenu)
        editmenu.add_command(label="Insert file name", accelerator='Ctrl+F',command=self.InsertFileName)
        editmenu.add_separator()
        editmenu.add_command(label="Clear input", command=self.ClearInputCommand)
        editmenu.add_command(label="Clear output", command=self.ClearOutputCommand)
        editmenu.add_command(label="Clear all", command=self.ClearAllCommand)
        editmenu.add_separator()
        editmenu.add_checkbutton(label="Log", variable=self.log_on)
        editmenu.add_separator()
        editmenu.add_radiobutton(label="No output to file", variable=self.output_to_file,value='n')
        editmenu.add_radiobutton(label="Write output to file", variable=self.output_to_file,value='w')
        editmenu.add_radiobutton(label="Append output to file", variable=self.output_to_file,value='a')
        editmenu.add_command(label="Output file...", command=self.OutputFileCommand)

        runmenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0)
        menu.add_cascade(label="Run", underline=0, menu=runmenu)
        runmenu.add_command(label="Run all", command=self.RunAllCommand)
        runmenu.add_command(label="Run current line", command=self.RunLineCommand)
        runmenu.add_command(label="Run selection", command=self.RunSelectionCommand)
       
        helpmenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0)
        menu.add_cascade(label="Help", underline=0, menu=helpmenu)
        helpmenu.add_command(label="Help", underline=0, accelerator='F1',command=self.ShowHelpCommand)
        helpmenu.add_command(label="About", underline=0, command=self.AboutCommand)

        self.master.bind("<Control-KeyPress-q>", self.QuitHandler)
        self.master.bind("<Control-KeyPress-n>", self.NewHandler)
        self.master.bind("<Control-KeyPress-o>", self.OpenHandler)
        self.master.bind("<Control-KeyPress-s>", self.SaveHandler)
        self.master.bind("<Control-KeyPress-f>", self.InsertFileNameHandler)
        self.master.bind("<KeyPress-F1>", self.ShowHelpHandler)
        self.master.bind("<KeyPress>", self.KeyPressHandler)
        
        self.wordIndex = ['1.0','1.0']
               
        self.suggestionswindow = Toplevel(bg='#ffffff',bd=0,height=50,width=600,highlightthickness=0,takefocus=True)
        self.suggestionswindow.overrideredirect(1)
        self.suggestionslist = Listbox(self.suggestionswindow,bg='#ffffff',bd=1,fg='#336699',activestyle='none',highlightthickness=0,height=9)
        self.suggestionslist.insert(END,"foo")
        self.suggestionslist.pack(side=TOP,fill=X)
        self.suggestionswindow.bind("<KeyPress>", self.TopKeyPressHandler)
        self.suggestionswindow.withdraw()

        self.master.rowconfigure(0,weight=1)
        self.master.columnconfigure(0,weight=1)
        content = Frame(self.master,bd=0,padx=2,pady=2) 
        content.grid(row=0,column=0,sticky=N+S+W+E)
        content.rowconfigure(0,weight=1,minsize=50)
        content.rowconfigure(1,weight=0)
        content.columnconfigure(0,weight=1)

        panes = PanedWindow(content,orient=VERTICAL,bd=1,sashwidth=8,sashpad=0,sashrelief=RAISED,showhandle=True)
        panes.grid(row=0,column=0,sticky=N+S+W+E)

        frame1 = Frame(panes,bd=0) 
        frame1.grid(row=0,column=0,sticky=N+S+W+E)
        frame1.columnconfigure(0,weight=1)
        frame1.columnconfigure(1,weight=0)
        frame1.rowconfigure(0,weight=1)

        panes.add(frame1,height=300,minsize=20)        

        frame2 = Frame(panes,bd=0) 
        frame2.grid(row=1,column=0,sticky=N+S+W+E)
        frame2.columnconfigure(0,weight=1)
        frame2.columnconfigure(1,weight=0)
        frame2.rowconfigure(0,weight=1)
        
        panes.add(frame2,minsize=20) 
 
        self.text_input = Text(frame1, bg='#ffffff',bd=1,highlightthickness=0)

        self.text_input.bind("<KeyPress>", self.KeyPressHandler)
        self.text_input.bind("<Button-3>", self.PopupHandler)
        self.text_input.bind("<Control-Return>", self.RunKeyboardHandler)
 
        self.input_scrollbar = Scrollbar(frame1,orient=VERTICAL,command=self.text_input.yview)
        self.text_input["yscrollcommand"] = self.input_scrollbar.set    

        self.text_output = Text(frame2,state=DISABLED,bd=1,bg='#ffffff',highlightthickness=0)
        
        self.output_scrollbar = Scrollbar(frame2,orient=VERTICAL,command=self.text_output.yview)
        self.text_output["yscrollcommand"] = self.output_scrollbar.set    
      
        self.text_entry = Entry(content,bd=1,bg='#ffffff',state=DISABLED,highlightthickness=0)

        self.text_input.focus_set()

        self.text_input.grid(row=0,column=0,sticky=N+S+W+E)
        self.input_scrollbar.grid(row=0,column=1,sticky=N+S+W+E)
        self.text_output.grid(row=0,column=0,sticky=N+S+W+E)
        self.output_scrollbar.grid(row=0,column=1,sticky=N+S+W+E)
        self.text_entry.grid(row=1,column=0,sticky=N+S+W+E)

        self.popupmenu = Menu(self.text_input, tearoff=1, bd=0)
        self.popupmenu.add_command(label="Context help", command=self.ShowHelpCommand)
        self.popupmenu.add_cascade(label="Insert script",menu=scriptmenu)
        self.popupmenu.add_command(label="Insert file name...", command=self.InsertFileName)
        self.popupmenu.add_separator()
        self.popupmenu.add_command(label="Run all", command=self.RunAllCommand)
        self.popupmenu.add_command(label="Run current line", command=self.RunLineCommand)
        self.popupmenu.add_command(label="Run selection", command=self.RunSelectionCommand)

        self.output_stream = TkPadOutputStream(self.text_output)
        self.input_stream = TkPadInputStream(self.text_entry,self.output_stream)
view_menu.add_cascade(label='Themes', menu=themes_menu)

color_schemes = {
    'Default': '#000000.#FFFFFF',
    'Greygarious': '#83406A.#D1D4D1',
    'Aquamarine': '#5B8340.#D1E7E0',
    'Bold Beige': '#4B4620.#FFF0E1',
    'Cobalt Blue': '#ffffBB.#3333aa',
    'Olive Green': '#D1E7E0.#5B8340',
    'Night Mode': '#FFFFFF.#000000',
}

theme_choice = StringVar()
theme_choice.set('Default')
for k in sorted(color_schemes):
    themes_menu.add_radiobutton(label=k, variable=theme_choice)
menu_bar.add_cascade(label='View', menu=view_menu)

about_menu = Menu(menu_bar, tearoff=0)
about_menu.add_command(label='About')
about_menu.add_command(label='Help')
menu_bar.add_cascade(label='About', menu=about_menu)
root.config(menu=menu_bar)

shortcut_bar = Frame(root, height=25, background='light sea green')
shortcut_bar.pack(expand='no', fill='x')
line_number_bar = Text(root,
                       width=4,
                       padx=3,
                       takefocus=0,
                       border=0,
Example #26
0
    def _init_menubar(self, parent):
        menubar = Menu(parent)

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

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

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

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

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

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

        parent.config(menu=menubar)
Example #27
0
    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)
Example #28
0
    def _init_menubar(self):
        self._result_size = IntVar(self.top)
        self._cntx_bf_len = IntVar(self.top)
        self._cntx_af_len = IntVar(self.top)
        menubar = Menu(self.top)

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

        editmenu = Menu(menubar, tearoff=0)
        rescntmenu = Menu(editmenu, tearoff=0)
        rescntmenu.add_radiobutton(
            label="20", variable=self._result_size, underline=0, value=20, command=self.set_result_size
        )
        rescntmenu.add_radiobutton(
            label="50", variable=self._result_size, underline=0, value=50, command=self.set_result_size
        )
        rescntmenu.add_radiobutton(
            label="100", variable=self._result_size, underline=0, value=100, command=self.set_result_size
        )
        rescntmenu.invoke(1)
        editmenu.add_cascade(label="Result Count", underline=0, menu=rescntmenu)

        cntxmenu = Menu(editmenu, tearoff=0)
        cntxbfmenu = Menu(cntxmenu, tearoff=0)
        cntxbfmenu.add_radiobutton(
            label="60 characters", variable=self._cntx_bf_len, underline=0, value=60, command=self.set_cntx_bf_len
        )
        cntxbfmenu.add_radiobutton(
            label="80 characters", variable=self._cntx_bf_len, underline=0, value=80, command=self.set_cntx_bf_len
        )
        cntxbfmenu.add_radiobutton(
            label="100 characters", variable=self._cntx_bf_len, underline=0, value=100, command=self.set_cntx_bf_len
        )
        cntxbfmenu.invoke(1)
        cntxmenu.add_cascade(label="Before", underline=0, menu=cntxbfmenu)

        cntxafmenu = Menu(cntxmenu, tearoff=0)
        cntxafmenu.add_radiobutton(
            label="70 characters", variable=self._cntx_af_len, underline=0, value=70, command=self.set_cntx_af_len
        )
        cntxafmenu.add_radiobutton(
            label="90 characters", variable=self._cntx_af_len, underline=0, value=90, command=self.set_cntx_af_len
        )
        cntxafmenu.add_radiobutton(
            label="110 characters", variable=self._cntx_af_len, underline=0, value=110, command=self.set_cntx_af_len
        )
        cntxafmenu.invoke(1)
        cntxmenu.add_cascade(label="After", underline=0, menu=cntxafmenu)

        editmenu.add_cascade(label="Context", underline=0, menu=cntxmenu)

        menubar.add_cascade(label="Edit", underline=0, menu=editmenu)

        self.top.config(menu=menubar)
Example #29
0
    def createInterface(self):
        # The interior of the toplevel panel
        interior = self.interior()
        interior['relief'] = tkinter.FLAT
        # Add placer commands to menubar
        self.menuBar.addmenu('Placer', 'Placer Panel Operations')
        self.menuBar.addmenuitem('Placer', 'command',
                            'Zero Node Path',
                            label = 'Zero All',
                            command = self.zeroAll)
        self.menuBar.addmenuitem('Placer', 'command',
                            'Reset Node Path',
                            label = 'Reset All',
                            command = self.resetAll)
        self.menuBar.addmenuitem('Placer', 'command',
                            'Print Node Path Info',
                            label = 'Print Info',
                            command = self.printNodePathInfo)
        self.menuBar.addmenuitem(
            'Placer', 'command',
            'Toggle widget visability',
            label = 'Toggle Widget Vis',
            command = SEditor.toggleWidgetVis)
        self.menuBar.addmenuitem(
            'Placer', 'command',
            'Toggle widget manipulation mode',
            label = 'Toggle Widget Mode',
            command = SEditor.manipulationControl.toggleObjectHandlesMode)

        # Get a handle to the menu frame
        menuFrame = self.menuFrame
        self.nodePathMenu = Pmw.ComboBox(
            menuFrame, labelpos = tkinter.W, label_text = 'Node Path:',
            entry_width = 20,
            selectioncommand = self.selectNodePathNamed,
            scrolledlist_items = self.nodePathNames)
        self.nodePathMenu.selectitem('selected')
        self.nodePathMenuEntry = (
            self.nodePathMenu.component('entryfield_entry'))
        self.nodePathMenuBG = (
            self.nodePathMenuEntry.configure('background')[3])
        self.nodePathMenu.pack(side = 'left', fill = 'x', expand = 1)
        self.bind(self.nodePathMenu, 'Select node path to manipulate')

        modeMenu = Pmw.OptionMenu(menuFrame,
                                  items = ('Relative To:',
                                           'Orbit:'),
                                  initialitem = 'Relative To:',
                                  command = self.setMovementMode,
                                  menubutton_width = 8)
        modeMenu.pack(side = 'left', expand = 0)
        self.bind(modeMenu, 'Select manipulation mode')

        self.refNodePathMenu = Pmw.ComboBox(
            menuFrame, entry_width = 16,
            selectioncommand = self.selectRefNodePathNamed,
            scrolledlist_items = self.refNodePathNames)
        self.refNodePathMenu.selectitem('parent')
        self.refNodePathMenuEntry = (
            self.refNodePathMenu.component('entryfield_entry'))
        self.refNodePathMenu.pack(side = 'left', fill = 'x', expand = 1)
        self.bind(self.refNodePathMenu, 'Select relative node path')

        self.undoButton = Button(menuFrame, text = 'Undo',
                                 command = SEditor.undo)
        if SEditor.undoList:
            self.undoButton['state'] = 'normal'
        else:
            self.undoButton['state'] = 'disabled'
        self.undoButton.pack(side = 'left', expand = 0)
        self.bind(self.undoButton, 'Undo last operation')

        self.redoButton = Button(menuFrame, text = 'Redo',
                                 command = SEditor.redo)
        if SEditor.redoList:
            self.redoButton['state'] = 'normal'
        else:
            self.redoButton['state'] = 'disabled'
        self.redoButton.pack(side = 'left', expand = 0)
        self.bind(self.redoButton, 'Redo last operation')

        # Create and pack the Pos Controls
        posGroup = Pmw.Group(interior,
                             tag_pyclass = Menubutton,
                             tag_text = 'Position',
                             tag_font=('MSSansSerif', 14),
                             tag_activebackground = '#909090',
                             ring_relief = tkinter.RIDGE)
        posMenubutton = posGroup.component('tag')
        self.bind(posMenubutton, 'Position menu operations')
        posMenu = Menu(posMenubutton, tearoff = 0)
        posMenu.add_command(label = 'Set to zero', command = self.zeroPos)
        posMenu.add_command(label = 'Reset initial',
                            command = self.resetPos)
        posMenubutton['menu'] = posMenu
        posGroup.pack(side='left', fill = 'both', expand = 1)
        posInterior = posGroup.interior()

        # Create the dials
        self.posX = self.createcomponent('posX', (), None,
                                         Floater, (posInterior,),
                                         text = 'X', relief = tkinter.FLAT,
                                         value = 0.0,
                                         label_foreground = 'Red')
        self.posX['commandData'] = ['x']
        self.posX['preCallback'] = self.xformStart
        self.posX['postCallback'] = self.xformStop
        self.posX['callbackData'] = ['x']
        self.posX.pack(expand=1,fill='both')

        self.posY = self.createcomponent('posY', (), None,
                                         Floater, (posInterior,),
                                         text = 'Y', relief = tkinter.FLAT,
                                         value = 0.0,
                                         label_foreground = '#00A000')
        self.posY['commandData'] = ['y']
        self.posY['preCallback'] = self.xformStart
        self.posY['postCallback'] = self.xformStop
        self.posY['callbackData'] = ['y']
        self.posY.pack(expand=1,fill='both')

        self.posZ = self.createcomponent('posZ', (), None,
                                         Floater, (posInterior,),
                                         text = 'Z', relief = tkinter.FLAT,
                                         value = 0.0,
                                         label_foreground = 'Blue')
        self.posZ['commandData'] = ['z']
        self.posZ['preCallback'] = self.xformStart
        self.posZ['postCallback'] = self.xformStop
        self.posZ['callbackData'] = ['z']
        self.posZ.pack(expand=1,fill='both')

        # Create and pack the Hpr Controls
        hprGroup = Pmw.Group(interior,
                             tag_pyclass = Menubutton,
                             tag_text = 'Orientation',
                             tag_font=('MSSansSerif', 14),
                             tag_activebackground = '#909090',
                             ring_relief = tkinter.RIDGE)
        hprMenubutton = hprGroup.component('tag')
        self.bind(hprMenubutton, 'Orientation menu operations')
        hprMenu = Menu(hprMenubutton, tearoff = 0)
        hprMenu.add_command(label = 'Set to zero', command = self.zeroHpr)
        hprMenu.add_command(label = 'Reset initial', command = self.resetHpr)
        hprMenubutton['menu'] = hprMenu
        hprGroup.pack(side='left',fill = 'both', expand = 1)
        hprInterior = hprGroup.interior()

        # Create the dials
        self.hprH = self.createcomponent('hprH', (), None,
                                         AngleDial, (hprInterior,),
                                         style = 'mini',
                                         text = 'H', value = 0.0,
                                         relief = tkinter.FLAT,
                                         label_foreground = 'blue')
        self.hprH['commandData'] = ['h']
        self.hprH['preCallback'] = self.xformStart
        self.hprH['postCallback'] = self.xformStop
        self.hprH['callbackData'] = ['h']
        self.hprH.pack(expand=1,fill='both')

        self.hprP = self.createcomponent('hprP', (), None,
                                         AngleDial, (hprInterior,),
                                         style = 'mini',
                                         text = 'P', value = 0.0,
                                         relief = tkinter.FLAT,
                                         label_foreground = 'red')
        self.hprP['commandData'] = ['p']
        self.hprP['preCallback'] = self.xformStart
        self.hprP['postCallback'] = self.xformStop
        self.hprP['callbackData'] = ['p']
        self.hprP.pack(expand=1,fill='both')

        self.hprR = self.createcomponent('hprR', (), None,
                                         AngleDial, (hprInterior,),
                                         style = 'mini',
                                         text = 'R', value = 0.0,
                                         relief = tkinter.FLAT,
                                         label_foreground = '#00A000')
        self.hprR['commandData'] = ['r']
        self.hprR['preCallback'] = self.xformStart
        self.hprR['postCallback'] = self.xformStop
        self.hprR['callbackData'] = ['r']
        self.hprR.pack(expand=1,fill='both')

        # Create and pack the Scale Controls
        # The available scaling modes
        self.scalingMode = StringVar()
        self.scalingMode.set('Scale Uniform')
        # The scaling widgets
        scaleGroup = Pmw.Group(interior,
                               tag_text = 'Scale Uniform',
                               tag_pyclass = Menubutton,
                               tag_font=('MSSansSerif', 14),
                               tag_activebackground = '#909090',
                               ring_relief = tkinter.RIDGE)
        self.scaleMenubutton = scaleGroup.component('tag')
        self.bind(self.scaleMenubutton, 'Scale menu operations')
        self.scaleMenubutton['textvariable'] = self.scalingMode

        # Scaling menu
        scaleMenu = Menu(self.scaleMenubutton, tearoff = 0)
        scaleMenu.add_command(label = 'Set to unity',
                              command = self.unitScale)
        scaleMenu.add_command(label = 'Reset initial',
                              command = self.resetScale)
        scaleMenu.add_radiobutton(label = 'Scale Free',
                                      variable = self.scalingMode)
        scaleMenu.add_radiobutton(label = 'Scale Uniform',
                                      variable = self.scalingMode)
        scaleMenu.add_radiobutton(label = 'Scale Proportional',
                                      variable = self.scalingMode)
        self.scaleMenubutton['menu'] = scaleMenu
        # Pack group widgets
        scaleGroup.pack(side='left',fill = 'both', expand = 1)
        scaleInterior = scaleGroup.interior()

        # Create the dials
        self.scaleX = self.createcomponent('scaleX', (), None,
                                           Floater, (scaleInterior,),
                                           text = 'X Scale',
                                           relief = tkinter.FLAT,
                                           min = 0.0001, value = 1.0,
                                           resetValue = 1.0,
                                           label_foreground = 'Red')
        self.scaleX['commandData'] = ['sx']
        self.scaleX['callbackData'] = ['sx']
        self.scaleX['preCallback'] = self.xformStart
        self.scaleX['postCallback'] = self.xformStop
        self.scaleX.pack(expand=1,fill='both')

        self.scaleY = self.createcomponent('scaleY', (), None,
                                           Floater, (scaleInterior,),
                                           text = 'Y Scale',
                                           relief = tkinter.FLAT,
                                           min = 0.0001, value = 1.0,
                                           resetValue = 1.0,
                                           label_foreground = '#00A000')
        self.scaleY['commandData'] = ['sy']
        self.scaleY['callbackData'] = ['sy']
        self.scaleY['preCallback'] = self.xformStart
        self.scaleY['postCallback'] = self.xformStop
        self.scaleY.pack(expand=1,fill='both')

        self.scaleZ = self.createcomponent('scaleZ', (), None,
                                           Floater, (scaleInterior,),
                                           text = 'Z Scale',
                                           relief = tkinter.FLAT,
                                           min = 0.0001, value = 1.0,
                                           resetValue = 1.0,
                                           label_foreground = 'Blue')
        self.scaleZ['commandData'] = ['sz']
        self.scaleZ['callbackData'] = ['sz']
        self.scaleZ['preCallback'] = self.xformStart
        self.scaleZ['postCallback'] = self.xformStop
        self.scaleZ.pack(expand=1,fill='both')

        # Make sure appropriate labels are showing
        self.setMovementMode('Relative To:')
        # Set up placer for inital node path
        self.selectNodePathNamed('init')
        self.selectRefNodePathNamed('parent')
        # Update place to reflect initial state
        self.updatePlacer()
        # Now that you're done setting up, attach commands
        self.posX['command'] = self.xform
        self.posY['command'] = self.xform
        self.posZ['command'] = self.xform
        self.hprH['command'] = self.xform
        self.hprP['command'] = self.xform
        self.hprR['command'] = self.xform
        self.scaleX['command'] = self.xform
        self.scaleY['command'] = self.xform
        self.scaleZ['command'] = self.xform
Example #30
0
    def _init_menubar(self, parent):
        menubar = Menu(parent)

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

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

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

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

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

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

        parent.config(menu=menubar)
Example #31
0
class Sticky(Toplevel):
    """ Sticky note class """
    def __init__(self, master, key, **kwargs):
        """ Create a new sticky note.
            master: main app
            key: key identifying this note in master.note_data
            kwargs: dictionnary of the other arguments
            (title, txt, category, color, tags, geometry, locked, checkboxes,
             images, rolled)
        """
        Toplevel.__init__(self, master)
        # --- window properties
        self.id = key
        self.is_locked = not (kwargs.get("locked", False))
        self.images = []
        self.links = {}
        self.latex = {}
        self.nb_links = 0
        self.title('mynotes%s' % key)
        self.attributes("-type", "splash")
        self.attributes("-alpha", CONFIG.getint("General", "opacity") / 100)
        self.focus_force()
        # window geometry
        self.update_idletasks()
        self.geometry(kwargs.get("geometry", '220x235'))
        self.save_geometry = kwargs.get("geometry", '220x235')
        self.update()
        self.rowconfigure(1, weight=1)
        self.minsize(10, 10)
        self.protocol("WM_DELETE_WINDOW", self.hide)

        # --- style
        self.style = Style(self)
        self.style.configure(self.id + ".TCheckbutton", selectbackground="red")
        self.style.map('TEntry', selectbackground=[('!focus', '#c3c3c3')])
        selectbg = self.style.lookup('TEntry', 'selectbackground', ('focus', ))
        self.style.configure("sel.TCheckbutton", background=selectbg)
        self.style.map("sel.TCheckbutton", background=[("active", selectbg)])

        # --- note elements
        # title
        font_title = "%s %s" % (CONFIG.get("Font", "title_family").replace(
            " ", "\ "), CONFIG.get("Font", "title_size"))
        style = CONFIG.get("Font", "title_style").split(",")
        if style:
            font_title += " "
            font_title += " ".join(style)

        self.title_var = StringVar(master=self,
                                   value=kwargs.get("title", _("Title")))
        self.title_label = Label(self,
                                 textvariable=self.title_var,
                                 anchor="center",
                                 style=self.id + ".TLabel",
                                 font=font_title)
        self.title_entry = Entry(self,
                                 textvariable=self.title_var,
                                 exportselection=False,
                                 justify="center",
                                 font=font_title)
        # buttons/icons
        self.roll = Label(self, image="img_roll", style=self.id + ".TLabel")
        self.close = Label(self, image="img_close", style=self.id + ".TLabel")
        self.im_lock = PhotoImage(master=self, file=IM_LOCK)
        self.cadenas = Label(self, style=self.id + ".TLabel")
        # corner grip
        self.corner = Sizegrip(self, style=self.id + ".TSizegrip")
        # texte
        font_text = "%s %s" % (CONFIG.get("Font", "text_family").replace(
            " ", "\ "), CONFIG.get("Font", "text_size"))
        self.txt = Text(self,
                        wrap='word',
                        undo=True,
                        selectforeground='white',
                        inactiveselectbackground=selectbg,
                        selectbackground=selectbg,
                        tabs=(10, 'right', 21, 'left'),
                        relief="flat",
                        borderwidth=0,
                        highlightthickness=0,
                        font=font_text)
        # tags
        self.txt.tag_configure("bold", font="%s bold" % font_text)
        self.txt.tag_configure("italic", font="%s italic" % font_text)
        self.txt.tag_configure("bold-italic",
                               font="%s bold italic" % font_text)
        self.txt.tag_configure("underline",
                               underline=True,
                               selectforeground="white")
        self.txt.tag_configure("overstrike",
                               overstrike=True,
                               selectforeground="white")
        self.txt.tag_configure("center", justify="center")
        self.txt.tag_configure("left", justify="left")
        self.txt.tag_configure("right", justify="right")
        self.txt.tag_configure("link",
                               foreground="blue",
                               underline=True,
                               selectforeground="white")
        self.txt.tag_configure("list",
                               lmargin1=0,
                               lmargin2=21,
                               tabs=(10, 'right', 21, 'left'))
        self.txt.tag_configure("todolist",
                               lmargin1=0,
                               lmargin2=21,
                               tabs=(10, 'right', 21, 'left'))
        margin = 2 * Font(self, font=font_text).measure("m")
        self.txt.tag_configure("enum",
                               lmargin1=0,
                               lmargin2=margin + 5,
                               tabs=(margin, 'right', margin + 5, 'left'))

        for coul in TEXT_COLORS.values():
            self.txt.tag_configure(coul,
                                   foreground=coul,
                                   selectforeground="white")
            self.txt.tag_configure(coul + "-underline",
                                   foreground=coul,
                                   selectforeground="white",
                                   underline=True)
            self.txt.tag_configure(coul + "-overstrike",
                                   foreground=coul,
                                   overstrike=True,
                                   selectforeground="white")
        # --- menus
        # --- * menu on title
        self.menu = Menu(self, tearoff=False)
        # note color
        menu_note_color = Menu(self.menu, tearoff=False)
        colors = list(COLORS.keys())
        colors.sort()
        for coul in colors:
            menu_note_color.add_command(
                label=coul, command=lambda key=coul: self.change_color(key))
        # category
        self.category = StringVar(
            self,
            kwargs.get("category", CONFIG.get("General", "default_category")))
        self.menu_categories = Menu(self.menu, tearoff=False)
        categories = CONFIG.options("Categories")
        categories.sort()
        for cat in categories:
            self.menu_categories.add_radiobutton(label=cat.capitalize(),
                                                 value=cat,
                                                 variable=self.category,
                                                 command=self.change_category)
        # position: normal, always above, always below
        self.position = StringVar(
            self, kwargs.get("position", CONFIG.get("General", "position")))
        menu_position = Menu(self.menu, tearoff=False)
        menu_position.add_radiobutton(label=_("Always above"),
                                      value="above",
                                      variable=self.position,
                                      command=self.set_position_above)
        menu_position.add_radiobutton(label=_("Always below"),
                                      value="below",
                                      variable=self.position,
                                      command=self.set_position_below)
        menu_position.add_radiobutton(label=_("Normal"),
                                      value="normal",
                                      variable=self.position,
                                      command=self.set_position_normal)
        # mode: note, list, todo list
        menu_mode = Menu(self.menu, tearoff=False)
        self.mode = StringVar(self, kwargs.get("mode", "note"))
        menu_mode.add_radiobutton(label=_("Note"),
                                  value="note",
                                  variable=self.mode,
                                  command=self.set_mode_note)
        menu_mode.add_radiobutton(label=_("List"),
                                  value="list",
                                  variable=self.mode,
                                  command=self.set_mode_list)
        menu_mode.add_radiobutton(label=_("ToDo List"),
                                  value="todolist",
                                  variable=self.mode,
                                  command=self.set_mode_todolist)
        menu_mode.add_radiobutton(label=_("Enumeration"),
                                  value="enum",
                                  variable=self.mode,
                                  command=self.set_mode_enum)

        self.menu.add_command(label=_("Delete"), command=self.delete)
        self.menu.add_cascade(label=_("Category"), menu=self.menu_categories)
        self.menu.add_cascade(label=_("Color"), menu=menu_note_color)
        self.menu.add_command(label=_("Lock"), command=self.lock)
        self.menu.add_cascade(label=_("Position"), menu=menu_position)
        self.menu.add_cascade(label=_("Mode"), menu=menu_mode)

        # --- * menu on main text
        self.menu_txt = Menu(self.txt, tearoff=False)
        # style
        menu_style = Menu(self.menu_txt, tearoff=False)
        menu_style.add_command(label=_("Bold"),
                               command=lambda: self.toggle_text_style("bold"))
        menu_style.add_command(
            label=_("Italic"),
            command=lambda: self.toggle_text_style("italic"))
        menu_style.add_command(label=_("Underline"),
                               command=self.toggle_underline)
        menu_style.add_command(label=_("Overstrike"),
                               command=self.toggle_overstrike)
        # text alignment
        menu_align = Menu(self.menu_txt, tearoff=False)
        menu_align.add_command(label=_("Left"),
                               command=lambda: self.set_align("left"))
        menu_align.add_command(label=_("Right"),
                               command=lambda: self.set_align("right"))
        menu_align.add_command(label=_("Center"),
                               command=lambda: self.set_align("center"))
        # text color
        menu_colors = Menu(self.menu_txt, tearoff=False)
        colors = list(TEXT_COLORS.keys())
        colors.sort()
        for coul in colors:
            menu_colors.add_command(label=coul,
                                    command=lambda key=coul: self.
                                    change_sel_color(TEXT_COLORS[key]))

        # insert
        menu_insert = Menu(self.menu_txt, tearoff=False)
        menu_insert.add_command(label=_("Symbols"), command=self.add_symbols)
        menu_insert.add_command(label=_("Checkbox"), command=self.add_checkbox)
        menu_insert.add_command(label=_("Image"), command=self.add_image)
        menu_insert.add_command(label=_("Date"), command=self.add_date)
        menu_insert.add_command(label=_("Link"), command=self.add_link)
        if LATEX:
            menu_insert.add_command(label="LaTex", command=self.add_latex)

        self.menu_txt.add_cascade(label=_("Style"), menu=menu_style)
        self.menu_txt.add_cascade(label=_("Alignment"), menu=menu_align)
        self.menu_txt.add_cascade(label=_("Color"), menu=menu_colors)
        self.menu_txt.add_cascade(label=_("Insert"), menu=menu_insert)

        # --- restore note content/appearence
        self.color = kwargs.get("color",
                                CONFIG.get("Categories", self.category.get()))
        self.txt.insert('1.0', kwargs.get("txt", ""))
        self.txt.edit_reset()  # clear undo stack
        # restore inserted objects (images and checkboxes)
        # we need to restore objects with increasing index to avoid placment errors
        indexes = list(kwargs.get("inserted_objects", {}).keys())
        indexes.sort(key=sorting)
        for index in indexes:
            kind, val = kwargs["inserted_objects"][index]
            if kind == "checkbox":
                ch = Checkbutton(self.txt,
                                 takefocus=False,
                                 style=self.id + ".TCheckbutton")
                if val:
                    ch.state(("selected", ))
                self.txt.window_create(index, window=ch)

            elif kind == "image":
                if os.path.exists(val):
                    self.images.append(PhotoImage(master=self.txt, file=val))
                    self.txt.image_create(index,
                                          image=self.images[-1],
                                          name=val)
        # restore tags
        for tag, indices in kwargs.get("tags", {}).items():
            if indices:
                self.txt.tag_add(tag, *indices)

        for link in kwargs.get("links", {}).values():
            self.nb_links += 1
            self.links[self.nb_links] = link
            self.txt.tag_bind("link#%i" % self.nb_links,
                              "<Button-1>",
                              lambda e, l=link: open_url(l))

        for img, latex in kwargs.get("latex", {}).items():
            self.latex[img] = latex
            if LATEX:
                self.txt.tag_bind(img,
                                  '<Double-Button-1>',
                                  lambda e, im=img: self.add_latex(im))
        mode = self.mode.get()
        if mode != "note":
            self.txt.tag_add(mode, "1.0", "end")
        self.txt.focus_set()
        self.lock()
        if kwargs.get("rolled", False):
            self.rollnote()
        if self.position.get() == "above":
            self.set_position_above()
        elif self.position.get() == "below":
            self.set_position_below()

        # --- placement
        # titlebar
        if CONFIG.get("General", "buttons_position") == "right":
            # right = lock icon - title - roll - close
            self.columnconfigure(1, weight=1)
            self.roll.grid(row=0, column=2, sticky="e")
            self.close.grid(row=0, column=3, sticky="e", padx=(0, 2))
            self.cadenas.grid(row=0, column=0, sticky="w")
            self.title_label.grid(row=0, column=1, sticky="ew", pady=(1, 0))
        else:
            # left = close - roll - title - lock icon
            self.columnconfigure(2, weight=1)
            self.roll.grid(row=0, column=1, sticky="w")
            self.close.grid(row=0, column=0, sticky="w", padx=(2, 0))
            self.cadenas.grid(row=0, column=3, sticky="e")
            self.title_label.grid(row=0, column=2, sticky="ew", pady=(1, 0))
        # body
        self.txt.grid(row=1,
                      columnspan=4,
                      column=0,
                      sticky="ewsn",
                      pady=(1, 4),
                      padx=4)
        self.corner.lift(self.txt)
        self.corner.place(relx=1.0, rely=1.0, anchor="se")

        # --- bindings
        self.bind("<FocusOut>", self.save_note)
        self.bind('<Configure>', self.bouge)
        self.bind('<Button-1>', self.change_focus, True)
        self.close.bind("<Button-1>", self.hide)
        self.close.bind("<Enter>", self.enter_close)
        self.close.bind("<Leave>", self.leave_close)
        self.roll.bind("<Button-1>", self.rollnote)
        self.roll.bind("<Enter>", self.enter_roll)
        self.roll.bind("<Leave >", self.leave_roll)
        self.title_label.bind("<Double-Button-1>", self.edit_title)
        self.title_label.bind("<ButtonPress-1>", self.start_move)
        self.title_label.bind("<ButtonRelease-1>", self.stop_move)
        self.title_label.bind("<B1-Motion>", self.move)
        self.title_label.bind('<Button-3>', self.show_menu)
        self.title_entry.bind("<Return>",
                              lambda e: self.title_entry.place_forget())
        self.title_entry.bind("<FocusOut>",
                              lambda e: self.title_entry.place_forget())
        self.title_entry.bind("<Escape>",
                              lambda e: self.title_entry.place_forget())
        self.txt.tag_bind("link", "<Enter>",
                          lambda event: self.txt.configure(cursor="hand1"))
        self.txt.tag_bind("link", "<Leave>",
                          lambda event: self.txt.configure(cursor=""))
        self.txt.bind("<FocusOut>", self.save_note)
        self.txt.bind('<Button-3>', self.show_menu_txt)
        # add binding to the existing class binding so that the selected text
        # is erased on pasting
        self.txt.bind("<Control-v>", self.paste)
        self.corner.bind('<ButtonRelease-1>', self.resize)

        # --- keyboard shortcuts
        self.txt.bind('<Control-b>', lambda e: self.toggle_text_style('bold'))
        self.txt.bind('<Control-i>',
                      lambda e: self.toggle_text_style('italic'))
        self.txt.bind('<Control-u>', lambda e: self.toggle_underline())
        self.txt.bind('<Control-r>', lambda e: self.set_align('right'))
        self.txt.bind('<Control-l>', lambda e: self.set_align('left'))

    def __setattr__(self, name, value):
        object.__setattr__(self, name, value)
        if name == "color":
            self.style.configure(self.id + ".TSizegrip", background=self.color)
            self.style.configure(self.id + ".TLabel", background=self.color)
            self.style.configure("close" + self.id + ".TLabel",
                                 background=self.color)
            self.style.configure("roll" + self.id + ".TLabel",
                                 background=self.color)
            self.style.map(self.id + ".TLabel",
                           background=[("active", self.color)])
            self.style.configure(self.id + ".TCheckbutton",
                                 background=self.color)
            self.style.map(self.id + ".TCheckbutton",
                           background=[("active", self.color),
                                       ("disabled", self.color)])
            self.style.map("close" + self.id + ".TLabel",
                           background=[("active", self.color)])
            self.style.map("roll" + self.id + ".TLabel",
                           background=[("active", self.color)])
            self.configure(bg=self.color)
            self.txt.configure(bg=self.color)

    def paste(self, event):
        """ delete selected text before pasting """
        if self.txt.tag_ranges("sel"):
            self.txt.delete("sel.first", "sel.last")

    def delete(self, confirmation=True):
        """ Delete this note """
        if confirmation:
            rep = askokcancel(_("Confirmation"), _("Delete the note?"))
        else:
            rep = True
        if rep:
            del (self.master.note_data[self.id])
            del (self.master.notes[self.id])
            self.master.save()
            self.destroy()

    def lock(self):
        """ Put note in read-only mode to avoid unwanted text insertion """
        if self.is_locked:
            selectbg = self.style.lookup('TEntry', 'selectbackground',
                                         ('focus', ))
            self.txt.configure(state="normal",
                               selectforeground='white',
                               selectbackground=selectbg,
                               inactiveselectbackground=selectbg)
            self.style.configure("sel.TCheckbutton", background=selectbg)
            self.style.map("sel.TCheckbutton",
                           background=[("active", selectbg)])
            self.is_locked = False
            for checkbox in self.txt.window_names():
                ch = self.txt.children[checkbox.split(".")[-1]]
                ch.configure(state="normal")
            self.cadenas.configure(image="")
            self.menu.entryconfigure(3, label=_("Lock"))
            self.title_label.bind("<Double-Button-1>", self.edit_title)
            self.txt.bind('<Button-3>', self.show_menu_txt)
        else:
            self.txt.configure(state="disabled",
                               selectforeground='black',
                               inactiveselectbackground='#c3c3c3',
                               selectbackground='#c3c3c3')
            self.style.configure("sel.TCheckbutton", background='#c3c3c3')
            self.style.map("sel.TCheckbutton",
                           background=[("active", '#c3c3c3')])
            self.cadenas.configure(image=self.im_lock)
            for checkbox in self.txt.window_names():
                ch = self.txt.children[checkbox.split(".")[-1]]
                ch.configure(state="disabled")
            self.is_locked = True
            self.menu.entryconfigure(3, label=_("Unlock"))
            self.title_label.unbind("<Double-Button-1>")
            self.txt.unbind('<Button-3>')
        self.save_note()

    def save_info(self):
        """ Return the dictionnary containing all the note data """
        data = {}
        data["txt"] = self.txt.get("1.0", "end")[:-1]
        data["tags"] = {}
        for tag in self.txt.tag_names():
            if tag not in ["sel", "todolist", "list", "enum"]:
                data["tags"][tag] = [
                    index.string for index in self.txt.tag_ranges(tag)
                ]
        data["title"] = self.title_var.get()
        data["geometry"] = self.save_geometry
        data["category"] = self.category.get()
        data["color"] = self.color
        data["locked"] = self.is_locked
        data["mode"] = self.mode.get()
        data["inserted_objects"] = {}
        data["rolled"] = not self.txt.winfo_ismapped()
        data["position"] = self.position.get()
        data["links"] = {}
        for i, link in self.links.items():
            if self.txt.tag_ranges("link#%i" % i):
                data["links"][i] = link
        data["latex"] = {}
        for img, latex in self.latex.items():
            if self.txt.tag_ranges(img):
                data["latex"][img] = latex
        for image in self.txt.image_names():
            data["inserted_objects"][self.txt.index(image)] = (
                "image", image.split('#')[0])
        for checkbox in self.txt.window_names():
            ch = self.txt.children[checkbox.split(".")[-1]]
            data["inserted_objects"][self.txt.index(checkbox)] = (
                "checkbox", "selected" in ch.state())
        return data

    def change_color(self, key):
        self.color = COLORS[key]
        self.save_note()

    def change_category(self, category=None):
        if category:
            self.category.set(category)
        self.color = CONFIG.get("Categories", self.category.get())
        self.save_note()

    def set_position_above(self):
        e = ewmh.EWMH()
        for w in e.getClientList():
            if w.get_wm_name() == 'mynotes%s' % self.id:
                e.setWmState(w, 1, '_NET_WM_STATE_ABOVE')
                e.setWmState(w, 0, '_NET_WM_STATE_BELOW')
        e.display.flush()
        self.save_note()

    def set_position_below(self):
        e = ewmh.EWMH()
        for w in e.getClientList():
            if w.get_wm_name() == 'mynotes%s' % self.id:
                e.setWmState(w, 0, '_NET_WM_STATE_ABOVE')
                e.setWmState(w, 1, '_NET_WM_STATE_BELOW')
        e.display.flush()
        self.save_note()

    def set_position_normal(self):
        e = ewmh.EWMH()
        for w in e.getClientList():
            if w.get_wm_name() == 'mynotes%s' % self.id:
                e.setWmState(w, 0, '_NET_WM_STATE_BELOW')
                e.setWmState(w, 0, '_NET_WM_STATE_ABOVE')
        e.display.flush()
        self.save_note()

    def set_mode_note(self):
        self.txt.tag_remove("list", "1.0", "end")
        self.txt.tag_remove("todolist", "1.0", "end")
        self.txt.tag_remove("enum", "1.0", "end")
        self.save_note()

    def set_mode_list(self):
        end = int(self.txt.index("end").split(".")[0])
        lines = self.txt.get("1.0", "end").splitlines()
        for i, l in zip(range(1, end), lines):
            # remove checkboxes
            try:
                ch = self.txt.window_cget("%i.0" % i, "window")
                self.txt.children[ch.split('.')[-1]].destroy()
                self.txt.delete("%i.0" % i)
            except TclError:
                # there is no checkbox
                # remove enumeration
                res = re.match('^\t[0-9]+\.\t', l)
                if res:
                    self.txt.delete("%i.0" % i, "%i.%i" % (i, res.end()))
            if self.txt.get("%i.0" % i, "%i.3" % i) != "\t•\t":
                self.txt.insert("%i.0" % i, "\t•\t")
        self.txt.tag_add("list", "1.0", "end")
        self.txt.tag_remove("todolist", "1.0", "end")
        self.txt.tag_remove("enum", "1.0", "end")
        self.save_note()

    def set_mode_enum(self):
        self.txt.configure(autoseparators=False)
        self.txt.edit_separator()
        end = int(self.txt.index("end").split(".")[0])
        lines = self.txt.get("1.0", "end").splitlines()
        for i, l in zip(range(1, end), lines):
            # remove checkboxes
            try:
                ch = self.txt.window_cget("%i.0" % i, "window")
                self.txt.children[ch.split('.')[-1]].destroy()
                self.txt.delete("%i.0" % i)
            except TclError:
                # there is no checkbox
                # remove bullets
                if self.txt.get("%i.0" % i, "%i.3" % i) == "\t•\t":
                    self.txt.delete("%i.0" % i, "%i.3" % i)
            if not re.match('^\t[0-9]+\.', l):
                self.txt.insert("%i.0" % i, "\t0.\t")
        self.txt.tag_add("enum", "1.0", "end")
        self.txt.tag_remove("todolist", "1.0", "end")
        self.txt.tag_remove("list", "1.0", "end")
        self.update_enum()
        self.txt.configure(autoseparators=True)
        self.txt.edit_separator()
        self.save_note()

    def set_mode_todolist(self):
        end = int(self.txt.index("end").split(".")[0])
        lines = self.txt.get("1.0", "end").splitlines()
        for i, l in zip(range(1, end), lines):
            res = re.match('^\t[0-9]+\.\t', l)
            if res:
                self.txt.delete("%i.0" % i, "%i.%i" % (i, res.end()))
            elif self.txt.get("%i.0" % i, "%i.3" % i) == "\t•\t":
                self.txt.delete("%i.0" % i, "%i.3" % i)
            try:
                ch = self.txt.window_cget("%i.0" % i, "window")
            except TclError:
                ch = Checkbutton(self.txt,
                                 takefocus=False,
                                 style=self.id + ".TCheckbutton")
                self.txt.window_create("%i.0" % i, window=ch)
        self.txt.tag_remove("enum", "1.0", "end")
        self.txt.tag_remove("list", "1.0", "end")
        self.txt.tag_add("todolist", "1.0", "end")
        self.save_note()

    # --- bindings
    def enter_roll(self, event):
        """ mouse is over the roll icon """
        self.roll.configure(image="img_rollactive")

    def leave_roll(self, event):
        """ mouse leaves the roll icon """
        self.roll.configure(image="img_roll")

    def enter_close(self, event):
        """ mouse is over the close icon """
        self.close.configure(image="img_closeactive")

    def leave_close(self, event):
        """ mouse leaves the close icon """
        self.close.configure(image="img_close")

    def change_focus(self, event):
        if not self.is_locked:
            event.widget.focus_force()

    def show_menu(self, event):
        self.menu.tk_popup(event.x_root, event.y_root)

    def show_menu_txt(self, event):
        self.menu_txt.tk_popup(event.x_root, event.y_root)

    def resize(self, event):
        self.save_geometry = self.geometry()

    def bouge(self, event):
        geo = self.geometry().split("+")[1:]
        self.save_geometry = self.save_geometry.split("+")[0] \
                             + "+%s+%s" % tuple(geo)

    def edit_title(self, event):
        self.title_entry.place(x=self.title_label.winfo_x() + 5,
                               y=self.title_label.winfo_y(),
                               anchor="nw",
                               width=self.title_label.winfo_width() - 10)

    def start_move(self, event):
        self.x = event.x
        self.y = event.y
        self.configure(cursor='fleur')

    def stop_move(self, event):
        self.x = None
        self.y = None
        self.configure(cursor='')

    def move(self, event):
        if self.x is not None and self.y is not None:
            deltax = event.x - self.x
            deltay = event.y - self.y
            x = self.winfo_x() + deltax
            y = self.winfo_y() + deltay
            self.geometry("+%s+%s" % (x, y))

    def save_note(self, event=None):
        data = self.save_info()
        data["visible"] = True
        self.master.note_data[self.id] = data
        self.master.save()

    def rollnote(self, event=None):
        if self.txt.winfo_ismapped():
            self.txt.grid_forget()
            self.corner.place_forget()
            self.geometry("%sx22" % self.winfo_width())
        else:
            self.txt.grid(row=1,
                          columnspan=4,
                          column=0,
                          sticky="ewsn",
                          pady=(1, 4),
                          padx=4)
            self.corner.place(relx=1.0, rely=1.0, anchor="se")
            self.geometry(self.save_geometry)
        self.save_note()

    def hide(self, event=None):
        """ Hide note (can be displayed again via app menu) """
        cat = self.category.get()
        self.master.add_note_to_menu(self.id,
                                     self.title_var.get().strip(), cat)
        data = self.save_info()
        data["visible"] = False
        self.master.note_data[self.id] = data
        del (self.master.notes[self.id])
        self.master.save()
        self.destroy()

    # --- Settings update
    def update_title_font(self):
        font = "%s %s" % (CONFIG.get("Font", "title_family").replace(
            " ", "\ "), CONFIG.get("Font", "title_size"))
        style = CONFIG.get("Font", "title_style").split(",")
        if style:
            font += " "
            font += " ".join(style)
        self.title_label.configure(font=font)

    def update_text_font(self):
        font = "%s %s" % (CONFIG.get("Font", "text_family").replace(
            " ", "\ "), CONFIG.get("Font", "text_size"))
        self.txt.configure(font=font)
        self.txt.tag_configure("bold", font="%s bold" % font)
        self.txt.tag_configure("italic", font="%s italic" % font)
        self.txt.tag_configure("bold-italic", font="%s bold italic" % font)
        margin = 2 * Font(self, font=font).measure("m")
        self.txt.tag_configure("enum",
                               lmargin1=0,
                               lmargin2=margin + 5,
                               tabs=(margin, 'right', margin + 5, 'left'))

    def update_menu_cat(self, categories):
        """ Update the category submenu """
        self.menu_categories.delete(0, "end")
        for cat in categories:
            self.menu_categories.add_radiobutton(label=cat.capitalize(),
                                                 value=cat,
                                                 variable=self.category,
                                                 command=self.change_category)

    def update_titlebar(self):
        if CONFIG.get("General", "buttons_position") == "right":
            # right = lock icon - title - roll - close
            self.columnconfigure(1, weight=1)
            self.columnconfigure(2, weight=0)
            self.roll.grid_configure(row=0, column=2, sticky="e")
            self.close.grid_configure(row=0, column=3, sticky="e", padx=(0, 2))
            self.cadenas.grid_configure(row=0, column=0, sticky="w")
            self.title_label.grid_configure(row=0,
                                            column=1,
                                            sticky="ew",
                                            pady=(1, 0))
        else:
            # left = close - roll - title - lock icon
            self.columnconfigure(2, weight=1)
            self.columnconfigure(1, weight=0)
            self.roll.grid_configure(row=0, column=1, sticky="w")
            self.close.grid_configure(row=0, column=0, sticky="w", padx=(2, 0))
            self.cadenas.grid_configure(row=0, column=3, sticky="e")
            self.title_label.grid_configure(row=0,
                                            column=2,
                                            sticky="ew",
                                            pady=(1, 0))

    # --- Text edition
    def add_link(self):
        def ok(eveny=None):
            lien = link.get()
            txt = text.get()
            if lien:
                if not txt:
                    txt = lien
                self.nb_links += 1
                if self.txt.tag_ranges("sel"):
                    index = self.txt.index("sel.first")
                    self.txt.delete('sel.first', 'sel.last')
                else:
                    index = "current"
                tags = self.txt.tag_names(index) + ("link",
                                                    "link#%i" % self.nb_links)
                self.txt.insert("current", txt, tags)
                if not lien[:4] == "http":
                    lien = "http://" + lien
                self.links[self.nb_links] = lien
                self.txt.tag_bind("link#%i" % self.nb_links, "<Button-1>",
                                  lambda e: open_url(lien))
            top.destroy()

        top = Toplevel(self)
        top.transient(self)
        top.update_idletasks()
        top.geometry("+%i+%i" % top.winfo_pointerxy())
        top.grab_set()
        top.resizable(True, False)
        top.title(_("Link"))
        top.columnconfigure(1, weight=1)
        text = Entry(top)
        link = Entry(top)
        if self.txt.tag_ranges('sel'):
            txt = self.txt.get('sel.first', 'sel.last')
        else:
            txt = ''
        text.insert(0, txt)
        text.icursor("end")
        Label(top, text=_("Text")).grid(row=0,
                                        column=0,
                                        sticky="e",
                                        padx=4,
                                        pady=4)
        Label(top, text=_("Link")).grid(row=1,
                                        column=0,
                                        sticky="e",
                                        padx=4,
                                        pady=4)
        text.grid(row=0, column=1, sticky="ew", padx=4, pady=4)
        link.grid(row=1, column=1, sticky="ew", padx=4, pady=4)
        Button(top, text="Ok", command=ok).grid(row=2,
                                                columnspan=2,
                                                padx=4,
                                                pady=4)

        text.focus_set()
        text.bind("<Return>", ok)
        link.bind("<Return>", ok)

    def add_checkbox(self):
        ch = Checkbutton(self.txt,
                         takefocus=False,
                         style=self.id + ".TCheckbutton")
        self.txt.window_create("current", window=ch)

    def add_date(self):
        self.txt.insert("current", strftime("%x"))

    def add_latex(self, img_name=None):
        def ok(event):
            latex = r'%s' % text.get()
            if latex:
                if img_name is None:
                    l = [
                        int(os.path.splitext(f)[0])
                        for f in os.listdir(PATH_LATEX)
                    ]
                    l.sort()
                    if l:
                        i = l[-1] + 1
                    else:
                        i = 0
                    img = "%i.png" % i
                    self.txt.tag_bind(img, '<Double-Button-1>',
                                      lambda e: self.add_latex(img))
                    self.latex[img] = latex

                else:
                    img = img_name
                im = os.path.join(PATH_LATEX, img)
                try:
                    math_to_image(latex,
                                  im,
                                  fontsize=CONFIG.getint("Font", "text_size") -
                                  2)
                    self.images.append(PhotoImage(file=im, master=self))
                    if self.txt.tag_ranges("sel"):
                        index = self.txt.index("sel.first")
                        self.txt.delete('sel.first', 'sel.last')
                    else:
                        index = self.txt.index("current")
                    self.txt.image_create(index,
                                          image=self.images[-1],
                                          name=im)
                    self.txt.tag_add(img, index)
                    top.destroy()

                except Exception as e:
                    showerror(_("Error"), str(e))

        top = Toplevel(self)
        top.transient(self)
        top.update_idletasks()
        top.geometry("+%i+%i" % top.winfo_pointerxy())
        top.grab_set()
        top.resizable(True, False)
        top.title("LaTex")
        text = Entry(top, justify='center')
        if img_name is not None:
            text.insert(0, self.latex[img_name])
        else:
            if self.txt.tag_ranges('sel'):
                text.insert(0, self.txt.get('sel.first', 'sel.last'))
            else:
                text.insert(0, '$$')
                text.icursor(1)

        text.pack(fill='x', expand=True)
        text.bind('<Return>', ok)
        text.focus_set()

    def add_image(self):
        fichier = askopenfilename(defaultextension=".png",
                                  filetypes=[("PNG", "*.png")],
                                  initialdir="",
                                  initialfile="",
                                  title=_('Select PNG image'))
        if os.path.exists(fichier):
            self.images.append(PhotoImage(master=self.txt, file=fichier))
            self.txt.image_create("current",
                                  image=self.images[-1],
                                  name=fichier)
        elif fichier:
            showerror("Erreur", "L'image %s n'existe pas" % fichier)

    def add_symbols(self):
        symbols = pick_symbol(
            self,
            CONFIG.get("Font", "text_family").replace(" ", "\ "),
            CONFIG.get("General", "symbols"))
        self.txt.insert("current", symbols)

    def toggle_text_style(self, style):
        '''Toggle the style of the selected text'''
        if self.txt.tag_ranges("sel"):
            current_tags = self.txt.tag_names("sel.first")
            if style in current_tags:
                # first char is in style so 'unstyle' the range
                self.txt.tag_remove(style, "sel.first", "sel.last")
            elif style == "bold" and "bold-italic" in current_tags:
                self.txt.tag_remove("bold-italic", "sel.first", "sel.last")
                self.txt.tag_add("italic", "sel.first", "sel.last")
            elif style == "italic" and "bold-italic" in current_tags:
                self.txt.tag_remove("bold-italic", "sel.first", "sel.last")
                self.txt.tag_add("bold", "sel.first", "sel.last")
            elif style == "bold" and "italic" in current_tags:
                self.txt.tag_remove("italic", "sel.first", "sel.last")
                self.txt.tag_add("bold-italic", "sel.first", "sel.last")
            elif style == "italic" and "bold" in current_tags:
                self.txt.tag_remove("bold", "sel.first", "sel.last")
                self.txt.tag_add("bold-italic", "sel.first", "sel.last")
            else:
                # first char is normal, so apply style to the whole selection
                self.txt.tag_add(style, "sel.first", "sel.last")

    def toggle_underline(self):
        if self.txt.tag_ranges("sel"):
            current_tags = self.txt.tag_names("sel.first")
            if "underline" in current_tags:
                # first char is in style so 'unstyle' the range
                self.txt.tag_remove("underline", "sel.first", "sel.last")
                for coul in TEXT_COLORS.values():
                    self.txt.tag_remove(coul + "-underline", "sel.first",
                                        "sel.last")
            else:
                self.txt.tag_add("underline", "sel.first", "sel.last")
                for coul in TEXT_COLORS.values():
                    r = text_ranges(self.txt, coul, "sel.first", "sel.last")
                    if r:
                        for deb, fin in zip(r[::2], r[1::2]):
                            self.txt.tag_add(coul + "-underline", "sel.first",
                                             "sel.last")

    def toggle_overstrike(self):
        if self.txt.tag_ranges("sel"):
            current_tags = self.txt.tag_names("sel.first")
            if "overstrike" in current_tags:
                # first char is in style so 'unstyle' the range
                self.txt.tag_remove("overstrike", "sel.first", "sel.last")
                for coul in TEXT_COLORS.values():
                    self.txt.tag_remove(coul + "-overstrike", "sel.first",
                                        "sel.last")
            else:
                self.txt.tag_add("overstrike", "sel.first", "sel.last")
                for coul in TEXT_COLORS.values():
                    r = text_ranges(self.txt, coul, "sel.first", "sel.last")
                    if r:
                        for deb, fin in zip(r[::2], r[1::2]):
                            self.txt.tag_add(coul + "-overstrike", "sel.first",
                                             "sel.last")

    def change_sel_color(self, color):
        """ change the color of the selection """
        if self.txt.tag_ranges("sel"):
            for coul in TEXT_COLORS.values():
                self.txt.tag_remove(coul, "sel.first", "sel.last")
                self.txt.tag_remove(coul + "-overstrike", "sel.first",
                                    "sel.last")
                self.txt.tag_remove(coul + "-underline", "sel.first",
                                    "sel.last")
            if not color == "black":
                self.txt.tag_add(color, "sel.first", "sel.last")
                underline = text_ranges(self.txt, "underline", "sel.first",
                                        "sel.last")
                overstrike = text_ranges(self.txt, "overstrike", "sel.first",
                                         "sel.last")

                for deb, fin in zip(underline[::2], underline[1::2]):
                    self.txt.tag_add(color + "-underline", deb, fin)
                for deb, fin in zip(overstrike[::2], overstrike[1::2]):
                    self.txt.tag_add(color + "-overstrike", deb, fin)

    def set_align(self, alignment):
        """ Align the text according to alignment (left, right, center) """
        if self.txt.tag_ranges("sel"):
            line = self.txt.index("sel.first").split(".")[0]
            line2 = self.txt.index("sel.last").split(".")[0]
            deb, fin = line + ".0", line2 + ".end"
            if not "\t" in self.txt.get(deb, fin):
                # tabulations don't support right/center alignment
                # remove old alignment tag
                self.txt.tag_remove("left", deb, fin)
                self.txt.tag_remove("right", deb, fin)
                self.txt.tag_remove("center", deb, fin)
                # set new alignment tag
                self.txt.tag_add(alignment, deb, fin)

    def update_enum(self):
        """ update enumeration numbers """
        lines = self.txt.get("1.0", "end").splitlines()
        indexes = []
        for i, l in enumerate(lines):
            res = re.match('^\t[0-9]+\.\t', l)
            res2 = re.match('^\t[0-9]+\.', l)
            if res:
                indexes.append((i, res.end()))
            elif res2:
                indexes.append((i, res2.end()))
        for j, (i, end) in enumerate(indexes):
            self.txt.delete("%i.0" % (i + 1), "%i.%i" % (i + 1, end))
            self.txt.insert("%i.0" % (i + 1), "\t%i.\t" % (j + 1))
        self.txt.tag_add("enum", "1.0", "end")
    def init_UI(self):
        self.frame = ttk.Frame(self)
        self.frame.pack(side=tk.TOP, fill=tk.BOTH, expand=True)

        self.new_icon = tk.PhotoImage(file='__Final/_PORTFOLIO/_projects/Text Editor/icons/new.gif')
        self.open_icon = tk.PhotoImage(file='__Final/_PORTFOLIO/_projects/Text Editor/icons/open.gif')
        self.save_icon = tk.PhotoImage(file='__Final/_PORTFOLIO/_projects/Text Editor/icons/save.gif')
        self.cut_icon = tk.PhotoImage(file='__Final/_PORTFOLIO/_projects/Text Editor/icons/cut.gif')
        self.copy_icon = tk.PhotoImage(file='__Final/_PORTFOLIO/_projects/Text Editor/icons/copy.gif')
        self.paste_icon = tk.PhotoImage(file='__Final/_PORTFOLIO/_projects/Text Editor/icons/paste.gif')
        self.undo_icon = tk.PhotoImage(file='__Final/_PORTFOLIO/_projects/Text Editor/icons/undo.gif')
        self.redo_icon = tk.PhotoImage(file='__Final/_PORTFOLIO/_projects/Text Editor/icons/redo.gif')

        # -------------------------------------
        menubar = tk.Menu(self.frame)
        file = Menu(menubar, tearoff=0)
        file.add_command(label='New', accelerator='Ctrl+N', compound='left', image=self.new_icon, underline=0, command=self.new)
        file.add_command(label='Open', accelerator='Ctrl+O', compound='left', image=self.open_icon, underline=0, command=self.open)
        file.add_command(label='Save', accelerator='Ctrl+S', compound='left', image=self.save_icon, underline=0, command=self.save)
        file.add_command(label='Save as', accelerator='Shift+Ctrl+S', command=self.saveas)
        file.add_separator()
        file.add_command(label='Exit', accelerator='Alt+F4')
        menubar.add_cascade(label='File', menu=file)

        edit = Menu(menubar, tearoff=0)
        edit.add_command(label='Undo', accelerator='Ctrl+Z', compound='left', image=self.undo_icon, command=self.undo)
        edit.add_command(label='Redo', accelerator='Ctrl+Y', compound='left', image=self.redo_icon, command=self.redo)
        edit.add_separator()
        edit.add_command(label='Cut', accelerator='Ctrl+X', compound='left', image=self.cut_icon, command=self.cut)
        edit.add_command(label='Copy', accelerator='Ctrl+C', compound='left', image=self.copy_icon, command=self.copy)
        edit.add_command(label='Paste', accelerator='Ctrl+V', compound='left', image=self.paste_icon, command=self.paste)
        edit.add_separator()
        edit.add_command(label='Find', underline=0, accelerator='Ctrl+F', command=self.find)
        edit.add_separator()
        edit.add_command(label='Select All', underline=7, accelerator='Ctrl+A', command=self.select)
        menubar.add_cascade(label='Edit', menu=edit)

        view = Menu(menubar, tearoff=0)
        self.show_linebar_number = tk.IntVar()
        self.show_linebar_number.set(1)
        view.add_checkbutton(label='Show Line Number', variable=self.show_linebar_number, command=self.update_line_numbers)

        self.show_cursor_info = tk.IntVar()
        self.show_cursor_info.set(1)
        view.add_checkbutton(label='Show Cursor Location at Bottom', variable=self.show_cursor_info, command=self.show_statusbar)

        self.highlight = tk.BooleanVar()
        view.add_checkbutton(label='Highlight Current Line', onvalue=1, offvalue=0, variable=self.highlight, command=self.toggle_highlight)

        themes = Menu(menubar, tearoff=0)
        view.add_cascade(label='Themes', menu=themes)

        self.theme_choice = tk.StringVar()
        self.theme_choice.set('Default')

        for color in sorted(self.color_schemes):
            themes.add_radiobutton(label=color, variable=self.theme_choice, command=self.change_theme)

        menubar.add_cascade(label='View', menu=view)

        about = Menu(menubar, tearoff=0)
        about.add_command(label='About', command=self.mb_about)
        about.add_command(label='Help', command=self.mb_help)
        menubar.add_cascade(label='About',  menu=about)

        self.config(menu=menubar)

        # -------------------------------------
        toolbar = ttk.Frame(self.frame, height=25)
        toolbar.pack(expand=tk.NO, fill=tk.X)

        for icon in self.icons:
            toolbar_icon = tk.PhotoImage(file=f'__Final/_PORTFOLIO/_projects/Text Editor/icons/{icon}.gif')
            cmd = eval(f'self.{icon}')
            toolbar_button = ttk.Button(toolbar, image=toolbar_icon, command=cmd)
            toolbar_button.image = toolbar_icon
            toolbar_button.pack(side=tk.LEFT, pady=2, padx=(2, 0))

        self.linebar = tk.Text(self.frame, background='khaki', width=4, padx=3, takefocus=0,  border=0, state=tk.DISABLED, wrap=tk.NONE)
        self.linebar.pack(side=tk.LEFT,  fill=tk.Y)

        self.textarea = tk.Text(self.frame, wrap=tk.WORD, undo=1, borderwidth=0, highlightthickness=0)
        self.textarea.pack(expand=tk.YES, fill=tk.BOTH, anchor=tk.CENTER)

        self.scrollbar = ttk.Scrollbar(self.textarea)
        self.scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.scrollbar.config(command=self.on_scroll)

        self.textarea['yscrollcommand'] = self.on_textscroll
        self.linebar['yscrollcommand'] = self.on_textscroll

        # -------------------------------------
        self.statusbar = ttk.Frame(self, height=25)
        self.statusbar.pack(side=tk.TOP, expand=tk.NO, fill=tk.X, anchor=tk.SW)

        self.cursorinfo = ttk.Label(self.statusbar, text='Line: 1 | Column: 1')
        self.cursorinfo.pack(anchor=tk.SE)

        # -------------------------------------
        # set up the pop-up menu
        self.popupmenu = Menu(self.textarea, tearoff=0)
        for name in ('cut', 'copy', 'paste', 'undo', 'redo'):
            cmd = eval(f'self.{name}')
            self.popupmenu.add_command(label=name, compound='left', command=cmd)
        self.popupmenu.add_separator()
        self.popupmenu.add_command(label='Select All', underline=7, command=self.select)
Example #33
0
    def _init_general(self):
        frame_general = Frame(self)
        self.notebook.add(frame_general, text=_("General"))
        # --- Language
        Label(frame_general, text=_("Language")).grid(row=0,
                                                      column=0,
                                                      padx=8,
                                                      pady=4,
                                                      sticky="e")

        menu_lang = Menu(frame_general, tearoff=False, background=self._bg)
        mb = Menubutton(frame_general, menu=menu_lang, textvariable=self.lang)
        mb.grid(row=0, column=1, padx=8, pady=4, sticky="w")
        for lang in LANGUAGES:
            language = LANGUAGES[lang]
            menu_lang.add_radiobutton(label=language,
                                      value=language,
                                      variable=self.lang,
                                      command=self.translate)

        # --- gui toolkit
        Label(frame_general,
              text=_("GUI Toolkit for the system tray icon")).grid(row=2,
                                                                   column=0,
                                                                   padx=8,
                                                                   pady=4,
                                                                   sticky="e")

        menu_gui = Menu(frame_general, tearoff=False, background=self._bg)
        Menubutton(frame_general,
                   menu=menu_gui,
                   width=9,
                   textvariable=self.gui).grid(row=2,
                                               column=1,
                                               padx=8,
                                               pady=4,
                                               sticky="w")
        for toolkit, b in TOOLKITS.items():
            if b:
                menu_gui.add_radiobutton(label=toolkit.capitalize(),
                                         value=toolkit.capitalize(),
                                         variable=self.gui,
                                         command=self.change_gui)
        # --- Update delay
        Label(frame_general,
              text=_("Feed update delay (min)")).grid(row=4,
                                                      column=0,
                                                      padx=8,
                                                      pady=4,
                                                      sticky="e")
        self.entry_delay = Entry(frame_general,
                                 width=10,
                                 justify='center',
                                 validate='key',
                                 validatecommand=(self._validate, '%P'))
        self.entry_delay.grid(row=4, column=1, padx=8, pady=4, sticky='w')
        self.entry_delay.insert(
            0,
            CONFIG.getint('General', 'update_delay') // 60000)
        # --- image loading timeout
        Label(frame_general,
              text=_("Image loading timeout (s)")).grid(row=5,
                                                        column=0,
                                                        padx=8,
                                                        pady=4,
                                                        sticky="e")
        self.entry_timeout = Entry(frame_general,
                                   width=10,
                                   justify='center',
                                   validate='key',
                                   validatecommand=(self._validate, '%P'))
        self.entry_timeout.grid(row=5, column=1, padx=8, pady=4, sticky='w')
        self.entry_timeout.insert(
            0, CONFIG.getint('General', 'img_timeout', fallback=10))
        # --- Notifications
        self.notifications = Checkbutton(frame_general,
                                         text=_("Activate notifications"))
        self.notifications.grid(row=6,
                                column=0,
                                padx=8,
                                pady=4,
                                columnspan=2,
                                sticky='w')
        if CONFIG.getboolean('General', 'notifications', fallback=True):
            self.notifications.state(('selected', '!alternate'))
        else:
            self.notifications.state(('!selected', '!alternate'))

        # --- Confirm remove feed
        self.confirm_feed_rem = Checkbutton(
            frame_general,
            text=_("Show confirmation dialog before removing feed"))
        self.confirm_feed_rem.grid(row=7,
                                   column=0,
                                   padx=8,
                                   pady=4,
                                   columnspan=2,
                                   sticky='w')
        if CONFIG.getboolean('General', 'confirm_feed_remove', fallback=True):
            self.confirm_feed_rem.state(('selected', '!alternate'))
        else:
            self.confirm_feed_rem.state(('!selected', '!alternate'))
        # --- Confirm remove cat
        self.confirm_cat_rem = Checkbutton(
            frame_general,
            text=_("Show confirmation dialog before removing category"))
        self.confirm_cat_rem.grid(row=8,
                                  column=0,
                                  padx=8,
                                  pady=4,
                                  columnspan=2,
                                  sticky='w')
        if CONFIG.getboolean('General', 'confirm_cat_remove', fallback=True):
            self.confirm_cat_rem.state(('selected', '!alternate'))
        else:
            self.confirm_cat_rem.state(('!selected', '!alternate'))
        # --- Confirm update
        self.confirm_update = Checkbutton(
            frame_general, text=_("Check for updates on start-up"))
        self.confirm_update.grid(row=9,
                                 column=0,
                                 padx=8,
                                 pady=4,
                                 columnspan=2,
                                 sticky='w')
        if CONFIG.getboolean('General', 'check_update', fallback=True):
            self.confirm_update.state(('selected', '!alternate'))
        else:
            self.confirm_update.state(('!selected', '!alternate'))

        # --- Splash supported
        self.splash_support = Checkbutton(
            frame_general,
            text=_("Check this box if the widgets disappear when you click"))
        self.splash_support.grid(row=10,
                                 column=0,
                                 padx=8,
                                 pady=4,
                                 columnspan=2,
                                 sticky='w')
        if not CONFIG.getboolean('General', 'splash_supported', fallback=True):
            self.splash_support.state(('selected', '!alternate'))
        else:
            self.splash_support.state(('!selected', '!alternate'))
Example #34
0
    def __init__(self, master):
        """Create note manager to easily delete multiple notes."""
        Toplevel.__init__(self, master, class_='MyNotes')
        self.title(_("Note Manager"))
        self.minsize(width=546, height=200)
        self.grab_set()
        categories = CONFIG.options("Categories")
        categories.sort()

        self.im_del = PhotoImage(file=IM_DELETE, master=self)
        self.im_change = PhotoImage(file=IM_CHANGE, master=self)
        self.im_visible = PhotoImage(file=IM_VISIBLE_24, master=self)
        self.im_hidden = PhotoImage(file=IM_HIDDEN_24, master=self)

        tooltipwrapper = TooltipWrapper(self)

        self.notebook = Notebook(self)
        self.notebook.pack(fill='both', expand=True)

        self.texts = {}
        self.frames = {}
        self.notes = {}

        # to change notes category
        menu_cat = Menu(self, tearoff=False)
        self.category = StringVar(self)

        # create one tab per category
        for cat in categories:
            menu_cat.add_radiobutton(label=cat.capitalize(),
                                     value=cat,
                                     variable=self.category,
                                     command=self.change_cat_selection)
            self.notes[cat] = {}
            frame = Frame(self.notebook, padding=2)
            self.texts[cat] = Text(frame,
                                   width=1,
                                   height=1,
                                   bg=self.cget('bg'),
                                   relief='flat',
                                   highlightthickness=0,
                                   padx=0,
                                   pady=0,
                                   cursor='arrow')
            frame.columnconfigure(0, weight=1)
            frame.rowconfigure(1, weight=1)

            self.texts[cat].grid(row=1, column=0, sticky='ewsn')
            scrolly = Scrollbar(frame,
                                orient='vertical',
                                command=self.texts[cat].yview)
            scrolly.grid(row=1, column=1, sticky='ns', pady=(2, 0))
            scrollx = Scrollbar(frame,
                                orient='horizontal',
                                command=self.texts[cat].xview)
            scrollx.grid(row=2, column=0, sticky='ew')
            self.texts[cat].configure(xscrollcommand=scrollx.set,
                                      yscrollcommand=scrolly.set)
            self.frames[cat] = Frame(self.texts[cat],
                                     style='bg.TFrame',
                                     padding=1,
                                     height=29,
                                     width=523)
            self.frames[cat].columnconfigure(0, weight=1, minsize=170)
            headings = Frame(frame, padding=(1, 0, 1, 0))
            headings.columnconfigure(0, weight=0, minsize=20)
            headings.columnconfigure(1, weight=1, minsize=198)
            headings.columnconfigure(2, weight=1, minsize=198)
            headings.columnconfigure(3, weight=0, minsize=84)
            headings.columnconfigure(4, weight=0, minsize=22)
            Heading(headings,
                    cat,
                    'title',
                    command=self.sort_column,
                    text=_('Title')).grid(row=0, column=1, sticky='ew')
            Heading(headings,
                    cat,
                    'text',
                    command=self.sort_column,
                    text=_('Text')).grid(row=0, column=2, sticky='ew')
            Heading(headings,
                    cat,
                    'date',
                    command=self.sort_column,
                    text=_('Date')).grid(row=0, column=3, sticky='ew')
            Heading(headings,
                    cat,
                    'select_all',
                    style='select.heading.TLabel',
                    padding=0,
                    command=self.toggle_selectall).place(x=0,
                                                         y=0,
                                                         anchor='nw',
                                                         relheight=1,
                                                         width=20)
            Heading(headings, cat, 'visibility',
                    command=self.sort_column).place(relx=1,
                                                    y=0,
                                                    anchor='ne',
                                                    bordermode='outside',
                                                    width=23,
                                                    relheight=1)
            headings.place(x=0, y=2, anchor='nw')
            self.update_idletasks()
            frame.rowconfigure(0, minsize=headings.winfo_reqheight())
            self.texts[cat].window_create('1.0', window=self.frames[cat])
            b_frame = Frame(frame)
            b_frame.grid(row=3, columnspan=2)
            m = Menubutton(b_frame,
                           image=self.im_change,
                           text=_('Change category'),
                           compound='right',
                           menu=menu_cat,
                           padding=1)
            m.pack(side='left', padx=4, pady=4, fill='y')
            tooltipwrapper.add_tooltip(m,
                                       _('Change category of selected notes'))
            b_show = Button(b_frame,
                            image=self.im_visible,
                            padding=1,
                            command=self.show_selection)
            b_show.pack(side='left', padx=4, pady=4)
            tooltipwrapper.add_tooltip(b_show, _('Show selected notes'))
            b_hide = Button(b_frame,
                            image=self.im_hidden,
                            padding=1,
                            command=self.hide_selection)
            b_hide.pack(side='left', padx=4, pady=4)
            tooltipwrapper.add_tooltip(b_hide, _('Hide selected notes'))
            b_del = Button(b_frame,
                           image=self.im_del,
                           command=self.del_selection,
                           padding=1)
            b_del.pack(side='left', padx=4, pady=4, fill='y')
            tooltipwrapper.add_tooltip(b_del, _('Delete selected notes'))

            self.notebook.add(frame,
                              text=cat.capitalize(),
                              sticky="ewsn",
                              padding=0)
        # display notes by category
        for key, note_data in self.master.note_data.items():
            self.display_note(key, note_data)

        for txt in self.texts.values():
            txt.configure(state='disabled')
        self.geometry('410x450')
        self.bind("<Button-4>", lambda e: self.scroll(-1))
        self.bind("<Button-5>", lambda e: self.scroll(1))
        self.notebook.bind('<<NotebookTabChanged>>', self.on_change_tab)
Example #35
0
    def _init_menubar(self):
        self._result_size = IntVar(self.top)
        self._cntx_bf_len = IntVar(self.top)
        self._cntx_af_len = IntVar(self.top)
        menubar = Menu(self.top)

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

        editmenu = Menu(menubar, tearoff=0)
        rescntmenu = Menu(editmenu, tearoff=0)
        rescntmenu.add_radiobutton(label='20',
                                   variable=self._result_size,
                                   underline=0,
                                   value=20,
                                   command=self.set_result_size)
        rescntmenu.add_radiobutton(label='50',
                                   variable=self._result_size,
                                   underline=0,
                                   value=50,
                                   command=self.set_result_size)
        rescntmenu.add_radiobutton(label='100',
                                   variable=self._result_size,
                                   underline=0,
                                   value=100,
                                   command=self.set_result_size)
        rescntmenu.invoke(1)
        editmenu.add_cascade(label='Result Count',
                             underline=0,
                             menu=rescntmenu)

        cntxmenu = Menu(editmenu, tearoff=0)
        cntxbfmenu = Menu(cntxmenu, tearoff=0)
        cntxbfmenu.add_radiobutton(label='60 characters',
                                   variable=self._cntx_bf_len,
                                   underline=0,
                                   value=60,
                                   command=self.set_cntx_bf_len)
        cntxbfmenu.add_radiobutton(label='80 characters',
                                   variable=self._cntx_bf_len,
                                   underline=0,
                                   value=80,
                                   command=self.set_cntx_bf_len)
        cntxbfmenu.add_radiobutton(label='100 characters',
                                   variable=self._cntx_bf_len,
                                   underline=0,
                                   value=100,
                                   command=self.set_cntx_bf_len)
        cntxbfmenu.invoke(1)
        cntxmenu.add_cascade(label='Before', underline=0, menu=cntxbfmenu)

        cntxafmenu = Menu(cntxmenu, tearoff=0)
        cntxafmenu.add_radiobutton(label='70 characters',
                                   variable=self._cntx_af_len,
                                   underline=0,
                                   value=70,
                                   command=self.set_cntx_af_len)
        cntxafmenu.add_radiobutton(label='90 characters',
                                   variable=self._cntx_af_len,
                                   underline=0,
                                   value=90,
                                   command=self.set_cntx_af_len)
        cntxafmenu.add_radiobutton(label='110 characters',
                                   variable=self._cntx_af_len,
                                   underline=0,
                                   value=110,
                                   command=self.set_cntx_af_len)
        cntxafmenu.invoke(1)
        cntxmenu.add_cascade(label='After', underline=0, menu=cntxafmenu)

        editmenu.add_cascade(label='Context', underline=0, menu=cntxmenu)

        menubar.add_cascade(label='Edit', underline=0, menu=editmenu)

        self.top.config(menu=menubar)
Example #36
0
    def __init__(self, master, key, **kwargs):
        """ Create a new sticky note.
            master: main app
            key: key identifying this note in master.note_data
            kwargs: dictionnary of the other arguments
            (title, txt, category, color, tags, geometry, locked, checkboxes,
             images, rolled)
        """
        Toplevel.__init__(self, master)
        # --- window properties
        self.id = key
        self.is_locked = not (kwargs.get("locked", False))
        self.images = []
        self.links = {}
        self.latex = {}
        self.nb_links = 0
        self.title('mynotes%s' % key)
        self.attributes("-type", "splash")
        self.attributes("-alpha", CONFIG.getint("General", "opacity") / 100)
        self.focus_force()
        # window geometry
        self.update_idletasks()
        self.geometry(kwargs.get("geometry", '220x235'))
        self.save_geometry = kwargs.get("geometry", '220x235')
        self.update()
        self.rowconfigure(1, weight=1)
        self.minsize(10, 10)
        self.protocol("WM_DELETE_WINDOW", self.hide)

        # --- style
        self.style = Style(self)
        self.style.configure(self.id + ".TCheckbutton", selectbackground="red")
        self.style.map('TEntry', selectbackground=[('!focus', '#c3c3c3')])
        selectbg = self.style.lookup('TEntry', 'selectbackground', ('focus', ))
        self.style.configure("sel.TCheckbutton", background=selectbg)
        self.style.map("sel.TCheckbutton", background=[("active", selectbg)])

        # --- note elements
        # title
        font_title = "%s %s" % (CONFIG.get("Font", "title_family").replace(
            " ", "\ "), CONFIG.get("Font", "title_size"))
        style = CONFIG.get("Font", "title_style").split(",")
        if style:
            font_title += " "
            font_title += " ".join(style)

        self.title_var = StringVar(master=self,
                                   value=kwargs.get("title", _("Title")))
        self.title_label = Label(self,
                                 textvariable=self.title_var,
                                 anchor="center",
                                 style=self.id + ".TLabel",
                                 font=font_title)
        self.title_entry = Entry(self,
                                 textvariable=self.title_var,
                                 exportselection=False,
                                 justify="center",
                                 font=font_title)
        # buttons/icons
        self.roll = Label(self, image="img_roll", style=self.id + ".TLabel")
        self.close = Label(self, image="img_close", style=self.id + ".TLabel")
        self.im_lock = PhotoImage(master=self, file=IM_LOCK)
        self.cadenas = Label(self, style=self.id + ".TLabel")
        # corner grip
        self.corner = Sizegrip(self, style=self.id + ".TSizegrip")
        # texte
        font_text = "%s %s" % (CONFIG.get("Font", "text_family").replace(
            " ", "\ "), CONFIG.get("Font", "text_size"))
        self.txt = Text(self,
                        wrap='word',
                        undo=True,
                        selectforeground='white',
                        inactiveselectbackground=selectbg,
                        selectbackground=selectbg,
                        tabs=(10, 'right', 21, 'left'),
                        relief="flat",
                        borderwidth=0,
                        highlightthickness=0,
                        font=font_text)
        # tags
        self.txt.tag_configure("bold", font="%s bold" % font_text)
        self.txt.tag_configure("italic", font="%s italic" % font_text)
        self.txt.tag_configure("bold-italic",
                               font="%s bold italic" % font_text)
        self.txt.tag_configure("underline",
                               underline=True,
                               selectforeground="white")
        self.txt.tag_configure("overstrike",
                               overstrike=True,
                               selectforeground="white")
        self.txt.tag_configure("center", justify="center")
        self.txt.tag_configure("left", justify="left")
        self.txt.tag_configure("right", justify="right")
        self.txt.tag_configure("link",
                               foreground="blue",
                               underline=True,
                               selectforeground="white")
        self.txt.tag_configure("list",
                               lmargin1=0,
                               lmargin2=21,
                               tabs=(10, 'right', 21, 'left'))
        self.txt.tag_configure("todolist",
                               lmargin1=0,
                               lmargin2=21,
                               tabs=(10, 'right', 21, 'left'))
        margin = 2 * Font(self, font=font_text).measure("m")
        self.txt.tag_configure("enum",
                               lmargin1=0,
                               lmargin2=margin + 5,
                               tabs=(margin, 'right', margin + 5, 'left'))

        for coul in TEXT_COLORS.values():
            self.txt.tag_configure(coul,
                                   foreground=coul,
                                   selectforeground="white")
            self.txt.tag_configure(coul + "-underline",
                                   foreground=coul,
                                   selectforeground="white",
                                   underline=True)
            self.txt.tag_configure(coul + "-overstrike",
                                   foreground=coul,
                                   overstrike=True,
                                   selectforeground="white")
        # --- menus
        # --- * menu on title
        self.menu = Menu(self, tearoff=False)
        # note color
        menu_note_color = Menu(self.menu, tearoff=False)
        colors = list(COLORS.keys())
        colors.sort()
        for coul in colors:
            menu_note_color.add_command(
                label=coul, command=lambda key=coul: self.change_color(key))
        # category
        self.category = StringVar(
            self,
            kwargs.get("category", CONFIG.get("General", "default_category")))
        self.menu_categories = Menu(self.menu, tearoff=False)
        categories = CONFIG.options("Categories")
        categories.sort()
        for cat in categories:
            self.menu_categories.add_radiobutton(label=cat.capitalize(),
                                                 value=cat,
                                                 variable=self.category,
                                                 command=self.change_category)
        # position: normal, always above, always below
        self.position = StringVar(
            self, kwargs.get("position", CONFIG.get("General", "position")))
        menu_position = Menu(self.menu, tearoff=False)
        menu_position.add_radiobutton(label=_("Always above"),
                                      value="above",
                                      variable=self.position,
                                      command=self.set_position_above)
        menu_position.add_radiobutton(label=_("Always below"),
                                      value="below",
                                      variable=self.position,
                                      command=self.set_position_below)
        menu_position.add_radiobutton(label=_("Normal"),
                                      value="normal",
                                      variable=self.position,
                                      command=self.set_position_normal)
        # mode: note, list, todo list
        menu_mode = Menu(self.menu, tearoff=False)
        self.mode = StringVar(self, kwargs.get("mode", "note"))
        menu_mode.add_radiobutton(label=_("Note"),
                                  value="note",
                                  variable=self.mode,
                                  command=self.set_mode_note)
        menu_mode.add_radiobutton(label=_("List"),
                                  value="list",
                                  variable=self.mode,
                                  command=self.set_mode_list)
        menu_mode.add_radiobutton(label=_("ToDo List"),
                                  value="todolist",
                                  variable=self.mode,
                                  command=self.set_mode_todolist)
        menu_mode.add_radiobutton(label=_("Enumeration"),
                                  value="enum",
                                  variable=self.mode,
                                  command=self.set_mode_enum)

        self.menu.add_command(label=_("Delete"), command=self.delete)
        self.menu.add_cascade(label=_("Category"), menu=self.menu_categories)
        self.menu.add_cascade(label=_("Color"), menu=menu_note_color)
        self.menu.add_command(label=_("Lock"), command=self.lock)
        self.menu.add_cascade(label=_("Position"), menu=menu_position)
        self.menu.add_cascade(label=_("Mode"), menu=menu_mode)

        # --- * menu on main text
        self.menu_txt = Menu(self.txt, tearoff=False)
        # style
        menu_style = Menu(self.menu_txt, tearoff=False)
        menu_style.add_command(label=_("Bold"),
                               command=lambda: self.toggle_text_style("bold"))
        menu_style.add_command(
            label=_("Italic"),
            command=lambda: self.toggle_text_style("italic"))
        menu_style.add_command(label=_("Underline"),
                               command=self.toggle_underline)
        menu_style.add_command(label=_("Overstrike"),
                               command=self.toggle_overstrike)
        # text alignment
        menu_align = Menu(self.menu_txt, tearoff=False)
        menu_align.add_command(label=_("Left"),
                               command=lambda: self.set_align("left"))
        menu_align.add_command(label=_("Right"),
                               command=lambda: self.set_align("right"))
        menu_align.add_command(label=_("Center"),
                               command=lambda: self.set_align("center"))
        # text color
        menu_colors = Menu(self.menu_txt, tearoff=False)
        colors = list(TEXT_COLORS.keys())
        colors.sort()
        for coul in colors:
            menu_colors.add_command(label=coul,
                                    command=lambda key=coul: self.
                                    change_sel_color(TEXT_COLORS[key]))

        # insert
        menu_insert = Menu(self.menu_txt, tearoff=False)
        menu_insert.add_command(label=_("Symbols"), command=self.add_symbols)
        menu_insert.add_command(label=_("Checkbox"), command=self.add_checkbox)
        menu_insert.add_command(label=_("Image"), command=self.add_image)
        menu_insert.add_command(label=_("Date"), command=self.add_date)
        menu_insert.add_command(label=_("Link"), command=self.add_link)
        if LATEX:
            menu_insert.add_command(label="LaTex", command=self.add_latex)

        self.menu_txt.add_cascade(label=_("Style"), menu=menu_style)
        self.menu_txt.add_cascade(label=_("Alignment"), menu=menu_align)
        self.menu_txt.add_cascade(label=_("Color"), menu=menu_colors)
        self.menu_txt.add_cascade(label=_("Insert"), menu=menu_insert)

        # --- restore note content/appearence
        self.color = kwargs.get("color",
                                CONFIG.get("Categories", self.category.get()))
        self.txt.insert('1.0', kwargs.get("txt", ""))
        self.txt.edit_reset()  # clear undo stack
        # restore inserted objects (images and checkboxes)
        # we need to restore objects with increasing index to avoid placment errors
        indexes = list(kwargs.get("inserted_objects", {}).keys())
        indexes.sort(key=sorting)
        for index in indexes:
            kind, val = kwargs["inserted_objects"][index]
            if kind == "checkbox":
                ch = Checkbutton(self.txt,
                                 takefocus=False,
                                 style=self.id + ".TCheckbutton")
                if val:
                    ch.state(("selected", ))
                self.txt.window_create(index, window=ch)

            elif kind == "image":
                if os.path.exists(val):
                    self.images.append(PhotoImage(master=self.txt, file=val))
                    self.txt.image_create(index,
                                          image=self.images[-1],
                                          name=val)
        # restore tags
        for tag, indices in kwargs.get("tags", {}).items():
            if indices:
                self.txt.tag_add(tag, *indices)

        for link in kwargs.get("links", {}).values():
            self.nb_links += 1
            self.links[self.nb_links] = link
            self.txt.tag_bind("link#%i" % self.nb_links,
                              "<Button-1>",
                              lambda e, l=link: open_url(l))

        for img, latex in kwargs.get("latex", {}).items():
            self.latex[img] = latex
            if LATEX:
                self.txt.tag_bind(img,
                                  '<Double-Button-1>',
                                  lambda e, im=img: self.add_latex(im))
        mode = self.mode.get()
        if mode != "note":
            self.txt.tag_add(mode, "1.0", "end")
        self.txt.focus_set()
        self.lock()
        if kwargs.get("rolled", False):
            self.rollnote()
        if self.position.get() == "above":
            self.set_position_above()
        elif self.position.get() == "below":
            self.set_position_below()

        # --- placement
        # titlebar
        if CONFIG.get("General", "buttons_position") == "right":
            # right = lock icon - title - roll - close
            self.columnconfigure(1, weight=1)
            self.roll.grid(row=0, column=2, sticky="e")
            self.close.grid(row=0, column=3, sticky="e", padx=(0, 2))
            self.cadenas.grid(row=0, column=0, sticky="w")
            self.title_label.grid(row=0, column=1, sticky="ew", pady=(1, 0))
        else:
            # left = close - roll - title - lock icon
            self.columnconfigure(2, weight=1)
            self.roll.grid(row=0, column=1, sticky="w")
            self.close.grid(row=0, column=0, sticky="w", padx=(2, 0))
            self.cadenas.grid(row=0, column=3, sticky="e")
            self.title_label.grid(row=0, column=2, sticky="ew", pady=(1, 0))
        # body
        self.txt.grid(row=1,
                      columnspan=4,
                      column=0,
                      sticky="ewsn",
                      pady=(1, 4),
                      padx=4)
        self.corner.lift(self.txt)
        self.corner.place(relx=1.0, rely=1.0, anchor="se")

        # --- bindings
        self.bind("<FocusOut>", self.save_note)
        self.bind('<Configure>', self.bouge)
        self.bind('<Button-1>', self.change_focus, True)
        self.close.bind("<Button-1>", self.hide)
        self.close.bind("<Enter>", self.enter_close)
        self.close.bind("<Leave>", self.leave_close)
        self.roll.bind("<Button-1>", self.rollnote)
        self.roll.bind("<Enter>", self.enter_roll)
        self.roll.bind("<Leave >", self.leave_roll)
        self.title_label.bind("<Double-Button-1>", self.edit_title)
        self.title_label.bind("<ButtonPress-1>", self.start_move)
        self.title_label.bind("<ButtonRelease-1>", self.stop_move)
        self.title_label.bind("<B1-Motion>", self.move)
        self.title_label.bind('<Button-3>', self.show_menu)
        self.title_entry.bind("<Return>",
                              lambda e: self.title_entry.place_forget())
        self.title_entry.bind("<FocusOut>",
                              lambda e: self.title_entry.place_forget())
        self.title_entry.bind("<Escape>",
                              lambda e: self.title_entry.place_forget())
        self.txt.tag_bind("link", "<Enter>",
                          lambda event: self.txt.configure(cursor="hand1"))
        self.txt.tag_bind("link", "<Leave>",
                          lambda event: self.txt.configure(cursor=""))
        self.txt.bind("<FocusOut>", self.save_note)
        self.txt.bind('<Button-3>', self.show_menu_txt)
        # add binding to the existing class binding so that the selected text
        # is erased on pasting
        self.txt.bind("<Control-v>", self.paste)
        self.corner.bind('<ButtonRelease-1>', self.resize)

        # --- keyboard shortcuts
        self.txt.bind('<Control-b>', lambda e: self.toggle_text_style('bold'))
        self.txt.bind('<Control-i>',
                      lambda e: self.toggle_text_style('italic'))
        self.txt.bind('<Control-u>', lambda e: self.toggle_underline())
        self.txt.bind('<Control-r>', lambda e: self.set_align('right'))
        self.txt.bind('<Control-l>', lambda e: self.set_align('left'))
Example #37
0
#format menu adding command
fontsmenu = Menu(formatmenu, tearoff=0)
formatmenu.add_cascade(label='Fonts', menu=fontsmenu)

fontlist = [
    "Arial", "Courier New", "Comic Sans MS", "Calibre", "Fixedsys",
    "MS Sans Serif", "MS Serif", "Symbol", "System", "Times New Roman",
    "Verdana"
]
font_choice = StringVar()
font_choice.set('Arial')

for f in fontlist:
    fontsmenu.add_radiobutton(label=f,
                              variable=font_choice,
                              command=Changefonts)

fontsizemenu = Menu(formatmenu, tearoff=0)
formatmenu.add_cascade(label='Font Size', menu=fontsizemenu)
fontsizelist = [i for i in range(101)]
font_size_choice = IntVar()
font_size_choice.set(14)

for f in fontsizelist:
    fontsizemenu.add_radiobutton(label=f,
                                 variable=font_size_choice,
                                 command=Changefonts)

menubar.add_cascade(label='Format', menu=formatmenu)
    def _init_menubar(self):
        self._result_size = IntVar(self.top)
        self._cntx_bf_len = IntVar(self.top)
        self._cntx_af_len = IntVar(self.top)
        menubar = Menu(self.top)

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

        editmenu = Menu(menubar, tearoff=0)
        rescntmenu = Menu(editmenu, tearoff=0)
        rescntmenu.add_radiobutton(label='20', variable=self._result_size,
                                   underline=0, value=20,
                                   command=self.set_result_size)
        rescntmenu.add_radiobutton(label='50', variable=self._result_size,
                                   underline=0, value=50,
                                   command=self.set_result_size)
        rescntmenu.add_radiobutton(label='100', variable=self._result_size,
                                   underline=0, value=100,
                                   command=self.set_result_size)
        rescntmenu.invoke(1)
        editmenu.add_cascade(label='Result Count', underline=0, menu=rescntmenu)

        cntxmenu = Menu(editmenu, tearoff=0)
        cntxbfmenu = Menu(cntxmenu, tearoff=0)
        cntxbfmenu.add_radiobutton(label='60 characters',
                                   variable=self._cntx_bf_len,
                                   underline=0, value=60,
                                   command=self.set_cntx_bf_len)
        cntxbfmenu.add_radiobutton(label='80 characters',
                                   variable=self._cntx_bf_len,
                                   underline=0, value=80,
                                   command=self.set_cntx_bf_len)
        cntxbfmenu.add_radiobutton(label='100 characters',
                                   variable=self._cntx_bf_len,
                                   underline=0, value=100,
                                   command=self.set_cntx_bf_len)
        cntxbfmenu.invoke(1)
        cntxmenu.add_cascade(label='Before', underline=0, menu=cntxbfmenu)

        cntxafmenu = Menu(cntxmenu, tearoff=0)
        cntxafmenu.add_radiobutton(label='70 characters',
                                   variable=self._cntx_af_len,
                                   underline=0, value=70,
                                   command=self.set_cntx_af_len)
        cntxafmenu.add_radiobutton(label='90 characters',
                                   variable=self._cntx_af_len,
                                   underline=0, value=90,
                                   command=self.set_cntx_af_len)
        cntxafmenu.add_radiobutton(label='110 characters',
                                   variable=self._cntx_af_len,
                                   underline=0, value=110,
                                   command=self.set_cntx_af_len)
        cntxafmenu.invoke(1)
        cntxmenu.add_cascade(label='After', underline=0, menu=cntxafmenu)

        editmenu.add_cascade(label='Context', underline=0, menu=cntxmenu)

        menubar.add_cascade(label='Edit', underline=0, menu=editmenu)

        self.top.config(menu=menubar)
Example #39
0
    def __init__(self, data, header):
        self.win = Tk()
        self.win.title("USGS Current Earthquake Data")
        self.checked = BooleanVar()
        self.checked.trace("w", self.mark_checked)
        self.sortOption = StringVar()
        self.sortOption.set("1")
        self.sortOption.trace("w", self.mark_sortOption)

        # ----- Menu Bar - Create the Menu Bar -------------------------
        menuBar = Menu()
        self.win.config(menu=menuBar)
        fileMenu = Menu(menuBar, tearoff=False)
        dataMenu = Menu(menuBar, tearoff=False)
        optionsMenu = Menu(menuBar, tearoff=False)
        helpMenu = Menu(menuBar, tearoff=False)
        menuBar.add_cascade(menu=fileMenu, label="File")
        menuBar.add_cascade(menu=dataMenu, label="Data")
        menuBar.add_cascade(menu=optionsMenu, label="Options")
        menuBar.add_cascade(menu=helpMenu, label="Help")
        # ----- Menu Bar - Create the File Menu ------------------------
        fileMenu.add_separator()
        fileMenu.add_command(label="Exit", command=self._quit)
        # ----- Menu Bar - Create the Options Menu ---------------------
        sortSubMenu = Menu(optionsMenu, tearoff=False)
        optionsMenu.add_cascade(menu=sortSubMenu, label="Sort")
        sortSubMenu.add_radiobutton(label="Sort by Magnitude",
                                    value="1",
                                    variable=self.sortOption)
        sortSubMenu.add_radiobutton(
            label="Sort by Predictive damage or Shake(MMI)",
            value="2",
            variable=self.sortOption)
        # ----- Menu Bar - Create the Data Menu-------------------------
        dataMenu.add_command(label="Refresh current Data source",
                             command=self._refreshData)
        dataMenu.add_separator()
        dataSubMenu = Menu(dataMenu, tearoff=False)
        dataMenu.add_cascade(menu=dataSubMenu, label="New Data Source")
        # ----- Menu Bar - Create the Data submenu ---------------------
        d1 = [
            ["Significant", "significant"],
            ["Magnitude 4.5+", "4.5"],
            ["Magnitude 2.5+", "2.5"],
            ["Magnitude 1.0+", "1.0"],
            ["All Earthquakes+", "all"],
        ]
        d2 = [
            ["hour", "hour"],
            ["day", "day"],
            ["7 days", "week"],
            ["30 days", "month"],
        ]
        for i in range(len(d2)):
            for j in range(len(d1)):
                s1 = str(d1[j][0] + ", past " + d2[i][0])
                s2 = str(d1[j][1] + "_" + d2[i][1])
                dataSubMenu.add_command(
                    label=s1,
                    command=lambda widget=s2: self.getNewData(widget))
                if j == (len(d1) - 1) and i != (len(d2) - 1):
                    dataSubMenu.add_separator()
        # ----- Set up frames and subframes to store widgets -----------
        self.mainFrame = ttk.LabelFrame()
        self.headings_frame = ttk.LabelFrame(self.mainFrame)
        self.headings_frame.grid(row=0)
        self.selection_frame = ttk.LabelFrame(self.headings_frame,
                                              text="selection frame")
        self.selection_frame.configure(text=header["title"])
        self.selection_frame.grid(column=0, columnspan=2, row=0, sticky="NW")
        self.file_frame = ttk.LabelFrame(self.headings_frame, text="File Info")
        self.file_frame.grid(column=2, row=0, rowspan=3, sticky="NW")
        self.details_frame = ttk.LabelFrame(self.mainFrame)
        self.details_frame.grid(row=1)
        self.summary_frame = ttk.LabelFrame(self.details_frame,
                                            text="Event Details")
        self.summary_frame.grid(row=0, columnspan=2)
        self.location_frame = ttk.LabelFrame(self.details_frame,
                                             text="Event Location")
        self.location_frame.grid(row=1, column=0, sticky="NW")
        self.time_frame = ttk.LabelFrame(self.details_frame,
                                         text="Time of Event")
        self.time_frame.grid(row=1, column=1, sticky="NW")
        ttk.Label(self.selection_frame).grid(column=0, row=0, sticky="W")
        # ----- Set up combo box and data to populate it ---------------
        self.summarySelected = ttk.Combobox(self.selection_frame,
                                            width=85,
                                            state="readonly")
        self.summarySelected.grid(column=0, row=1)
        self.updateComboBoxData(data)
        # ----- Add File widget - File delta ---------------------------
        self.fileDelta = StringVar()
        fileDeltaEntry = ttk.Label(self.file_frame,
                                   width=25,
                                   textvariable=self.fileDelta,
                                   state="readonly")
        fileDeltaEntry.grid(column=1, row=0, columnspan=2, sticky="W")
        # ----- Add File widget - File Time ----------------------------
        ttk.Label(self.file_frame, text="File Time:").grid(column=0,
                                                           row=1,
                                                           sticky="E")
        self.fileTime = StringVar()
        fileTimeEntry = ttk.Label(self.file_frame,
                                  width=25,
                                  textvariable=self.fileTime,
                                  state="readonly")
        fileTimeEntry.grid(column=1, row=1, sticky="W")
        # ----- Add File widget - Event count --------------------------
        ttk.Label(self.file_frame, text="Count:").grid(column=0,
                                                       row=2,
                                                       sticky="E")
        self.fileCount = StringVar()
        fileCountEntry = ttk.Label(self.file_frame,
                                   width=25,
                                   textvariable=self.fileCount,
                                   state="readonly")
        fileCountEntry.grid(column=1, row=2, sticky="W")
        # ----- Add Summary widget - Magnitude -------------------------
        ttk.Label(self.summary_frame, text="Magnitude:").grid(column=0,
                                                              row=0,
                                                              sticky="E")
        self.mag = StringVar()
        magEntry = ttk.Label(self.summary_frame,
                             width=7,
                             textvariable=self.mag,
                             state="readonly")
        magEntry.grid(column=1, row=0, sticky="W")
        # ----- Add Summary widget - Alert -----------------------------
        ttk.Label(self.summary_frame, text="Alert:").grid(column=2,
                                                          row=0,
                                                          sticky="E")
        self.alert = StringVar()
        alertEntry = ttk.Label(self.summary_frame,
                               width=7,
                               textvariable=self.alert,
                               state="readonly")
        alertEntry.grid(column=3, row=0, sticky="W")
        # ----- Add Summary widget - Shake -----------------------------
        ttk.Label(self.summary_frame, text="Shake (MMI):").grid(column=4,
                                                                row=0,
                                                                sticky="E")
        self.shake = StringVar()
        shakeEntry = ttk.Label(self.summary_frame,
                               width=7,
                               textvariable=self.shake,
                               state="readonly")
        shakeEntry.grid(column=5, row=0, sticky="W")
        # ----- Add Summary widget - Report Felt -----------------------
        ttk.Label(self.summary_frame, text="Reported felt:").grid(column=6,
                                                                  row=0,
                                                                  sticky="E")
        self.felt = StringVar()
        feltEntry = ttk.Label(self.summary_frame,
                              width=7,
                              textvariable=self.felt,
                              state="readonly")
        feltEntry.grid(column=7, row=0, sticky="W")
        # ----- Add Summary widget - Url/More Info ---------------------
        ttk.Label(self.summary_frame, text="More info:").grid(column=0,
                                                              row=1,
                                                              sticky="E")
        self.urlName = StringVar()
        self.urlEntry = ttk.Button(self.summary_frame)
        self.urlEntry.grid(column=1, row=1, columnspan=8, sticky="W")
        # ----- Add Location widget - Place ----------------------------
        ttk.Label(self.location_frame, text="Place:").grid(column=0,
                                                           row=4,
                                                           sticky="E")
        self.place = StringVar()
        locEntry = ttk.Label(self.location_frame,
                             width=45,
                             textvariable=self.place,
                             state="readonly")
        locEntry.grid(column=1, row=4, sticky="W")
        # ----- Add Location widget - Latitude -------------------------
        ttk.Label(self.location_frame, text="Latitude:").grid(column=0,
                                                              row=10,
                                                              sticky="E")
        self.lat = StringVar()
        latEntry = ttk.Label(self.location_frame,
                             width=25,
                             textvariable=self.lat,
                             state="readonly")
        latEntry.grid(column=1, row=10, sticky="W")
        # ----- Add Location widget - Longitude ------------------------
        ttk.Label(self.location_frame, text="Longitude:").grid(column=0,
                                                               row=11,
                                                               sticky="E")
        self.lon = StringVar()
        longEntry = ttk.Label(self.location_frame,
                              width=25,
                              textvariable=self.lon,
                              state="readonly")
        longEntry.grid(column=1, row=11, sticky="W")
        # ----- Add Location widget - Depth ----------------------------
        ttk.Label(self.location_frame, text="Depth:").grid(column=0,
                                                           row=12,
                                                           sticky="E")
        self.depth = StringVar()
        depthEntry = ttk.Label(self.location_frame,
                               width=25,
                               textvariable=self.depth,
                               state="readonly")
        depthEntry.grid(column=1, row=12, sticky="W")
        # ----- Add Time widget - Event delta --------------------------
        self.deltaEntry = StringVar()
        deltaEntry = ttk.Label(self.time_frame,
                               width=25,
                               textvariable=self.deltaEntry,
                               state="readonly")
        deltaEntry.grid(column=1, row=0, sticky="W")
        # ----- Add Time widget - Event Time ---------------------------
        ttk.Label(self.time_frame, text="Time:").grid(column=0,
                                                      row=1,
                                                      sticky="E")
        self.time = StringVar()
        timeEntry = ttk.Label(self.time_frame,
                              width=25,
                              textvariable=self.time,
                              state="readonly")
        timeEntry.grid(column=1, row=1, sticky="W")
        # ----- Add Time widget - Event Local Time ---------------------
        ttk.Label(self.time_frame, text="Your local time:").grid(column=0,
                                                                 row=2,
                                                                 sticky="E")
        self.tz = StringVar()
        tzEntry = ttk.Label(self.time_frame,
                            width=25,
                            textvariable=self.tz,
                            state="readonly")
        tzEntry.grid(column=1, row=2, sticky="W")
        # ----- Add padding around fields
        self.mainFrame.grid_configure(padx=8, pady=4)
        for child in self.mainFrame.winfo_children():
            child.grid_configure(padx=8, pady=4)
            for grandChild in child.winfo_children():
                grandChild.grid_configure(padx=8, pady=4)
                for widget in grandChild.winfo_children():
                    widget.grid_configure(padx=8, pady=4)

        # ----- Call funtion to update fields --------------------------
        data = self.sortData(data)
        self.updateHeaderFields(header)
        self.updateFields(data, self.summarySelected.current())
Example #40
0
    def _init_menubar(self):
        self._result_size = IntVar(self.top)
        self._cntx_bf_len = IntVar(self.top)
        self._cntx_af_len = IntVar(self.top)
        menubar = Menu(self.top)

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

        editmenu = Menu(menubar, tearoff=0)
        rescntmenu = Menu(editmenu, tearoff=0)
        rescntmenu.add_radiobutton(
            label="20",
            variable=self._result_size,
            underline=0,
            value=20,
            command=self.set_result_size,
        )
        rescntmenu.add_radiobutton(
            label="50",
            variable=self._result_size,
            underline=0,
            value=50,
            command=self.set_result_size,
        )
        rescntmenu.add_radiobutton(
            label="100",
            variable=self._result_size,
            underline=0,
            value=100,
            command=self.set_result_size,
        )
        rescntmenu.invoke(1)
        editmenu.add_cascade(label="Result Count",
                             underline=0,
                             menu=rescntmenu)

        cntxmenu = Menu(editmenu, tearoff=0)
        cntxbfmenu = Menu(cntxmenu, tearoff=0)
        cntxbfmenu.add_radiobutton(
            label="60 characters",
            variable=self._cntx_bf_len,
            underline=0,
            value=60,
            command=self.set_cntx_bf_len,
        )
        cntxbfmenu.add_radiobutton(
            label="80 characters",
            variable=self._cntx_bf_len,
            underline=0,
            value=80,
            command=self.set_cntx_bf_len,
        )
        cntxbfmenu.add_radiobutton(
            label="100 characters",
            variable=self._cntx_bf_len,
            underline=0,
            value=100,
            command=self.set_cntx_bf_len,
        )
        cntxbfmenu.invoke(1)
        cntxmenu.add_cascade(label="Before", underline=0, menu=cntxbfmenu)

        cntxafmenu = Menu(cntxmenu, tearoff=0)
        cntxafmenu.add_radiobutton(
            label="70 characters",
            variable=self._cntx_af_len,
            underline=0,
            value=70,
            command=self.set_cntx_af_len,
        )
        cntxafmenu.add_radiobutton(
            label="90 characters",
            variable=self._cntx_af_len,
            underline=0,
            value=90,
            command=self.set_cntx_af_len,
        )
        cntxafmenu.add_radiobutton(
            label="110 characters",
            variable=self._cntx_af_len,
            underline=0,
            value=110,
            command=self.set_cntx_af_len,
        )
        cntxafmenu.invoke(1)
        cntxmenu.add_cascade(label="After", underline=0, menu=cntxafmenu)

        editmenu.add_cascade(label="Context", underline=0, menu=cntxmenu)

        menubar.add_cascade(label="Edit", underline=0, menu=editmenu)

        self.top.config(menu=menubar)
Example #41
0
    def __init__(self, file=None):
        Tk.__init__(self, className="Sudoku-Tk")
        self.title("Sudoku-Tk")
        self.resizable(0, 0)
        self.protocol("WM_DELETE_WINDOW", self.quitter)
        cst.set_icon(self)
        self.columnconfigure(3, weight=1)

        # --- style
        bg = '#dddddd'
        activebg = '#efefef'
        pressedbg = '#c1c1c1'
        lightcolor = '#ededed'
        darkcolor = '#cfcdc8'
        bordercolor = '#888888'
        focusbordercolor = '#5E5E5E'
        disabledfg = '#999999'
        disabledbg = bg

        button_style_config = {'bordercolor': bordercolor,
                               'background': bg,
                               'lightcolor': lightcolor,
                               'darkcolor': darkcolor}

        button_style_map = {'background': [('active', activebg),
                                           ('disabled', disabledbg),
                                           ('pressed', pressedbg)],
                            'lightcolor': [('pressed', darkcolor)],
                            'darkcolor': [('pressed', lightcolor)],
                            'bordercolor': [('focus', focusbordercolor)],
                            'foreground': [('disabled', disabledfg)]}

        style = Style(self)
        style.theme_use(cst.STYLE)
        style.configure('TFrame', background=bg)
        style.configure('TLabel', background=bg)
        style.configure('TScrollbar', gripcount=0, troughcolor=pressedbg,
                        **button_style_config)
        style.map('TScrollbar', **button_style_map)
        style.configure('TButton', **button_style_config)
        style.map('TButton', **button_style_map)
        style.configure('TCheckutton', **button_style_config)
        style.map('TCheckutton', **button_style_map)
        self.option_add('*Toplevel.background', bg)
        self.option_add('*Menu.background', bg)
        self.option_add('*Menu.activeBackground', activebg)
        self.option_add('*Menu.activeForeground', "black")
        self.configure(bg=bg)

        style.configure("bg.TFrame", background="grey")
        style.configure("case.TFrame", background="white")
        style.configure("case.TLabel", background="white", foreground="black")
        style.configure("case_init.TFrame", background="lightgrey")
        style.configure("case_init.TLabel", background="lightgrey", foreground="black")
        style.configure("erreur.TFrame", background="white")
        style.configure("erreur.TLabel", background="white", foreground="red")
        style.configure("solution.TFrame", background="white")
        style.configure("solution.TLabel", background="white", foreground="blue")
        style.configure("pause.TLabel", foreground="grey", background='white')

        # --- images
        self.im_erreur = open_image(cst.ERREUR)
        self.im_pause = open_image(cst.PAUSE)
        self.im_restart = open_image(cst.RESTART)
        self.im_play = open_image(cst.PLAY)
        self.im_info = open_image(cst.INFO)
        self.im_undo = open_image(cst.UNDO)
        self.im_redo = open_image(cst.REDO)
        self.im_question = open_image(cst.QUESTION)

        # --- timer
        self.chrono = [0, 0]
        self.tps = Label(self, text=" %02i:%02i" % tuple(self.chrono),
                         font="Arial 16")
        self.debut = False  # la partie a-t-elle commencée ?
        self.chrono_on = False  # le chrono est-il en marche ?

        # --- buttons
        self.b_pause = Button(self, state="disabled", image=self.im_pause,
                              command=self.play_pause)
        self.b_restart = Button(self, state="disabled", image=self.im_restart,
                                command=self.recommence)
        self.b_undo = Button(self, image=self.im_undo, command=self.undo)
        self.b_redo = Button(self, image=self.im_redo, command=self.redo)

        # --- tooltips
        self.tooltip_wrapper = TooltipWrapper(self)
        self.tooltip_wrapper.add_tooltip(self.b_pause, _("Pause game"))
        self.tooltip_wrapper.add_tooltip(self.b_restart, _("Restart game"))
        self.tooltip_wrapper.add_tooltip(self.b_undo, _("Undo"))
        self.tooltip_wrapper.add_tooltip(self.b_redo, _("Redo"))

        # --- numbers
        frame_nb = Frame(self, style='bg.TFrame', width=36)
        self.progression = []
        for i in range(1, 10):
            self.progression.append(Progression(frame_nb, i))
            self.progression[-1].pack(padx=1, pady=1)

        # --- level indication
        frame = Frame(self)
        frame.grid(row=0, columnspan=5, padx=(30, 10), pady=10)
        Label(frame, text=_("Level") + ' - ', font="Arial 16").pack(side='left')
        self.label_level = Label(frame, font="Arial 16", text=_("Unknown"))
        self.label_level.pack(side='left')
        self.level = "unknown"  # puzzle level

        # --- frame contenant la grille de sudoku
        self.frame_puzzle = Frame(self, style="bg.TFrame")
        self.frame_pause = Frame(self, style="case.TFrame")
        self.frame_pause.grid_propagate(False)
        self.frame_pause.columnconfigure(0, weight=1)
        self.frame_pause.rowconfigure(0, weight=1)
        Label(self.frame_pause, text='PAUSE', style='pause.TLabel',
              font='Arial 30 bold').grid()

        # --- placement
        frame_nb.grid(row=1, column=6, sticky='en', pady=0, padx=(0, 30))
        self.frame_puzzle.grid(row=1, columnspan=5, padx=(30, 15))
        self.tps.grid(row=2, column=0, sticky="e", padx=(30, 10), pady=30)
        self.b_pause.grid(row=2, column=1, sticky="w", padx=2, pady=30)
        self.b_restart.grid(row=2, column=2, sticky="w", padx=2, pady=30)
        self.b_undo.grid(row=2, column=3, sticky="e", pady=30, padx=2)
        self.b_redo.grid(row=2, column=4, sticky="w", pady=30, padx=(2, 10))

        # --- menu
        menu = Menu(self, tearoff=0)

        menu_nouveau = Menu(menu, tearoff=0)

        menu_levels = Menu(menu_nouveau, tearoff=0)
        menu_levels.add_command(label=_("Easy"), command=self.new_easy)
        menu_levels.add_command(label=_("Medium"), command=self.new_medium)
        menu_levels.add_command(label=_("Difficult"), command=self.new_difficult)

        menu_nouveau.add_cascade(label=_("Level"), menu=menu_levels)
        menu_nouveau.add_command(label=_("Generate a puzzle"),
                                 command=self.genere_grille,
                                 accelerator="Ctrl+G")
        menu_nouveau.add_command(label=_("Empty grid"),
                                 command=self.grille_vide,
                                 accelerator="Ctrl+N")

        menu_ouvrir = Menu(menu, tearoff=0)
        menu_ouvrir.add_command(label=_("Game"), command=self.import_partie,
                                accelerator="Ctrl+O")
        menu_ouvrir.add_command(label=_("Puzzle"), command=self.import_grille,
                                accelerator="Ctrl+Shift+O")

        menu_game = Menu(menu, tearoff=0)
        menu_game.add_command(label=_("Restart"), command=self.recommence)
        menu_game.add_command(label=_("Solve"), command=self.resolution)
        menu_game.add_command(label=_("Save"), command=self.sauvegarde,
                              accelerator="Ctrl+S")
        menu_game.add_command(label=_("Export"), command=self.export_impression,
                              accelerator="Ctrl+E")
        menu_game.add_command(label=_("Evaluate level"),
                              command=self.evaluate_level)

        menu_language = Menu(menu, tearoff=0)
        self.langue = StringVar(self)
        self.langue.set(cst.LANGUE[:2])
        menu_language.add_radiobutton(label="Français",
                                      variable=self.langue,
                                      value="fr", command=self.translate)
        menu_language.add_radiobutton(label="English", variable=self.langue,
                                      value="en", command=self.translate)

        menu_help = Menu(menu, tearoff=0)
        menu_help.add_command(label=_("Help"), command=self.aide, accelerator='F1')
        menu_help.add_command(label=_("About"), command=self.about)

        menu.add_cascade(label=_("New"), menu=menu_nouveau)
        menu.add_cascade(label=_("Open"), menu=menu_ouvrir)
        menu.add_cascade(label=_("Game"), menu=menu_game)
        menu.add_cascade(label=_("Language"), menu=menu_language)
        menu.add_command(label=_("Statistics"), command=self.show_stat)
        menu.add_cascade(label=_("Help"), menu=menu_help)

        self.configure(menu=menu)

        # --- clavier popup
        self.clavier = None

        # --- cases
        self.nb_cases_remplies = 0
        self.blocs = np.zeros((9, 9), dtype=object)
        for i in range(9):
            for j in range(9):
                self.blocs[i, j] = Case(self.frame_puzzle, i, j, self.update_nbs, width=50, height=50)
                px, py = 1, 1
                if i % 3 == 2 and i != 8:
                    py = (1, 3)
                if j % 3 == 2 and j != 8:
                    px = (1, 3)
                self.blocs[i, j].grid(row=i, column=j, padx=px, pady=py)
                self.blocs[i, j].grid_propagate(0)

        # --- undo/redo stacks
        self._undo_stack = []
        self._redo_stack = []

        # --- raccourcis clavier et actions de la souris
        self.bind("<Button>", self.edit_case)
        self.bind("<Control-z>", lambda e: self.undo())
        self.bind("<Control-y>", lambda e: self.redo())
        self.bind("<Control-s>", lambda e: self.sauvegarde())
        self.bind("<Control-e>", lambda e: self.export_impression())
        self.bind("<Control-o>", lambda e: self.import_partie())
        self.bind("<Control-Shift-O>", lambda e: self.import_grille())
        self.bind("<Control-n>", lambda e: self.grille_vide())
        self.bind("<Control-g>", lambda e: self.genere_grille())
        self.bind("<FocusOut>", self.focus_out)
        self.bind("<F1>", self.aide)

        # --- open game
        if file:
            try:
                self.load_sudoku(file)
            except FileNotFoundError:
                one_button_box(self, _("Error"),
                               _("The file %(file)r does not exist.") % file,
                               image=self.im_erreur)
            except (KeyError, EOFError, UnpicklingError):
                try:
                    self.load_grille(file)
                except Exception:
                    one_button_box(self, _("Error"),
                                   _("This file is not a valid sudoku file."),
                                   image=self.im_erreur)
        elif exists(cst.PATH_SAVE):
            self.load_sudoku(cst.PATH_SAVE)
            remove(cst.PATH_SAVE)