Exemple #1
0
    def count_lines(self, s):
        """Count the number of lines in a given text.

        Before calculation, the tab width and line length of the text are
        fetched, so that up-to-date values are used.

        Lines are counted as if the string was wrapped so that lines are never
        over linewidth characters long.

        Tabs are considered tabwidth characters long.
        """
        # Tab width is configurable
        tabwidth = self.editwin.get_tk_tabwidth()

        # Get the Text widget's size
        linewidth = self.editwin.text.winfo_width()
        # Deduct the border and padding
        linewidth -= 2*sum([int(self.editwin.text.cget(opt))
                            for opt in ('border', 'padx')])

        # Get the Text widget's font
        font = Font(self.editwin.text, name=self.editwin.text.cget('font'))
        # Divide the size of the Text widget by the font's width.
        # According to Tk8.5 docs, the Text widget's width is set
        # according to the width of its font's '0' (zero) character,
        # so we will use this as an approximation.
        # see: http://www.tcl.tk/man/tcl8.5/TkCmd/text.htm#M-width
        linewidth //= font.measure('0')

        return count_lines_with_wrapping(s, linewidth, tabwidth)
Exemple #2
0
 def SyntexHighlight(self, event=None):
     from tkinter.font import Font
     for tag in self.tag_names():
         self.tag_delete(tag)
     self.mark_set("range_start", "1.0")
     data = self._get_value()
     self.tag_configure("Token.Comment", foreground="#F00")
     bolder = Font(family=self.app.cnf['font'][0])
     bolder.config(size=self.app.cnf['font'][1]-2)
     bolder.config(weight="bold")
     for token, content in lex(data, PythonLexer()):
         self.mark_set("range_end", "range_start + %dc" % len(content))
         self.tag_add(str(token), "range_start", "range_end")
         self.mark_set("range_start", "range_end")
     self.tag_config("Token.Comment.Single", foreground="#F00")
     self.tag_config("Token.Literal.String.Doc", foreground="#F00")
     for tag in self.tag_names():
         if 'Token.Keyword' == tag:
             self.tag_config(tag, foreground="#008", font=bolder)
         elif 'Token.Keyword.Namespace' == tag:
             self.tag_config(tag, foreground="#00F", font=bolder)
         elif 'Token.Name.Class' in tag:
             self.tag_config(tag, foreground="#F30", background='#AFA')
         elif 'Token.Name.Function' in tag:
             self.tag_config(tag, foreground="#A3A", background='#FFA')
         elif 'Token.Literal' in tag:
             self.tag_config(tag, foreground="#6A0")
         elif 'Token.Operator' in tag:
             self.tag_config(tag, foreground="#A3A")
     print(self.tag_names())
Exemple #3
0
        def text_extents(self, style, text):
            """
            The text extents are calculated using tkinter.Font
            """
            with InternalWindow() as window:
                font_type = ""
                if style["bold"]:
                    font_type += "bold"
                if style["italic"]:
                    if len(font_type) > 0:
                        font_type += " "
                    font_type += "italic"

                # Create the new font object.
                font = Font(window, (style["font"], -int(style["size"]*FONT_SCALING), font_type))
                # Query the data
                width = font.measure(text)
                metrics = font.metrics()

            return {
                "width": width / float(FONT_SCALING),
                "height": metrics["linespace"] / float(FONT_SCALING),
                "ascent": metrics["ascent"] / float(FONT_SCALING),
                "descent": metrics["descent"] / float(FONT_SCALING)
            }
    def initialize(self):
        #Create the menubar
        self.menubar=Menu(self)
        menu=Menu(self.menubar,tearoff=0)
        self.menubar.add_cascade(label="File",menu=menu)
        menu.add_command(label="Open",command=self.openfile)
        #menu.add_command(label="Exit")
        menu=Menu(self.menubar,tearoff=0)
        self.menubar.add_cascade(label="Tools",menu=menu)
        menu.add_command(label="Class",command=self.classwindow)
        menu.add_command(label="Hilbert",command=self.hilbertwindow)
        menu.add_command(label="Entropy",command=self.entropywindow)
        menu.add_command(label="Gradient",command=self.gradientwindow)
        self.master.config(menu=self.menubar)

        #Configure grid layout
        self.columnconfigure(0,pad=5)
        self.columnconfigure(1,pad=5)
        self.columnconfigure(2,pad=5)
        self.rowconfigure(0,pad=5)
        self.rowconfigure(0,pad=5)

        #Add canvas to plot points from converted hex values
        self.plotcanvas=Canvas(self,width=256,height=256)
        self.plotcanvas.configure(background='black')
        self.plotcanvas.grid(row=0,column=0)

        #Add listbox to hold the current group of hexvalues
        listframe=Frame(self)
        hexscroll=Scrollbar(listframe,orient=VERTICAL)
        hexbox_font = Font(size=8)
        hexbox_font.config(family={"posix": "Monospace","nt": "Courier New"})
        self.hexbox=Listbox(listframe,width=75,height=20,font=hexbox_font,yscrollcommand=hexscroll.set,selectmode=EXTENDED)
        hexscroll.config(command=self.hexbox.yview)
        hexscroll.pack(side=RIGHT,fill=Y)
        self.hexbox.pack(side=LEFT)
        listframe.grid(row=0,column=1)

        #Add slider for location in hex lines and size of window of hex values
        commandframe=Frame(self)
        playframe=Frame(commandframe)
        windowframe=Frame(commandframe)
        self.playslider=Scale(playframe,command=self.playslider_moved)
        self.playslider.configure(from_=0,to=100)
        self.playslider.configure(orient=HORIZONTAL)
        self.playslider.pack(side=BOTTOM)
        hexaddress=gethexaddress(int(self.playslider.get()))
        self.currhexaddress=Label(playframe,width=20,text=hexaddress)
        self.currhexaddress.pack(side=TOP)
        self.curroffset=Label(windowframe,text=self.hexaddressoffset)
        self.curroffset.pack(side=TOP)
        self.windowslider=Scale(windowframe,command=self.windowslider_moved)
        self.windowslider.configure(from_=100,to=600,orient=HORIZONTAL)
        self.windowslider.pack(side=TOP)
        self.windowslider.set(self.hexaddressoffset)
        playframe.pack(side=LEFT)
        windowframe.pack(side=RIGHT)
        commandframe.grid(row=1,columnspan=2)

        self.pack()
Exemple #5
0
 def adjust_fonts(self, event):
   new_font = Font(**self.fonts['normal'].configure())
   size = orig_size = new_font['size']
   desired_total_height = event.height
   orig_row_height = new_font.metrics('linespace')
   orig_row_height += self.LS_EXTRA
   orig_total_height = self.N_ROWS * orig_row_height
   if orig_total_height < desired_total_height:
     a, compfname, final_neg_adjust = 1, '__gt__', True
   elif orig_total_height > desired_total_height:
     a, compfname, final_neg_adjust = -1, '__lt__', False
   else:
     return
   prev_total_height = orig_total_height
   while True:
     if a < 0 and size <= self.MIN_FONT_SIZE:
       size = self.MIN_FONT_SIZE
       break
     size += a
     new_font.configure(size=size)
     new_row_height = new_font.metrics('linespace')
     new_row_height += self.LS_EXTRA
     new_total_height = self.N_ROWS * new_row_height
     if new_total_height == prev_total_height:
       size -= a
       break
     compf = getattr(new_total_height, compfname)
     if compf(desired_total_height):
       if final_neg_adjust and size > self.MIN_FONT_SIZE:
         size -= a
       break
     prev_total_height = new_total_height
   if size != orig_size:
     self.fonts['normal'].configure(size=size)
     self.fonts['bold'].configure(size=size)
Exemple #6
0
 def overstrike(self, *args):
     """Toggles overstrike for selected text."""
     try:
         current_tags = self.text.tag_names("sel.first")
         if "overstrike" in current_tags:
             self.text.tag_remove("overstrike", "sel.first", "sel.last")
         else:
             self.text.tag_add("overstrike", "sel.first", "sel.last")
             overstrike_font = Font(self.text, self.text.cget("font"))
             overstrike_font.configure(overstrike=1)
             self.text.tag_configure("overstrike", font=overstrike_font)
     except TclError:
         pass
Exemple #7
0
 def underline(self, *args):
     """Toggles underline for selected text."""
     try:
         current_tags = self.text.tag_names("sel.first")
         if "underline" in current_tags:
             self.text.tag_remove("underline", "sel.first", "sel.last")
         else:
             self.text.tag_add("underline", "sel.first", "sel.last")
             underline_font = Font(self.text, self.text.cget("font"))
             underline_font.configure(underline=1)
             self.text.tag_configure("underline", font=underline_font)
     except TclError:
         pass
Exemple #8
0
 def italic(self, *args):
     """Toggles italic for selected text."""
     try:
         current_tags = self.text.tag_names("sel.first")
         if "italic" in current_tags:
             self.text.tag_remove("italic", "sel.first", "sel.last")
         else:
             self.text.tag_add("italic", "sel.first", "sel.last")
             italic_font = Font(self.text, self.text.cget("font"))
             italic_font.configure(slant="italic")
             self.text.tag_configure("italic", font=italic_font)
     except TclError:
         pass
Exemple #9
0
 def bold(self, *args):
     """Toggles bold for selected text."""
     try:
         current_tags = self.text.tag_names("sel.first")
         if "bold" in current_tags:
             self.text.tag_remove("bold", "sel.first", "sel.last")
         else:
             self.text.tag_add("bold", "sel.first", "sel.last")
             bold_font = Font(self.text, self.text.cget("font"))
             bold_font.configure(weight="bold")
             self.text.tag_configure("bold", font=bold_font)
     except TclError:
         pass
Exemple #10
0
    def GetFont(self, root, configType, section):
        """Retrieve a font from configuration (font, font-size, font-bold)
        Intercept the special value 'TkFixedFont' and substitute
        the actual font, factoring in some tweaks if needed for
        appearance sakes.

        The 'root' parameter can normally be any valid Tkinter widget.

        Return a tuple (family, size, weight) suitable for passing
        to tkinter.Font
        """
        family = self.GetOption(configType, section, 'font', default='courier')
        size = self.GetOption(configType, section, 'font-size', type='int',
                              default='10')
        bold = self.GetOption(configType, section, 'font-bold', default=0,
                              type='bool')
        if (family == 'TkFixedFont'):
            f = Font(name='TkFixedFont', exists=True, root=root)
            actualFont = Font.actual(f)
            family = actualFont['family']
            size = actualFont['size']
            if size <= 0:
                size = 10  # if font in pixels, ignore actual size
            bold = actualFont['weight'] == 'bold'
        return (family, size, 'bold' if bold else 'normal')
Exemple #11
0
 def __init__(self, wdw, sols):
     """
     Stores the list of solutions in sols
     and defines the layout of the GUI.
     """
     wdw.title('solutions scroller')
     self.sols = sols
     self.cursor = 0
     self.lbl = Label(wdw, text="solution : ")
     self.lbl.grid(row=0, column=0, sticky=E) 
     self.ent = Entry(wdw)
     self.ent.grid(row=0, column=1, stick=W)
     self.ent.insert(INSERT, "0 of %d" % len(sols))
     self.myft = Font(family="Courier New", size=12, weight="normal")
     self.mlen = self.myft.measure("M")
     lines = sols[0].split('\n')
     self.width = max([len(line) for line in lines])
     self.display = StringVar()
     self.display.set(self.sols[0])
     self.mess = Message(wdw, textvariable=self.display, \
         font=self.myft, width=self.width*self.mlen, background='white')
     self.mess.grid(row=1, column=0, columnspan=2)
     self.btnext = Button(wdw, command=self.next, text='next')
     self.btnext.grid(row=2, column=1, sticky=W+E)
     self.btprev = Button(wdw, command=self.previous, text='previous')
     self.btprev.grid(row=2, column=0, sticky=W+E)
    def _init_fonts(self, root):
        # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html>
        self._sysfont = Font(font=Button()["font"])
        root.option_add("*Font", self._sysfont)

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

        self._boldfont = Font(family="helvetica", weight="bold", size=self._size.get())
        self._font = Font(family="helvetica", size=self._size.get())
        if self._size.get() < 0:
            big = self._size.get() - 2
        else:
            big = self._size.get() + 2
        self._bigfont = Font(family="helvetica", weight="bold", size=big)
Exemple #13
0
    def GetFont(self, root, configType, section):
        """Retrieve a font from configuration (font, font-size, font-bold)
        Intercept the special value 'TkFixedFont' and substitute
        the actual font, factoring in some tweaks if needed for
        appearance sakes.

        The 'root' parameter can normally be any valid Tkinter widget.

        Return a tuple (family, size, weight) suitable for passing
        to tkinter.Font
        """
        family = self.GetOption(configType, section, "font", default="courier")
        size = self.GetOption(configType, section, "font-size", type="int", default="10")
        bold = self.GetOption(configType, section, "font-bold", default=0, type="bool")
        if family == "TkFixedFont":
            if TkVersion < 8.5:
                family = "Courier"
            else:
                f = Font(name="TkFixedFont", exists=True, root=root)
                actualFont = Font.actual(f)
                family = actualFont["family"]
                size = actualFont["size"]
                if size < 0:
                    size = 10  # if font in pixels, ignore actual size
                bold = actualFont["weight"] == "bold"
        return (family, size, "bold" if bold else "normal")
Exemple #14
0
class Scroller(object):
    """
    Scrolls through a solution list.
    """
    def __init__(self, wdw, sols):
        """
        Stores the list of solutions in sols
        and defines the layout of the GUI.
        """
        wdw.title('solutions scroller')
        self.sols = sols
        self.cursor = 0
        self.lbl = Label(wdw, text="solution : ")
        self.lbl.grid(row=0, column=0, sticky=E) 
        self.ent = Entry(wdw)
        self.ent.grid(row=0, column=1, stick=W)
        self.ent.insert(INSERT, "0 of %d" % len(sols))
        self.myft = Font(family="Courier New", size=12, weight="normal")
        self.mlen = self.myft.measure("M")
        lines = sols[0].split('\n')
        self.width = max([len(line) for line in lines])
        self.display = StringVar()
        self.display.set(self.sols[0])
        self.mess = Message(wdw, textvariable=self.display, \
            font=self.myft, width=self.width*self.mlen, background='white')
        self.mess.grid(row=1, column=0, columnspan=2)
        self.btnext = Button(wdw, command=self.next, text='next')
        self.btnext.grid(row=2, column=1, sticky=W+E)
        self.btprev = Button(wdw, command=self.previous, text='previous')
        self.btprev.grid(row=2, column=0, sticky=W+E)

    def show(self):
        """
        Shows the solution at position self.cursor
        in the message widget and updates the entry widget.
        """
        self.display.set(self.sols[self.cursor])
        self.ent.delete(0, END)
        self.ent.insert(INSERT, '%d of %d' % (self.cursor, len(self.sols)))

    def next(self):
        """
        Increases the cursor by one if possible.
        """
        if self.cursor < len(self.sols) - 1:
            self.cursor = self.cursor + 1
        self.show()

    def previous(self):
        """
        Decreases the cursor by one if possible.
        """
        if self.cursor > 0:
            self.cursor = self.cursor - 1
        self.show()
Exemple #15
0
 def __init__(self, master):
     BaseDiablog.__init__(self, master, "Preferences", exit_on_esc=True)
     self.startup_check = Config.config["startup_check"]
     self.general_label = ttk.Label(self.body,
                                    text="General")
     font = Font(self.general_label, self.general_label.cget("font"))
     font.configure(underline=True)
     self.general_label.configure(font=font)
     self.config_frame = ttk.Frame(self)
     self.startup_check_checkbtn = ttk.Checkbutton(self.config_frame,
                                                   text="Check for update at launch",
                                                   variable=PreferencesDialog.startup_check.raw_klass(self),
                                                   command=self._startup_check_clicked)
     self.buttons_frame = ttk.Frame(self)
     self.close_button = ttk.Button(self.buttons_frame,
                                    text="Close",
                                    command=self.destroy)
     options = dict(padx=5, pady=5)
     self.general_label.pack(side=LEFT, **options)
     self.config_frame.pack(fill=BOTH, expand=True, **options)
     self.startup_check_checkbtn.pack(side=LEFT, **options)
     self.buttons_frame.pack(side=BOTTOM, fill=BOTH, expand=True, **options)
     self.close_button.pack(side=RIGHT, expand=False)
Exemple #16
0
 def define_appearance(self):
     self.height = 22
     self.minwidth = 130
     self.maxwidth = 300
     self.addiconwidth = 24
     self.gapwidth = 15
     self.bg = '#c4c4c4'
     self.selbg = '#d3d3d3'
     self.dividerbg = '#b0b0b0'
     self.textcolor = '#424242'
     self.holecolor = '#eeeeee'
     self.titlefont = Font(name='TkTooltipFont', exists=True,
                           root=self.parent)
     self.tooltipfont = Font(name='TkTooltipFont', exists=True,
                             root=self.parent)
     self.plusfont = Font(name='TkMenuFont', exists=True, root=self.parent)
Exemple #17
0
    def test_get_font(self):
        from test.support import requires
        from tkinter import Tk
        from tkinter.font import Font
        conf = self.mock_config()

        requires('gui')
        root = Tk()
        root.withdraw()

        f = Font.actual(Font(name='TkFixedFont', exists=True, root=root))
        self.assertEqual(
            conf.GetFont(root, 'main', 'EditorWindow'),
            (f['family'], 10 if f['size'] <= 0 else f['size'], f['weight']))

        # Cleanup root
        root.destroy()
        del root
Exemple #18
0
    def __init__(self, master=None, **cnf):
        ScrolledText.__init__(self, master, **cnf)

        bold = Font(font=self['font']).copy()
        bold.config(weight='bold')
        italic = Font(font=self['font']).copy()
        italic.config(slant='italic')

        # Define tags for formatting styles
        self.tag_config('X', underline=1)
        self.tag_config('!', font=bold)
        self.tag_config('_', font=italic)

        # Set state to idle
        self.fp = None
        self.lineno = 0
    def __init__(self, master, client, queue, send_command):
        super(ClientUI, self).__init__()
        self.client = client
        self.queue = queue
        self.send_command = send_command
        self.master = master
        self.plugin_manager = PluginManager(self.send_command_with_prefs, self.echo)
        self.interrupt_input = False
        self.interrupt_buffer = deque()
        self.input_buffer = []
        self.input_cursor = 0
        self.list_depth = 0
        self.MAP_OFFSET = 60

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

        self.create_plugin_menu(menu_bar)

        self.master.config(menu=menu_bar)

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

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

        self.char_width = Font(self.output_panel, self.output_panel.cget("font")).measure('0')
        self.line_length = self.calc_line_length(self.output_panel.cget("width"))
        italic_font = Font(self.output_panel, self.output_panel.cget("font"))
        italic_font.configure(slant='italic')
        self.output_panel.tag_configure("italic", font=italic_font)
        bold_font = Font(self.output_panel, self.output_panel.cget("font"))
        bold_font.configure(weight='bold')
        self.output_panel.tag_configure('bold', font=bold_font)
        self.output_panel.tag_configure("center", justify=tk.CENTER)
Exemple #20
0
    def __init__(self, master, client, queue, send_command):
        super(ClientUI, self).__init__()
        self.client = client
        self.queue = queue
        self.send_command = send_command
        self.master = master
        self.interrupt_input = False
        self.interrupt_buffer = deque()
        self.input_buffer = []
        self.input_cursor = 0
        self.list_depth = 0

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

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

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

        self.char_width = Font(self.output_panel, self.output_panel.cget("font")).measure('0')
        self.line_length = self.calc_line_length(self.output_panel.cget("width"))
        italic_font = Font(self.output_panel, self.output_panel.cget("font"))
        italic_font.configure(slant='italic')
        self.output_panel.tag_configure("italic", font=italic_font)
        bold_font = Font(self.output_panel, self.output_panel.cget("font"))
        bold_font.configure(weight='bold')
        self.output_panel.tag_configure('bold', font=bold_font)
        self.output_panel.tag_configure("center", justify=tk.CENTER)
Exemple #21
0
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.geometry('+300+100')
        self.title('pyBurner')
        self.configure(bg=BGCOLOR)

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

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

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

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

        # file menu
        menubar = tk.Menu(self)
        filemenu = tk.Menu(menubar, tearoff=0)
        self.config(menu=menubar)
        filemenu.add_command(label='Open', command=self.csv_open, accelerator="Ctrl+O")
        filemenu.add_command(label='Preferences', command=self.open_preferences)
        filemenu.add_separator()
        filemenu.add_command(label='Exit', command=self.quit_app, accelerator='Ctrl+Q')
        self.bind("<Control-o>", self.csv_open)
        self.bind("<Control-q>", self.quit_app)
        menubar.add_cascade(label='File', menu=filemenu)
        self.text.clear_help()
        self.load_defaults()
Exemple #22
0
    def Make(self):
        """ Displays all of this Month's expenses. """

        # If the ExpenseFrame exists, it will be destroyed
        try:
            self.outer.destroy()
        except AttributeError as e:
            if debug: print(e.__class__, ':: ', e)
            else: pass

        # outer is created so the delete button frames can be
        # seperated visually from the expense list frame.
        self.outer = tk.Frame(self)
        self.outer.pack()

        self.Title()

        self.ExpenseFrame = tk.Frame(self.outer)
        self.ExpenseFrame.pack(fill='both')

        # Scrollbar for expense list
        scrollbar = tk.Scrollbar(self.ExpenseFrame)
        scrollbar.pack(side='right', fill='y')

        # Columns for expense list
        dataCols = ['Date', 'Expense Type', 'Cost', 'Notes']

        self.tree = ttk.Treeview(self.ExpenseFrame,
                                 columns=dataCols,
                                 show='headings')

        Exp_Attrs = self.master.Budget.expenses.get()

        # maxWidths is used to store the max width of each column in the
        # TreeView object.
        maxWidths = dict()

        # Loop sets max for each column to 0, so each max has starting value
        for col in dataCols:
            maxWidths[col] = 0

        # Defines the font that the TreeView elements will use
        treeFont = Font(self.ExpenseFrame, 'Times', "12")

        # Inserts each expense into the Treeview object
        for values in Exp_Attrs:
            self.tree.insert('', 'end', values=values, tag='expense')

            # This loop finds the width of the largest string in each column.
            for col, item in zip(dataCols, values):
                stringWidth = treeFont.measure(item)
                if stringWidth > maxWidths[col]:
                    maxWidths[col] = stringWidth

        # This loop serves two functions:
        # 1 - Sets the headings in the expense list.
        #     Without this loop, the headings will not actually show.
        #
        # 2 - Sets the width of each column based on the largest string within
        #     each column.
        for col in dataCols:
            self.tree.heading(col, text=col)
            extra = 100
            MAX = maxWidths[col] + extra
            self.tree.column(col, width=MAX)

        # Sets the font of the TreeView elements
        self.tree.tag_configure('expense', font=treeFont)

        # 'yscroll' option must be set to scrollbar set object
        self.tree['yscroll'] = scrollbar.set

        self.tree.pack(side='left', fill='both')

        # Associates scrollbar with the Treeview object
        scrollbar.config(command=self.tree.yview)

        self.CreateDeleteButton()
Exemple #23
0
class UITabs(Frame):
    def __init__(self, parent, observer):
        Frame.__init__(self, parent)
        self.parent = parent
        self.observer = observer

        self.tabs = []          # list of tab id's
        self.info = {}          # info on each tab
        self.drag = None        # state information when drag in progress
        self.current = None     # id of currently selected tab
        self.mouseover = None   # id of tab the mouse is currently over
        self.tooltip = None     # state information for tooltips
        self.last_x = -1
        self.nextid = 1

        self.define_appearance()
        self.c = Canvas(self, highlightthickness=0, borderwidth=0)
        self.c.grid(column=0, row=0, sticky='nwes')
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)
        self.c['background'] = self.bg
        self.c['height'] = self.height
        self.bind('<Configure>', self.rebuild)
        self.c.bind('<Motion>', self.mouse_moved)
        self.c.bind('<Leave>', self.leave)
        self.c.bind('<1>', self.mouse_down)
        self.c.bind('<B1-Motion>', self.mouse_dragged)
        self.c.bind('<ButtonRelease-1>', self.mouse_up)

    def add(self, tabid=None, title=None, dirty=False, tooltip=None):
        "Add a new tab"
        if tabid is None:
            while 'tab'+str(self.nextid) in self.tabs:
                self.nextid += 1
            tabid = 'tab'+str(self.nextid)
            self.nextid += 1
        if tabid in self.tabs:
            raise ValueError('tab already added')
        self.tabs.append(tabid)
        self.info[tabid] = {'title': title, 'dirty': dirty, 'tooltip': tooltip}
        self.select(tabid)
        return tabid

    def remove(self, tabid):
        "Remove an existing tab"
        if tabid not in self.tabs:
            raise ValueError('no such tab')
        self.tooltip_clear()
        idx = self.tabs.index(tabid)
        del(self.info[tabid])
        self.tabs.remove(tabid)
        if tabid == self.current:
            if len(self.tabs) == 0:
                self.current = None
            elif idx > len(self.tabs)-1:
                self.current = self.tabs[-1]
            else:
                self.current = self.tabs[idx]
            if self.current is not None:
                self.observer.tab_selected(self, self.current)
        self.update_mouseover(self.last_x)
        self.rebuild()

    def select(self, tabid):
        "Change the currently selected (frontmost) tab."
        if tabid not in self.tabs:
            raise ValueError('no such tab')
        if self.current != tabid:
            self.observer.tab_deselected(self, self.current)
            self.current = tabid
            self.rebuild()
            self.observer.tab_selected(self, self.current)

    def set_title(self, tabid, title):
        "Change the title of a tab"
        if tabid not in self.tabs:
            raise ValueError('no such tab')
        self.info[tabid]['title'] = title
        self.rebuild()

    def set_dirty(self, tabid, dirty=True):
        "Change the saved/unsaved indicator for a tab"
        if tabid not in self.tabs:
            raise ValueError('no such tab')
        self.info[tabid]['dirty'] = dirty
        self.rebuild()

    def set_tooltip(self, tabid, tooltip):
        "Change the tooltip for a tab"
        if tabid not in self.tabs:
            raise ValueError('no such tab')
        self.info[tabid]['tooltip'] = tooltip

    def mouse_moved(self, ev):
        self.last_x = ev.x
        self.update_mouseover(ev.x)

    def leave(self, ev):
        self.mouseover = None
        self.tooltip_clear()
        self.last_x = -1
        self.rebuild()

    def mouse_down(self, ev):
        self.drag_initiate(ev)

    def mouse_dragged(self, ev):
        self.drag_continue(ev)

    def mouse_up(self, ev):
        self.drag_conclude(ev)

    def define_appearance(self):
        self.height = 22
        self.minwidth = 130
        self.maxwidth = 300
        self.addiconwidth = 24
        self.gapwidth = 15
        self.bg = '#c4c4c4'
        self.selbg = '#d3d3d3'
        self.dividerbg = '#b0b0b0'
        self.textcolor = '#424242'
        self.holecolor = '#eeeeee'
        self.titlefont = Font(name='TkTooltipFont', exists=True,
                              root=self.parent)
        self.tooltipfont = Font(name='TkTooltipFont', exists=True,
                                root=self.parent)
        self.plusfont = Font(name='TkMenuFont', exists=True, root=self.parent)

    def calculate_positions(self):
        "Update state info on each tab needed for display, e.g. position"
        self.tabwidth = tabwidth = self.calculate_tabwidth()
        displayed = []
        extra = []
        xpos = 0
        # Step 1: Calculate positions for each tab that will fit on the
        #         display, and note which tabs won't fit
        for t in self.tabs:
            if xpos + tabwidth > self.winfo_width() - self.addiconwidth:
                self.info[t]['visible'] = False
                extra.append(t)
            else:
                self.info[t]['visible'] = True
                self.info[t]['left'] = xpos
                self.info[t]['shift'] = 0
                displayed.append(t)
                xpos += tabwidth
            self.info[t]['tablabel'] = self.tablabel(self.info[t]['title'],
                                                     tabwidth-40)
        # Step 2: If we're in the middle of dragging a tab, potentially
        #         to move it, we indicate a place where it can be dropped
        #         via a gap between tabs. If such a gap has been identified
        #         (see drag_identifygap), open up a space by moving all tabs
        #         to the left of the gap a bit more left, and all tabs to
        #         the right of the gap a bit more right.
        if self.drag is not None and self.drag['state'] == 'inprogress' \
                                 and self.drag['gap'] is not None:
            gap = self.drag['gap']
            tabidx = self.tabs.index(self.drag['tabid'])
            idx = 0
            for t in self.tabs:
                if self.info[t]['visible']:
                    if idx < gap:
                        self.info[t]['shift'] = -self.gapwidth
                    elif idx >= gap:
                        self.info[t]['shift'] = +self.gapwidth
                idx += 1
        # Step 3: If the currently selected tab will not fit on the screen
        #         because there are too many tabs before it on the list,
        #         swap the last displayed tab with the currently selected
        #         one, to ensure it is displayed. Note this doesn't update
        #         the actual order (in self.tabs), just display state info.
        if self.current in extra:
            last = displayed[-1]
            self.info[self.current]['visible'] = True
            self.info[self.current]['left'] = self.info[last]['left']
            self.info[self.current]['shift'] = self.info[last]['shift']
            self.info[last]['visible'] = False
            del(self.info[last]['left'])
            del(self.info[last]['shift'])
            displayed.remove(last)
            extra.insert(0, last)
            extra.remove(self.current)
            displayed.append(self.current)
        self.overflow_tab = displayed[-1] if extra else None
        self.plus_x = xpos

    def calculate_tabwidth(self):
        "Determine width of a tab, factoring in available space, etc."
        fullwidth = self.winfo_width()
        numtabs = len(self.tabs)
        if numtabs == 0:
            return -1
        tabwidth = int((fullwidth - self.addiconwidth) / numtabs)
        if tabwidth < self.minwidth:
            tabwidth = self.minwidth
        if tabwidth > self.maxwidth:
            tabwidth = self.maxwidth
        return tabwidth

    def tablabel(self, title, width):
        "Truncate any long titles that would not fit within the tab label"
        if self.titlefont.measure(title) <= width:
            return title
        dotwidth = self.titlefont.measure('...')
        while True:
            if self.titlefont.measure(title+'...') <= width:
                return title+'...'
            title = title[:-1]

    def update_mouseover(self, x):
        "Determine if the tab our mouse is over has changed, and adjust if so"
        nowover = self.tabunder(x) if x != -1 else None
        if nowover != self.mouseover:
            self.tooltip_clear()
            self.mouseover = nowover
            self.rebuild()
            if nowover is not None and \
                            self.info[nowover]['tooltip'] is not None:
                self.tooltip_schedule()

    def tabunder(self, x):
        "Identify which tab is at a given position"
        for t in self.tabs:
            if self.info[t]['visible'] and self.info[t]['left'] <= x <\
                                self.info[t]['left'] + self.tabwidth:
                return t
        return None

    def rebuild(self, ev=None):
        """
        Update the display to match the current state of the user interface.
        This actually draws all the pieces of the tabs, indicators, etc. on
        the canvas. We take a brute force approach and recreate everything
        from scratch each time we're called, which happens on any significant
        state change.
        """
        self.c.delete('all')
        if self.winfo_width() < self.addiconwidth:
            return
        self.calculate_positions()
        tabwidth = self.tabwidth
        for t in self.tabs:
            if not self.info[t]['visible']:
                continue
            lbl = self.info[t]['tablabel']
            xpos = self.info[t]['left'] + self.info[t]['shift']

            color = self.selbg if t == self.current else self.bg
            rect = self.c.create_rectangle(xpos, 0, xpos + tabwidth - 2,
                            self.height, fill=color, outline=color)
            self.c.tag_bind(rect, '<ButtonRelease-1>',
                            lambda ev=None, t=t: self.select(t))

            self.c.create_line(xpos-1, 0, xpos-1,
                            self.height, fill=self.dividerbg)
            self.c.create_line(xpos+tabwidth-1, 0, xpos+tabwidth-1,
                            self.height, fill=self.dividerbg)
            color = self.textcolor
            if self.drag is not None and self.drag['state'] == 'inprogress' \
                                     and self.drag['tabid'] == t:
                color = self.holecolor
            txt = self.c.create_text(xpos + tabwidth / 2, self.height - 3,
                                   anchor='s', text=lbl, fill=color,
                                   font=self.titlefont)
            self.c.tag_bind(txt, '<ButtonRelease-1>',
                            lambda ev=None, t=t: self.select(t))
            if self.info[t]['dirty']:
                close = self.c.create_oval(xpos+4, self.height-13, xpos+10,
                            self.height-7, fill=self.textcolor,
                            outline=self.textcolor, activefill='red',
                            activeoutline='red')
                self.c.tag_bind(close, '<1>',
                            lambda ev=None, t=t: self.closetab(t, ev))
            elif t == self.mouseover:
                if self.drag is None or self.drag['state'] != 'inprogress':
                    close = self.c.create_text(xpos+8, self.height-3,
                                    anchor='s', text='x', fill=self.textcolor,
                                    activefill='red', font=self.plusfont)
                    self.c.tag_bind(close, '<ButtonRelease-1>',
                                    lambda ev=None, t=t: self.closetab(t, ev))
            if t == self.overflow_tab:
                more = self.c.create_text(xpos + tabwidth - 12,
                            self.height - 5, anchor='s', text='>>',
                            fill=self.textcolor, font=self.titlefont)
                self.c.tag_bind(more, '<1>', self.post_extras_menu)
        plus = self.c.create_text(self.plus_x+self.addiconwidth/2,
                            self.height-3, anchor='s', text='+',
                            fill=self.textcolor, font=self.plusfont)
        self.c.tag_bind(plus, '<ButtonRelease-1>', self.addtab)
        self.drag_createitems()

    def addtab(self, ev=None):
        self.observer.handle_addtab(self)

    def closetab(self, tabid, ev):
        self.observer.handle_closetab(self, tabid)

    def post_extras_menu(self, ev):
        "Show a menu for selecting the tabs that do not fit onscreen"
        self.tooltip_clear()
        self.calculate_positions()
        menu = Menu(self, tearoff=0)
        for t in self.tabs:
            if not self.info[t]['visible']:
                menu.add_command(label=self.info[t]['title'],
                                 command=lambda t=t: self.select(t))
        menu.tk_popup(ev.x_root, ev.y_root)

    def drag_initiate(self, ev):
        tabid = self.tabunder(ev.x)
        if tabid is not None:
            self.drag = {'state': 'pending', 'tabid': tabid,
                         'offsetx': ev.x - (self.info[tabid]['left'] +
                                            self.tabwidth/2),
                         'offsety': ev.y - (self.height - 3),
                         'x': ev.x, 'y': ev.y}

    def drag_continue(self, ev):
        if self.drag is None:
            return
        if self.drag['state'] == 'pending':
            if abs(ev.x - self.drag['x']) > 3 or \
                            abs(ev.y - self.drag['y']) > 3:
                self.drag['state'] = 'inprogress'
                self.drag['x'] = ev.x - self.drag['offsetx']
                self.drag['y'] = ev.y - self.drag['offsety']
                self.drag['gap'] = None
                self.rebuild()
        elif self.drag['state'] == 'inprogress':
            self.drag['x'] = ev.x - self.drag['offsetx']
            self.drag['y'] = ev.y - self.drag['offsety']
            self.c.coords(self.drag['textitem'],
                          (self.drag['x'], self.drag['y']))
            self.drag_identifygap(ev.x, ev.y)

    def drag_conclude(self, ev):
        if self.drag is not None and self.drag['state'] == 'inprogress':
            self.drag_identifygap(ev.x, ev.y)
            gap = self.drag['gap']
            if gap is not None:
                curidx = self.tabs.index(self.drag['tabid'])
                if gap > curidx:
                    gap -= 1
                self.tabs.remove(self.drag['tabid'])
                self.tabs.insert(gap, self.drag['tabid'])
        self.drag = None
        self.rebuild()

    def drag_createitems(self):
        "Called by rebuild to create canvas items for drag in progress"
        if self.drag is not None and self.drag['state'] == 'inprogress':
            if self.drag['gap'] is not None:
                x = self.drag['gap'] * self.tabwidth
                self.c.create_rectangle(x-self.gapwidth, 0, x+self.gapwidth,
                            self.height, fill=self.holecolor,
                            outline=self.holecolor)
            label = self.info[self.drag['tabid']]['tablabel']
            self.drag['textitem'] = self.c.create_text(self.drag['x'],
                            self.drag['y'], text=label, font=self.titlefont,
                            fill=self.textcolor, anchor='s')

    def drag_identifygap(self, x, y):
        gap = None
        for t in self.tabs:
            if not self.info[t]['visible']:
                continue
            left = self.info[t]['left']
            if left <= x <= left + self.tabwidth / 2:
                gap = self.tabs.index(t)
                break
            elif left + self.tabwidth / 2 <= x <= left + self.tabwidth:
                gap = self.tabs.index(t) + 1
                break
        tabidx = self.tabs.index(self.drag['tabid'])
        if gap is not None and (tabidx == gap or tabidx + 1 == gap):
            gap = None
        if y < 0 or y > self.height:
            gap = None
        if gap != self.drag['gap']:
            self.drag['gap'] = gap
            self.rebuild()

    def tooltip_schedule(self):
        self.tooltip_clear()
        self.tooltip = {'window': None,
                        'afterid': self.after(1500, self.tooltip_display)}

    def tooltip_clear(self):
        if self.tooltip is not None:
            if self.tooltip['window'] is not None:
                self.tooltip['window'].destroy()
            if self.tooltip['afterid'] is not None:
                self.after_cancel(self.tooltip['afterid'])
            self.tooltip = None

    def tooltip_display(self):
        self.tooltip['afterid'] = None
        if self.mouseover is None:
            return
        x = self.winfo_rootx() + self.info[self.mouseover]['left'] + 20
        y = self.winfo_rooty() + self.height + 5
        txt = self.info[self.mouseover]['tooltip']
        tw = self.tooltip['window'] = Toplevel(self)
        tw.wm_withdraw()
        tw.wm_geometry("+%d+%d" % (x, y))
        tw.wm_overrideredirect(1)
        try:
            tw.tk.call("::tk::unsupported::MacWindowStyle", "style", tw._w,
                       "help", "noActivates")
        except TclError:
            pass
        lbl = Label(tw, text=txt, justify=LEFT, background="#ffffe0",
                    borderwidth=0, font=self.tooltipfont)
        if self.tk.call('tk', 'windowingsystem') != 'aqua':
            lbl['borderwidth'] = 1
            lbl['relief'] = 'solid'
        lbl.pack()
        tw.update_idletasks()  # calculate window size to avoid resize flicker
        tw.deiconify()
        tw.lift()  # needed to work around bug in Tk 8.5.18+ (issue #24570)
Exemple #24
0
##        font create varsFont   {*}[font configure TkDefaultFont]
##	if {[tk windowingsystem] eq "aqua"} {
##	    font configure titleFont -size 17
##	}
##    } else {
##        font create mainFont   -family Helvetica -size 12
##        font create fixedFont  -family Courier   -size 10
##        font create boldFont   -family Helvetica -size 12 -weight bold
##        font create titleFont  -family Helvetica -size 18 -weight bold
##        font create statusFont -family Helvetica -size 10
##        font create varsFont   -family Helvetica -size 14
##    }
##}
if 'defaultFont' not in root.tk.call('font', 'names'):
    if 'TkDefaultFont' in root.tk.call('font', 'names') and 'TkFixedFont' in root.tk.call('font', 'names'):
        mainFont = Font(name='TkDefaultFont', exists=True).copy()
        fixedFont = Font(name='TkFixedFont', exists=True).copy()
        boldFont = Font(name='TkDefaultFont', exists=True).copy()
        boldFont['weight'] = 'bold'
        titleFont = Font(name='TkDefaultFont', exists=True).copy()
        titleFont['weight'] = 'bold'
        statusFont = Font(name='TkDefaultFont', exists=True).copy()
        varsFont = Font(name='TkDefaultFont', exists=True).copy()
        if root._windowingsystem == 'aqua':
            titleFont['size'] = 17
    else:
        mainFont = Font(family='Helvetica', size=12)
        fixedFont = Font(family='Courier', size=10)
        boldFont = Font(family='Helvetica', size=12, weight='bold')
        titleFont = Font(family='Helvetica', size=18, weight='bold')
        statusFont = Font(family='Helvetica', size=10)
Exemple #25
0
# ---------------------------------------------------------------------------------

f = functions.functions()  #Create object to access list of methods
root = tk.Tk()  # Create Gui
root.title("Cryptocurrency Price Tracker")

# ----Set Height of the window-----
canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()

# ----Main Frame (Background Light Blue)------
frame = tk.Frame(root, bg='#0080ff')
frame.place(relwidth=1, relheight=1)

# -----Import Time------
timefont = Font(family="Open Sans", size=14)
time_label = tk.Label(root, font=timefont, bg='#0080ff', fg='#000000')
time_label.place(relx=0.01, rely=0.02)
update_time()

# -----Update BTC Price-----
pricefont_BTC = Font(family="Open Sans", size=22)
price_label_BTC = tk.Label(frame,
                           font=pricefont_BTC,
                           bg='#0080ff',
                           fg='#000000')
price_label_BTC.place(relx=0.35, rely=0.55)
BTC_price = update_BTC()

pricefont_secondary = Font(family="Open Sans", size=18)
# ------24hr ago price of BTC-----
Exemple #26
0
def ogsignlerf():
    from tkinter.font import Font
    import sqlite3, os, sys

    enter = Tk()
    enter.attributes('-fullscreen', True)

    def close():
        enter.destroy()

    def imgbinary11():
        global imgdata
        with open("111.png", "rb") as f:
            imgdata = f.read()

    def imgbinary22():
        global imgdata
        with open("158.png", "rb") as f:
            imgdata = f.read()

    def imgbinary33():
        global imgdata
        with open("175.png", "rb") as f:
            imgdata = f.read()

    def imgbinary44():
        global imgdata
        with open("186.png", "rb") as f:
            imgdata = f.read()

    def imgbinary55():
        global imgdata
        with open("153.png", "rb") as f:
            imgdata = f.read()

    def imgbinary66():
        global imgdata
        with open("136.png", "rb") as f:
            imgdata = f.read()

    def dtbssign():
        global naam
        naam = sign11.get()
        print(naam)
        if len(sign33.get()) >= 8 and len(sign44.get()) >= 8:
            if sign33.get() == sign44.get():
                conn = sqlite3.connect("pybox-db.db", isolation_level=None)
                cursor = conn.execute(
                    "Insert into accounts values(?,?,?,?)",
                    (naam, sign22.get(), sign33.get(), imgdata))
                print("data sent.")
                conn.close()
                print(naam)
                f = open("userella.txt", "w")
                f.write(naam)
                enter.destroy()
                os.system("python player.py")
            else:
                print("alag.")
        else:
            print("8.")

    def dtbslog():
        global naam, letter
        naam = log11.get()
        letter = log22.get()
        print(naam, letter)
        conn = sqlite3.connect("pybox-db.db", isolation_level=None)
        cursor = conn.execute(
            'SELECT * from accounts WHERE username="******" AND password="******"'.
            format(naam, letter))
        if cursor.fetchone() is not None:
            print("welcome")
            print(naam)
            f = open("userella.txt", "w")
            f.write(naam)
            f.close()
            enter.destroy()
            os.system("python player.py")
        else:
            print("Hatt!")
            log11.set("")
            log22.set("")
        conn.close()

    clsbtn = Button(enter, command=close, border=0, bg="white")
    calc = PhotoImage(file="cross.png").subsample(3, 3)
    clsbtn.config(image=calc, width="30", height="30")
    clsbtn.place(x=1325, y=10)
    photo = PhotoImage(file="F:\projects\pybox-tk\head.png").subsample(2, 2)
    fontl = Font(size=20, family="Fixedsys")
    fontr = Font(size=16, family="System")
    brcanva = Canvas(enter,
                     height=2,
                     width=1150,
                     bg="white",
                     background="black",
                     bd=0,
                     highlightthickness=0,
                     relief='ridge').place(x=100, y=390)
    imgcnv = Canvas(enter,
                    height=100,
                    width=100,
                    bg="white",
                    bd=0,
                    highlightthickness=0,
                    relief='ridge')
    imgcnv.create_image(50, 50, image=photo)
    imgcnv.place(x=50, y=0)
    frmlog = Frame(enter, height=200, width=600, bg="white").place(x=375,
                                                                   y=150)
    sgnfrm = Frame(enter, height=350, width=1100, bg="white").place(x=125,
                                                                    y=400)
    #dp=PhotoImage(file="user.png").subsample(3,3)
    imgcnv = Canvas(enter,
                    height=100,
                    width=100,
                    bg="white",
                    bd=0,
                    highlightthickness=0,
                    relief='ridge')
    imgcnv.create_image(50, 50, image=photo)
    imgcnv.place(x=1000, y=200)

    #frmlog
    loghead = Label(frmlog, text="Login", font=fontl, bg="white").place(x=380,
                                                                        y=155)
    userlogin = Label(frmlog, text="Username", font=fontr,
                      bg="white").place(x=440, y=210)
    pwdlogin = Label(frmlog, text="Password", font=fontr,
                     bg="white").place(x=440, y=270)
    login = Button(sgnfrm, text="Log In", font=fontr,
                   command=dtbslog).place(x=600, y=330)
    log11 = StringVar()
    log22 = StringVar()
    log1 = Entry(frmlog,
                 font=fontr,
                 textvariable=log11,
                 bg="white",
                 validate="focusout").place(x=580, y=210)
    log2 = Entry(frmlog, font=fontr, textvariable=log22,
                 bg="white").place(x=580, y=270)

    #sgnfrm
    sgnhead = Label(sgnfrm, text="Sign-Up", font=fontl,
                    bg="white").place(x=130, y=405)
    user = Label(sgnfrm, text="Create Username", font=fontr,
                 bg="white").place(x=190, y=460)
    email = Label(sgnfrm, text="Enter E-Mail", font=fontr,
                  bg="white").place(x=190, y=520)
    pwd = Label(sgnfrm, text="Create Password", font=fontr,
                bg="white").place(x=190, y=580)
    repwd = Label(sgnfrm, text="Re-Enter Password", font=fontr,
                  bg="white").place(x=190, y=640)
    imager = Label(sgnfrm,
                   text="Select You Profile Picture",
                   font=fontr,
                   bg="white").place(x=600, y=460)
    signup = Button(sgnfrm, text="Sign Up", font=fontr,
                    command=dtbssign).place(x=450, y=700)
    sign11 = StringVar()
    sign22 = StringVar()
    sign33 = StringVar()
    sign44 = StringVar()
    sign1 = Entry(sgnfrm, textvariable=sign11, font=fontr,
                  bg="white").place(x=330, y=460)
    sign2 = Entry(sgnfrm, textvariable=sign22, font=fontr,
                  bg="white").place(x=330, y=520)
    sign3 = Entry(sgnfrm, textvariable=sign33, font=fontr,
                  bg="white").place(x=330, y=580)
    sign4 = Entry(sgnfrm, textvariable=sign44, font=fontr,
                  bg="white").place(x=330, y=640)
    img11 = PhotoImage(file="111.png").zoom(2, 2)
    img11btn = Button(sgnfrm,
                      border=0,
                      command=imgbinary11,
                      bg="white",
                      relief=FLAT)
    img11btn.config(image=img11, width="100", height="100")
    img11btn.place(x=600, y=500)
    img22 = PhotoImage(file="158.png").zoom(2, 2)
    img22btn = Button(sgnfrm,
                      border=0,
                      command=imgbinary22,
                      bg="white",
                      relief=FLAT)
    img22btn.config(image=img22, width="100", height="100")
    img22btn.place(x=700, y=500)
    img33 = PhotoImage(file="175.png").zoom(2, 2)
    img33btn = Button(sgnfrm,
                      border=0,
                      command=imgbinary33,
                      bg="white",
                      relief=FLAT)
    img33btn.config(image=img33, width="100", height="100")
    img33btn.place(x=800, y=500)
    img44 = PhotoImage(file="186.png").zoom(2, 2)
    img44btn = Button(sgnfrm,
                      border=0,
                      command=imgbinary44,
                      bg="white",
                      relief=FLAT)
    img44btn.config(image=img44, width="100", height="100")
    img44btn.place(x=900, y=500)
    img55 = PhotoImage(file="153.png").zoom(2, 2)
    img55btn = Button(sgnfrm,
                      border=0,
                      command=imgbinary55,
                      bg="white",
                      relief=FLAT)
    img55btn.config(image=img55, width="100", height="100")
    img55btn.place(x=1000, y=500)
    img66 = PhotoImage(file="136.png").zoom(2, 2)
    img66btn = Button(sgnfrm,
                      border=0,
                      command=imgbinary66,
                      bg="white",
                      relief=FLAT)
    img66btn.config(image=img66, width="100", height="100")
    img66btn.place(x=1100, y=500)
    #cmnt
    #cmnt2

    enter.configure(background='white')
    enter.mainloop()
Exemple #27
0
                             width=322,
                             height=200)
    BATCH_FRAME.grid(row=1,
                     rowspan=3,
                     column=2,
                     columnspan=2,
                     padx=5,
                     pady=5,
                     ipadx=5,
                     sticky="NWE")
    BATCH_FRAME.columnconfigure(0, weight=1)
    BATCH_FRAME.rowconfigure(0, weight=1)
    BATCH_FRAME.grid_propagate(0)
    BATCHES = ScrolledText(BATCH_FRAME)
    BATCHES.grid(row=0, column=0, columnspan=5)
    BATCHES['font'] = Font(family="Helvetica", size=8, weight="bold")
    display_batches()
    LBLGYLE = Label(BATCH_FRAME, text="Enter gyle number: ")
    LBLGYLE.grid(row=1, column=0, sticky="W")
    gyle = Entry(BATCH_FRAME)
    gyle.grid(row=1, column=1, sticky="W")
    UPDATEBUTTON = Button(BATCH_FRAME, text="Update", command=update)
    UPDATEBUTTON.grid(row=1, column=2, columnspan=1, padx=1)
    DELETE_BUTTON = Button(BATCH_FRAME, text="Delete", command=remove_batch)
    DELETE_BUTTON.grid(row=1, column=3, columnspan=1)

    # move current batches to next production stage section drawn
    gyleNumber = 0
    UPDATE_FRAME = LabelFrame(
        WINDOW,
        text="Move current batches to next production stage",
    def __init__(self, parent, is_a_sandbox_sudoku, sudoku=empty_sudoku_board):
        tk.Frame.__init__(self, parent)
        from menu import declare_an_image_for_a_widget, bind_events_for_widget
        from menu import MenuWindow
        from select_difficult import SelectDifficult

        self.empty_sudoku_board = [['' for i in range(9)] for j in range(9)]
        self.TEXT_COLOR = '#05619a'
        self.parent = parent
        self.BG = '#42445e'
        self.config(bg=self.BG)

        self.font = Font(family='Dubai Light bold', size=18)
        self.is_there_focused_label = False
        self.previous_label = None
        self.labels = [[] for _ in range(9)]
        self.text_variables = [[] for _ in range(9)]

        self.stopped_timer = False
        self.is_in_play_mode = False
        self.is_window_blocked = False

        self._offsetx = 0
        self._offsety = 0

        # Time variables

        self.seconds = 0
        self.minutes = 0

        def announce_win():
            self.is_window_blocked = True
            play_again = tk, messagebox.askyesno(
                message=
                f'Congratulations, you did it in {self.minutes}:{self.seconds}! Do you want to play again?',
                title='Congrats!')
            if play_again:
                self.destroy()
                game = PlayWindow(self.parent, False, sudoku)
                game.grid()
            else:
                return_to_menu()

        def update_time():
            if not self.is_window_blocked:
                if self.is_in_play_mode:
                    if self.seconds == 59:
                        self.minutes += 1
                        self.seconds = 0

                    else:
                        self.seconds += 1
                    new_time = f'{str(self.minutes)}:{str(self.seconds)}'
                    self.time.set(new_time)
                    self.timer.after(1000, update_time)
            else:
                self.timer.after(1000, update_time)

        def desselect_label():
            self.is_there_focused_label = False
            self.previous_label.is_locked = True

        def start_play_mode():
            self.start_label.destroy()
            clean_highlighted_labels()
            self.is_in_play_mode = True
            for l, _ in enumerate(self.board):
                for k, _ in enumerate(self.board[l]):
                    if type(self.board[l][k]) == int:
                        self.labels[l][k].is_locked = True

            if is_a_sandbox_sudoku:
                self.solve_label = tk.Label(self,
                                            relief=FLAT,
                                            bg=self.BG,
                                            image=self.solve_button_off_image)
                self.solve_label.grid(row=10,
                                      column=1,
                                      sticky='NSEW',
                                      columnspan=3,
                                      padx=(20, 0),
                                      pady=(0, 10))
                bind_events_for_widget(self.solve_label,
                                       self.binding_functions, 'solve')

            # Timer widget

            timer_font = Font(family='Dubai', size=18)

            self.time = tk.StringVar()
            self.timer = tk.Label(self,
                                  textvariable=self.time,
                                  font=timer_font,
                                  relief=FLAT,
                                  bg=self.BG,
                                  fg='#a2a3b7')

            self.timer.grid(row=10,
                            column=4,
                            sticky='NSEW',
                            columnspan=9,
                            padx=(100, 0),
                            pady=(5, 15))
            self.time.set(f'{self.minutes}:{self.seconds}')
            self.after(1000, update_time)

        def change_focused_label_with_key(key, position):
            if key == 'Up':
                next_label = position[0] - 1
                if next_label < 0:
                    next_label = 8
                while self.labels[next_label][position[1]].is_locked:
                    next_label -= 1
                    if next_label < 0:
                        next_label = 8
                position = (next_label, position[1])
                label_to_go = self.labels[position[0]][position[1]]
                var = self.text_variables[position[0]][position[1]]
                focus_label((position[0], position[1]), label_to_go, var)

            elif key == 'Down':
                next_label = position[0] + 1
                if next_label > 8:
                    next_label = 0
                while self.labels[next_label][position[1]].is_locked:
                    next_label += 1
                    if next_label > 8:
                        next_label = 0
                position = (next_label, position[1])

                label_to_go = self.labels[position[0]][position[1]]
                var = self.text_variables[position[0]][position[1]]
                focus_label((position[0], position[1]), label_to_go, var)

            elif key == 'Left':
                next_label = position[1] - 1
                if next_label < 0:
                    next_label = 8
                while self.labels[position[0]][next_label].is_locked:
                    next_label -= 1
                    if next_label < 0:
                        next_label = 8
                position = (position[0], next_label)
                label_to_go = self.labels[position[0]][position[1]]
                var = self.text_variables[position[0]][position[1]]
                focus_label((position[0], position[1]), label_to_go, var)

            elif key == 'Right':
                next_label = position[1] + 1
                if next_label > 8:
                    next_label = 0
                while self.labels[position[0]][next_label].is_locked:
                    next_label += 1
                    if next_label > 8:
                        next_label = 0
                position = (position[0], next_label)

                label_to_go = self.labels[position[0]][position[1]]
                var = self.text_variables[position[0]][position[1]]
                focus_label((position[0], position[1]), label_to_go, var)

        def update_the_board():
            for index, list in enumerate(self.labels):
                for sub_index, sub_list in enumerate(list):
                    variable = tk.StringVar(value=self.board[index][sub_index])
                    label = self.labels[index][sub_index]
                    label.configure(textvariable=variable)

        def solve_the_sudoku():
            self.is_in_play_mode = False
            board = Sudoku(self.board)
            solve_sudoku = multiprocessing.Process(
                target=board.return_the_solution)
            solve_sudoku.start()
            solve_sudoku.join(4)
            if solve_sudoku.is_alive():
                solve_sudoku.terminate()
                tk.messagebox.showinfo(
                    message='There is no solution for this sudoku',
                    title='Advice')

            else:
                self.board = board.return_the_solution()
                update_the_board()

                # Lock all the labels

                for i, _ in enumerate(self.labels):
                    for l, _ in enumerate(self.labels):
                        self.labels[i][l].is_locked = True

                clean_highlighted_labels()

                tk.messagebox.showinfo(message='This is the solution!',
                                       title='Done!')

                # Leave the bord in blank if the user wants to play again

                self.board = self.empty_sudoku_board
                return_to_menu()

        def insert_number(number, variable, position):

            variable.set(number)
            if number.isdigit():
                self.board[position[0]][position[1]] = int(number)

        # If user press the backspace

            else:
                self.board[position[0]][position[1]] = ''

            highlight_keys(self.board, position, self.labels, self.TEXT_COLOR)

            if self.is_in_play_mode:
                board = self.board
                board = Sudoku(board)
                if board.check_if_solved():
                    announce_win()

        def clean_highlighted_labels():
            self.is_there_focused_label = False
            for i, _ in enumerate(self.board):
                for k, _ in enumerate(self.board):
                    self.labels[i][k].is_highlighted = False
                    self.labels[i][k].config(bg=self.BG_LABEL_COLOR,
                                             fg=self.TEXT_COLOR)

        def focus_label(position, label, variable):
            if not self.is_window_blocked:
                if not self.is_there_focused_label and not label.is_locked:
                    if self.previous_label:
                        self.previous_label.is_locked = False

                    label.is_locked = True
                    # The focused label is now the previous label
                    self.previous_label = self.labels[position[0]][position[1]]

                    # Set the window focus on the PlayWindow

                    self.focus_set()

                    for num in range(1, 10):
                        self.bind(
                            str(num),
                            lambda event, number=str(num), var=variable, pos=
                            position: insert_number(number, var, pos))
                    self.bind('<BackSpace>',
                              lambda event, value='', var=variable, pos=
                              position: insert_number(value, var, pos))

                    highlight_keys(self.board, position, self.labels,
                                   self.TEXT_COLOR)
                    self.is_there_focused_label = True

                elif self.is_there_focused_label and not label.is_locked:
                    self.previous_label.config(bg='white', fg=self.TEXT_COLOR)
                    self.is_there_focused_label = False
                    focus_label(position, label, variable)

                for key in ['Up', 'Down', 'Left', 'Right']:
                    self.bind('<' + key + '>',
                              lambda event, key=key, pos=position:
                              change_focused_label_with_key(key, position))

        def change_leave_color(label):
            if not self.is_window_blocked:
                if not label.is_locked and not label.is_highlighted:
                    if self.previous_label:
                        if self.previous_label.is_locked:
                            label.config(bg=self.BG_LABEL_COLOR)
                            label.is_highlighted = False
                    else:
                        label.config(bg=self.BG_LABEL_COLOR)
                        label.is_highlighted = False

        def change_enter_color(label):
            if not self.is_window_blocked:
                if not label.is_locked and not label.is_highlighted:
                    label.config(bg='#ffdddd')

        # Label binding functions

        def enter_label(widget):
            if not self.is_window_blocked:
                if widget == 'start':
                    self.start_label.config(image=self.start_button_on_image)
                    self.start_label.is_cursor_on = True
                elif widget == 'exit':
                    self.exit_button.config(image=self.exit_button_on_image)
                    self.exit_button.is_cursor_on = True
                elif widget == 'solve':
                    self.solve_label.config(
                        image=self.solve_button_cursor_on_image)
                    self.solve_button_is_cursor_on = True

        def leave_label(widget):
            if not self.is_window_blocked:
                if widget == 'start':
                    self.start_label.config(image=self.start_button_off_image)
                    self.start_label.is_cursor_on = False
                elif widget == 'exit':
                    self.exit_button.config(image=self.exit_button_off_image)
                    self.exit_button.is_cursor_on = False
                elif widget == 'solve':
                    self.solve_label.config(image=self.solve_button_off_image)
                    self.solve_button_is_cursor_on = False

        def press_label(widget):
            if not self.is_window_blocked:
                if widget == 'start':
                    self.start_label.config(
                        image=self.start_button_pressed_image)
                elif widget == 'exit':
                    self.exit_button.config(
                        image=self.exit_button_pressed_image)
                elif widget == 'solve':
                    self.solve_label.config(
                        image=self.solve_button_pressed_image)

        def release_label(widget):
            if not self.is_window_blocked:
                if widget == 'start':
                    if self.start_label.is_cursor_on:
                        start_play_mode()
                elif widget == 'exit':
                    if self.exit_button.is_cursor_on:
                        ask_if_exit()
                elif widget == 'solve':
                    if self.solve_button_is_cursor_on:
                        solve_the_sudoku()

        def return_to_menu():
            self.destroy()
            menu = MenuWindow(parent)
            menu.grid(sticky='NSEW')

        def ask_if_exit():
            # Block all the app's functions

            self.is_window_blocked = True

            exit_to_menu = tk, messagebox.askyesno(
                message=
                'Are you sure you want to exit? You will lose all your progress',
                title='Warning')

            # messagebox.askyesno returns a tuple, the first element is the route of the tkinter module (I don't know why)
            # and the second element is the boolean value, True or False

            if exit_to_menu[1] == True:
                return_to_menu()
            elif exit_to_menu[1] == False:
                self.is_window_blocked = False

                # List of all the images used in this widget, 'image route', 'size', atributte name'

        images = [
            [
                'Images/Start_button_off.png', (140, 65),
                'start_button_off_image'
            ],
            ['Images/Start_button_on.png', (140, 65), 'start_button_on_image'],
            [
                'Images/Start_button_pressed.png', (140, 65),
                'start_button_pressed_image'
            ], ['Images/leave_button.png', (40, 40), 'exit_button_off_image'],
            [
                'Images/leave_button_cursor_on.png', (40, 40),
                'exit_button_on_image'
            ],
            [
                'Images/leave_button_pressed.png', (40, 40),
                'exit_button_pressed_image'
            ],
            ['Images/solve_button.png', (140, 65), 'solve_button_off_image'],
            [
                'Images/solve_button_cursor_on.png', (140, 65),
                'solve_button_cursor_on_image'
            ],
            [
                'Images/solve_button_pressed.png', (140, 65),
                'solve_button_pressed_image'
            ]
        ]

        for image in images:
            declare_an_image_for_a_widget(self, image[0], image[1], image[2])

        self.binding_functions = [
            enter_label, leave_label, press_label, release_label
        ]

        #  Configuring the button that starts the game and the timer

        self.start_label = tk.Label(self,
                                    relief=FLAT,
                                    bg=self.BG,
                                    width=140,
                                    height=65,
                                    image=self.start_button_off_image)

        self.start_label.grid(row=10,
                              column=6,
                              sticky='NSEW',
                              padx=3,
                              pady=(1, 20),
                              columnspan=3)

        bind_events_for_widget(self.start_label, self.binding_functions,
                               'start')

        #  Configuring the button to leave the game and go to the menu

        self.exit_button = tk.Label(self,
                                    relief=FLAT,
                                    bg=self.BG,
                                    text='HOLA',
                                    image=self.exit_button_off_image)
        self.exit_button.grid(row=10,
                              sticky='NSEW',
                              column=0,
                              padx=(20, 0),
                              pady=(0, 10))
        bind_events_for_widget(self.exit_button, self.binding_functions,
                               'exit')

        if sudoku == 'easy':
            self.board = random.choice(easy_sudokus)
        elif sudoku == 'medium':
            self.board = random.choice(medium_sudokus)
        elif sudoku == 'hard':
            self.board = random.choice(hard_sudokus)
        else:
            self.board = self.empty_sudoku_board

        self.BG_LABEL_COLOR = '#ffffff'

        for row, sublist in enumerate(self.board):
            for column, sub_value in enumerate(sublist):
                label_variable = tk.StringVar(value=self.board[row][column])
                new_label = tk.Label(self,
                                     relief=FLAT,
                                     bg=self.BG_LABEL_COLOR,
                                     font=self.font,
                                     width=40,
                                     height=40,
                                     fg=self.TEXT_COLOR,
                                     textvariable=label_variable)

                setattr(new_label, 'is_highlighted', False)
                setattr(new_label, 'is_locked', False)

                b_padx = 1
                b_pady = 1

                if row == 0:
                    b_pady = (7, 1)

                if row == 8:
                    b_pady = (1, 10)

                if row == 3 or row == 6:
                    b_pady = (3, 1)

                if row == 2 or row == 5:
                    b_pady = (1, 3)

                if column == 0:
                    b_padx = (3, 1)

                if column == 8:
                    b_padx = (1, 3)

                if column == 2 or column == 5:
                    b_padx = (1, 3)

                if column == 3 or column == 6:
                    b_padx = (3, 1)

                new_label.grid(row=row,
                               column=column,
                               sticky='NSEW',
                               padx=b_padx,
                               pady=b_pady)

                new_label.bind('<Button-1>',
                               lambda event, position=(row, column), label=
                               new_label, variable=label_variable: focus_label(
                                   position, label, variable))
                new_label.bind(
                    '<Enter>',
                    lambda event, label=new_label: change_enter_color(label))
                new_label.bind(
                    '<Leave>',
                    lambda event, label=new_label: change_leave_color(label))

                self.labels[row].append(new_label)
                self.text_variables[row].append(label_variable)

        for i in range(10):
            self.rowconfigure(i, weight=1)
            self.columnconfigure(i, weight=1)

        if not self.board == self.empty_sudoku_board:
            start_play_mode()
Exemple #29
0
response = getApod('2019-08-24')
imgInfo = response.split('*', 3)

# Create the main UI
win = Tk()
win.title("SkySight")
win.resizable(False, False)
win.geometry("900x640")
win.config(background='black')

# Title Label
Label_one = Label(text=imgInfo[0] + ' (' + imgInfo[2] + ')',
                  height=1,
                  foreground="white",
                  background="black")
myFont = Font(family="Trebuchet MS", size=15)
Label_one.config(font=myFont)
Label_one.pack(anchor='center', fill='x')

# Image and Description Frames
picFrame = Frame(win)
picFrame.pack(anchor='center', fill='x')
bottomframe = Frame(win)
bottomframe.pack(anchor='center')

# Nasa Image display
im = Image.open("IMAGE_FILE_PATH")
logo = ImageTk.PhotoImage(im)
Label_two = Label(picFrame,
                  image=logo,
                  background='black',
    def buildItems(self, roomList, startTime, endTime):
        #Cleans frame, incase there are items in it:
        for widget in self.frame_classes.winfo_children():
            widget.destroy()
        for widget in self.frame_times.winfo_children():
            widget.destroy()
        for widget in self.frame_rooms.winfo_children():
            widget.destroy()

        sTime = 0 + startTime  #starts at 0, max eTime
        eTime = 28 - endTime  #starts at max of roomList timeslots, should be 28, min sTime
        #NO ERROR CHECKING, please do error checing before calling buildItems
        w = len(roomList * 170)
        if w > 1190:  #adding a max w for large sets
            w = 1190
        self.canvas_rooms.configure(width=w)
        self.canvas_classes.configure(width=w)
        self.font_HeaderItems = Font(family="Arial", size=15)
        self.font_DetailItems = Font(family="Verdana", size=10)

        self.gridWidth = 15
        self.gridHeight = 2

        i = 1
        flag = 0
        timeDisplay = 8.0  #start at 8 AM
        for item in roomList:
            print("item %d", i)
            self.label_room = Label(self.frame_rooms,
                                    text=item.getRoomName(),
                                    font=self.font_HeaderItems,
                                    width=self.gridWidth,
                                    height=self.gridHeight,
                                    bd=2,
                                    relief="groove")
            self.label_room.grid(row=0, column=i, sticky=W)
            i = i + 1
            #time slots on left side
            for x in range(len(item.timeSlots)):
                if (flag == 0):
                    if (timeDisplay < 1):
                        timeDisplay = timeDisplay + 12
                    timeDisplayString = str(format(timeDisplay, ".2f"))
                    timeDisplayString = timeDisplayString.replace(".", ":")
                    self.label_time = Label(self.frame_times,
                                            text=timeDisplayString,
                                            font=self.font_HeaderItems,
                                            height=self.gridHeight * 2,
                                            bd=2,
                                            relief="groove")
                    self.label_time.grid(row=x + 1, column=0, sticky="EW")
                    timeDisplay = (timeDisplay + .3)
                    if (round(timeDisplay) > timeDisplay):
                        timeDisplay = round(timeDisplay)
                        timeDisplay = (timeDisplay) % 12
            flag = 1
            #events in each room per time slot
            for time in range(len(item.timeSlots)):
                self.placeholderEvent = item.getEvent(time)
                self.text_header_label_event = self.placeholderEvent.getSubject(
                )[:10] + " " + self.placeholderEvent.getCourseNum(
                ) + "-" + self.placeholderEvent.getSection()
                self.text_details_label_event = " "
                if (self.placeholderEvent.getSubject() != " "):
                    self.text_details_label_event = "Instructor: " + self.placeholderEvent.getInstructor(
                    ) + "\nCapacity: " + str(
                        self.placeholderEvent.getCapacity())
                    self.label_eventDetail = Label
                self.label_eventTitle = Label(
                    self.frame_classes,
                    text=self.text_header_label_event,
                    font=self.font_HeaderItems,
                    width=self.gridWidth,
                    height=self.gridHeight,
                    bd=2,
                    relief="groove",
                    pady=3)
                self.label_eventDetail = Label(
                    self.frame_classes,
                    text=self.text_details_label_event,
                    font=self.font_DetailItems,
                    width=self.gridWidth,
                    height=self.gridHeight,
                    bd=2,
                    relief="groove",
                    pady=3)
                self.label_eventTitle.grid(row=(time * 2) + 1,
                                           column=i,
                                           sticky=W)
                self.label_eventDetail.grid(row=(time * 2) + 2,
                                            column=i,
                                            sticky="EW")
        #     h.execute("SELECT COUNT(SNo) from camera WHERE DATE(Date)=DATE(temp)")
        #     a=h.fetchall()
        #     for j in a:
        #         for k in j:
        #             number.append(k)

    elif va=="Week Wise":
        messagebox.showerror("Error","Not enough data available for weekly comparison")

    else:
        messagebox.showerror("Error","Please Select an option")

root=Tk()
root.title("Visualise Data")
root.geometry("400x250+450+225")
my = Font(family="Helvetica", size=16, weight="bold", slant="italic")
l1=Label(root,text="Please enter details below to log in")
l1.config(font=my)
l1.pack()
Label(root,text="").pack()
my = Font(family="Helvetica", size=14, weight="bold")
l2=Label(root,text="Enter the category according to which")
l2.config(font=my)
l2.pack()
l2=Label(root,text="data will be presented")
l2.config(font=my)
l2.pack()
Label(root,text="").pack()
v=["Hour Wise","Day Wise","Week Wise"]
c=Combobox(root,values=v,height=3,width=15)
c.set("select")
Exemple #32
0
import tkinter as tk
import os
import subprocess as sub

from tkinter import *
from tkinter.font import Font
from tkinter import messagebox

root = tk.Tk()
myFont = Font(family="Times New Roman", size=12)


def original_nice():
    p = sub.Popen('./nice_display.sh', stdout=sub.PIPE, stderr=sub.PIPE)
    output, errors = p.communicate()
    text = tk.Text(root)
    text.grid_forget()
    text.grid(row=1, column=0, padx=10, pady=10)
    text.insert(END, output)
    text.config(spacing2=1.5,
                state=DISABLED,
                height=7,
                width=30,
                font=myFont,
                autoseparators=2)


def change_nice():
    ch_Priority = my_entry1.get()
    ch_PID = my_entry2.get()
    update = "sudo renice " + ch_Priority + " -p " + ch_PID
Exemple #33
0
    def display_search_results(self, results):

        # Based heavily around: https://pyinmyeye.blogspot.com/2012/07/tkinter-multi-column-list-demo.html

        self.results_window = Toplevel()

        self.results_window.title("Search Results for: " + self.search_string)

        columns = {
            "name_first": "First Name",
            "name_last": "Last Name",
            "id": "Member ID",
            "join_date": "Join Date",
            "member_type": "Member Type"
        }

        columnKeys = []
        for k in columns.keys():
            columnKeys.append(k)

        self.tree = ttk.Treeview(self.results_window,
                                 columns=columnKeys,
                                 show="headings")

        for dbName in columns.keys():
            self.tree.column(dbName, width=Font().measure(columns[dbName]) + 2)
            self.tree.heading(dbName, text=columns[dbName])

        for item in results:
            arr = []
            for val in columns.keys():
                if val == "join_date":
                    join_date = datetime.strptime(item[val],
                                                  '%Y-%m-%d %H:%M:%S.%f')
                    join_date_str = str(join_date.year) + "-" + str(
                        join_date.month) + "-" + str(join_date.day)
                    arr.append(join_date_str)
                    iwidth = Font().measure(join_date_str) + 10
                elif val == "member_type":
                    member_type_str = config.member_types.get(item[val])
                    arr.append(member_type_str)
                    iwidth = Font().measure(member_type_str) + 10
                elif val == "link":
                    pass
                else:
                    arr.append(item[val])
                    iwidth = Font().measure(item[val]) + 10
                if self.tree.column(val, 'width') < iwidth:
                    self.tree.column(val, width=iwidth)
            self.tree.insert('', 'end', values=arr)

        ysb = ttk.Scrollbar(self.results_window,
                            orient=VERTICAL,
                            command=self.tree.yview)
        xsb = ttk.Scrollbar(self.results_window,
                            orient=HORIZONTAL,
                            command=self.tree.xview)

        self.tree['yscroll'] = ysb.set
        self.tree['xscroll'] = xsb.set

        self.tree.grid(row=0, column=0, sticky=NSEW)
        ysb.grid(row=0, column=1, sticky=NS)
        xsb.grid(row=1, column=0, sticky=EW)

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

        self.buttons = Frame(self.results_window)
        self.buttons.grid()

        if self.context == SMWContext.Search:  # In search for members window
            Button(self.buttons,
                   text="Print new barcode",
                   command=self.newBarcode).grid(row=2, column=1, padx=3)
            Button(self.buttons, text="Copy Member ID",
                   command=self.copyMID).grid(row=2, column=2, padx=3)
            if config.sign_offs_enabled:
                Button(self.buttons,
                       text="View Sign Offs",
                       command=self.edit_sign_offs).grid(row=2,
                                                         column=3,
                                                         padx=3)

        elif self.context == SMWContext.SplashEntry:  # In search window popped up from splash (first) screen
            Button(self.buttons,
                   text="Print new barcode",
                   command=self.newBarcode).grid(row=2, column=1, padx=3)
            Button(self.buttons,
                   text="Login Member",
                   command=self.search_return).grid(row=2, column=2, padx=3)
            Button(self.buttons,
                   text="Edit Member",
                   command=self.edit_from_splash).grid(row=2, column=4, padx=3)
            if config.sign_offs_enabled:
                Button(self.buttons,
                       text="View Sign Offs",
                       command=self.edit_sign_offs).grid(row=2,
                                                         column=3,
                                                         padx=3)

        elif self.context == SMWContext.EditMember:  # In search window popped up from edit member window
            Button(self.buttons,
                   text="Edit Member",
                   command=self.search_return).grid(row=2, column=1, padx=3)

        self.center(self.results_window)
        self.results_window.focus_force()
Exemple #34
0
 def __setitem__(self, key, value):
     if key not in self._properties:
         raise AttributeError("Calendar object has no attribute %s." % key)
     elif key is "locale":
         raise AttributeError("This attribute cannot be modified.")
     else:
         if key is "selectmode":
             if value is "none":
                 for week in self._calendar:
                     for day in week:
                         day.unbind("<1>")
             elif value is "day":
                 for week in self._calendar:
                     for day in week:
                         day.bind("<1>", self._on_click)
             else:
                 raise ValueError(
                     "'selectmode' option should be 'none' or 'day'.")
         elif key is 'textvariable':
             if self._sel_date is not None:
                 if value is not None:
                     value.set(self._sel_date.strftime("%x"))
                 try:
                     if self._textvariable is not None:
                         self._textvariable.trace_remove(
                             'write', self._textvariable_trace_id)
                     if value is not None:
                         self._textvariable_trace_id = value.trace_add(
                             'write', self._textvariable_trace)
                 except AttributeError:
                     if self._textvariable is not None:
                         self._textvariable.trace_vdelete(
                             'w', self._textvariable_trace_id)
                     if value is not None:
                         value.trace('w', self._textvariable_trace)
             self._textvariable = value
         elif key is 'borderwidth':
             try:
                 bd = int(value)
                 self._cal_frame.pack_configure(padx=bd, pady=bd)
             except ValueError:
                 raise ValueError(
                     'expected integer for the borderwidth option.')
         elif key is 'state':
             if value not in ['normal', 'disabled']:
                 raise ValueError(
                     "bad state '%s': must be disabled or normal" % value)
             else:
                 state = '!' * (value == 'normal') + 'disabled'
                 self._l_year.state((state, ))
                 self._r_year.state((state, ))
                 self._l_month.state((state, ))
                 self._r_month.state((state, ))
                 for child in self._cal_frame.children.values():
                     child.state((state, ))
         elif key is "font":
             font = Font(self, value)
             prop = font.actual()
             self._font.configure(**prop)
             prop["size"] += 1
             self._header_font.configure(**prop)
             size = max(prop["size"], 10)
             self.style.configure('R.%s.TButton' % self._style_prefixe,
                                  arrowsize=size)
             self.style.configure('L.%s.TButton' % self._style_prefixe,
                                  arrowsize=size)
         elif key is "normalbackground":
             self.style.configure('cal.%s.TFrame' % self._style_prefixe,
                                  background=value)
             self.style.configure('normal.%s.TLabel' % self._style_prefixe,
                                  background=value)
             self.style.configure('normal_om.%s.TLabel' %
                                  self._style_prefixe,
                                  background=value)
         elif key is "normalforeground":
             self.style.configure('normal.%s.TLabel' % self._style_prefixe,
                                  foreground=value)
         elif key is "bordercolor":
             self.style.configure('cal.%s.TFrame' % self._style_prefixe,
                                  background=value)
         elif key is "othermonthforeground":
             self.style.configure('normal_om.%s.TLabel' %
                                  self._style_prefixe,
                                  foreground=value)
         elif key is "othermonthbackground":
             self.style.configure('normal_om.%s.TLabel' %
                                  self._style_prefixe,
                                  background=value)
         elif key is "othermonthweforeground":
             self.style.configure('we_om.%s.TLabel' % self._style_prefixe,
                                  foreground=value)
         elif key is "othermonthwebackground":
             self.style.configure('we_om.%s.TLabel' % self._style_prefixe,
                                  background=value)
         elif key is "selectbackground":
             self.style.configure('sel.%s.TLabel' % self._style_prefixe,
                                  background=value)
         elif key is "selectforeground":
             self.style.configure('sel.%s.TLabel' % self._style_prefixe,
                                  foreground=value)
         elif key is "disabledselectbackground":
             self.style.map('sel.%s.TLabel' % self._style_prefixe,
                            background=[('disabled', value)])
         elif key is "disabledselectforeground":
             self.style.map('sel.%s.TLabel' % self._style_prefixe,
                            foreground=[('disabled', value)])
         elif key is "disableddaybackground":
             self.style.map('%s.TLabel' % self._style_prefixe,
                            background=[('disabled', value)])
         elif key is "disableddayforeground":
             self.style.map('%s.TLabel' % self._style_prefixe,
                            foreground=[('disabled', value)])
         elif key is "weekendbackground":
             self.style.configure('we.%s.TLabel' % self._style_prefixe,
                                  background=value)
             self.style.configure('we_om.%s.TLabel' % self._style_prefixe,
                                  background=value)
         elif key is "weekendforeground":
             self.style.configure('we.%s.TLabel' % self._style_prefixe,
                                  foreground=value)
         elif key is "headersbackground":
             self.style.configure('headers.%s.TLabel' % self._style_prefixe,
                                  background=value)
         elif key is "headersforeground":
             self.style.configure('headers.%s.TLabel' % self._style_prefixe,
                                  foreground=value)
         elif key is "background":
             self.style.configure('main.%s.TFrame' % self._style_prefixe,
                                  background=value)
             self.style.configure('main.%s.TLabel' % self._style_prefixe,
                                  background=value)
             self.style.configure('R.%s.TButton' % self._style_prefixe,
                                  background=value,
                                  bordercolor=value,
                                  lightcolor=value,
                                  darkcolor=value)
             self.style.configure('L.%s.TButton' % self._style_prefixe,
                                  background=value,
                                  bordercolor=value,
                                  lightcolor=value,
                                  darkcolor=value)
         elif key is "foreground":
             self.style.configure('R.%s.TButton' % self._style_prefixe,
                                  arrowcolor=value)
             self.style.configure('L.%s.TButton' % self._style_prefixe,
                                  arrowcolor=value)
             self.style.configure('main.%s.TLabel' % self._style_prefixe,
                                  foreground=value)
         elif key is "cursor":
             ttk.Frame.configure(self, cursor=value)
         self._properties[key] = value
Exemple #35
0
    def __init__(self, master, font_dict={}, text="Abcd", title="Font Chooser",
                 **kwargs):
        """
        Create a new FontChooser instance.
        Arguments:
            master : Tk or Toplevel instance
                master window
            font_dict : dict
                dictionnary, like the one returned by the ``actual`` method of a ``Font`` object:
                ::
                    {'family': str,
                     'size': int,
                     'weight': 'bold'/'normal',
                     'slant': 'italic'/'roman',
                     'underline': bool,
                     'overstrike': bool}
            text : str
                text to be displayed in the preview label
            title : str
                window title
            kwargs : dict
                additional keyword arguments to be passed to ``Toplevel.__init__``
        """
        Toplevel.__init__(self, master, **kwargs)
        self.title(title)
        self.resizable(False, False)
        self.protocol("WM_DELETE_WINDOW", self.quit)
        self._validate_family = self.register(self.validate_font_family)
        self._validate_size = self.register(self.validate_font_size)

        # --- variable storing the chosen font
        self.res = ""

        style = Style(self)
        style.configure("prev.TLabel", background="white")
        bg = style.lookup("TLabel", "background")
        self.configure(bg=bg)

        # --- family list
        self.fonts = list(set(families()))
        self.fonts.append("TkDefaultFont")
        self.fonts.sort()
        for i in range(len(self.fonts)):
            self.fonts[i] = self.fonts[i].replace(" ", "\ ")
        max_length = int(2.5 * max([len(font) for font in self.fonts])) // 3
        self.sizes = ["%i" % i for i in (list(range(6, 17)) + list(range(18, 32, 2)))]
        # --- font default
        font_dict["weight"] = font_dict.get("weight", "normal")
        font_dict["slant"] = font_dict.get("slant", "roman")
        font_dict["underline"] = font_dict.get("underline", False)
        font_dict["overstrike"] = font_dict.get("overstrike", False)
        font_dict["family"] = font_dict.get("family",
                                            self.fonts[0].replace('\ ', ' '))
        font_dict["size"] = font_dict.get("size", 10)

        # --- creation of the widgets
        # ------ style parameters (bold, italic ...)
        options_frame = Frame(self, relief='groove', borderwidth=2)
        self.font_family = StringVar(self, " ".join(self.fonts))
        self.font_size = StringVar(self, " ".join(self.sizes))
        self.var_bold = BooleanVar(self, font_dict["weight"] == "bold")
        b_bold = Checkbutton(options_frame, text=TR["Bold"],
                             command=self.toggle_bold,
                             variable=self.var_bold)
        b_bold.grid(row=0, sticky="w", padx=4, pady=(4, 2))
        self.var_italic = BooleanVar(self, font_dict["slant"] == "italic")
        b_italic = Checkbutton(options_frame, text=TR["Italic"],
                               command=self.toggle_italic,
                               variable=self.var_italic)
        b_italic.grid(row=1, sticky="w", padx=4, pady=2)
        self.var_underline = BooleanVar(self, font_dict["underline"])
        b_underline = Checkbutton(options_frame, text=TR["Underline"],
                                  command=self.toggle_underline,
                                  variable=self.var_underline)
        b_underline.grid(row=2, sticky="w", padx=4, pady=2)
        self.var_overstrike = BooleanVar(self, font_dict["overstrike"])
        b_overstrike = Checkbutton(options_frame, text=TR["Overstrike"],
                                   variable=self.var_overstrike,
                                   command=self.toggle_overstrike)
        b_overstrike.grid(row=3, sticky="w", padx=4, pady=(2, 4))
        # ------ Size and family
        self.var_size = StringVar(self)
        self.entry_family = Entry(self, width=max_length, validate="key",
                                  validatecommand=(self._validate_family, "%d", "%S",
                                                   "%i", "%s", "%V"))
        self.entry_size = Entry(self, width=4, validate="key",
                                textvariable=self.var_size,
                                validatecommand=(self._validate_size, "%d", "%P", "%V"))
        self.list_family = Listbox(self, selectmode="browse",
                                   listvariable=self.font_family,
                                   highlightthickness=0,
                                   exportselection=False,
                                   width=max_length)
        self.list_size = Listbox(self, selectmode="browse",
                                 listvariable=self.font_size,
                                 highlightthickness=0,
                                 exportselection=False,
                                 width=4)
        scroll_family = Scrollbar(self, orient='vertical',
                                  command=self.list_family.yview)
        scroll_size = Scrollbar(self, orient='vertical',
                                command=self.list_size.yview)
        self.preview_font = Font(self, **font_dict)
        if len(text) > 30:
            text = text[:30]
        self.preview = Label(self, relief="groove", style="prev.TLabel",
                             text=text, font=self.preview_font,
                             anchor="center")

        # --- widget configuration
        self.list_family.configure(yscrollcommand=scroll_family.set)
        self.list_size.configure(yscrollcommand=scroll_size.set)

        self.entry_family.insert(0, font_dict["family"])
        self.entry_family.selection_clear()
        self.entry_family.icursor("end")
        self.entry_size.insert(0, font_dict["size"])

        try:
            i = self.fonts.index(self.entry_family.get().replace(" ", "\ "))
        except ValueError:
            # unknown font
            i = 0
        self.list_family.selection_clear(0, "end")
        self.list_family.selection_set(i)
        self.list_family.see(i)
        try:
            i = self.sizes.index(self.entry_size.get())
            self.list_size.selection_clear(0, "end")
            self.list_size.selection_set(i)
            self.list_size.see(i)
        except ValueError:
            # size not in list
            pass

        self.entry_family.grid(row=0, column=0, sticky="ew",
                               pady=(10, 1), padx=(10, 0))
        self.entry_size.grid(row=0, column=2, sticky="ew",
                             pady=(10, 1), padx=(10, 0))
        self.list_family.grid(row=1, column=0, sticky="nsew",
                              pady=(1, 10), padx=(10, 0))
        self.list_size.grid(row=1, column=2, sticky="nsew",
                            pady=(1, 10), padx=(10, 0))
        scroll_family.grid(row=1, column=1, sticky='ns', pady=(1, 10))
        scroll_size.grid(row=1, column=3, sticky='ns', pady=(1, 10))
        options_frame.grid(row=0, column=4, rowspan=2,
                           padx=10, pady=10, ipadx=10)

        self.preview.grid(row=2, column=0, columnspan=5, sticky="eswn",
                          padx=10, pady=(0, 10), ipadx=4, ipady=4)

        button_frame = Frame(self)
        button_frame.grid(row=3, column=0, columnspan=5, pady=(0, 10), padx=10)

        Button(button_frame, text="Ok",
               command=self.ok).grid(row=0, column=0, padx=4, sticky='ew')
        Button(button_frame, text=TR["Cancel"],
               command=self.quit).grid(row=0, column=1, padx=4, sticky='ew')
        self.list_family.bind('<<ListboxSelect>>', self.update_entry_family)
        self.list_size.bind('<<ListboxSelect>>', self.update_entry_size,
                            add=True)
        self.list_family.bind("<KeyPress>", self.keypress)
        self.entry_family.bind("<Return>", self.change_font_family)
        self.entry_family.bind("<Tab>", self.tab)
        self.entry_size.bind("<Return>", self.change_font_size)

        self.entry_family.bind("<Down>", self.down_family)
        self.entry_size.bind("<Down>", self.down_size)

        self.entry_family.bind("<Up>", self.up_family)
        self.entry_size.bind("<Up>", self.up_size)

        # bind Ctrl+A to select all instead of go to beginning
        self.bind_class("TEntry", "<Control-a>", self.select_all)

        self.wait_visibility(self)
        self.grab_set()
        self.entry_family.focus_set()
        self.lift()
def history_screen(cust_id, homepage):


    def on_closing():
        root.destroy()
        cursor.execute("SELECT CUSTOMER_NAME, CREDIT_POINTS, EMAIL_ID FROM CUSTOMER WHERE CUSTOMER_ID=%s;", [cust_id])
        records = cursor.fetchall()
        user_name = records[0][0]
        credit_points = records[0][1]
        email = records[0][2]
        import homepage
        homepage.homepage_screen(cust_id, email, user_name, credit_points)

    con = mysql.connect(
            host="localhost",
            user="******",
            password="******",
            database="FMS",
            port = 3306
            )

    dict_data = {
                    'journey_ids':[],
                    'date_book':[],
                    'date_journey':[],
                    'price':[],
                    'seat_type':[],
                    'seat_num':[],
                    'start':[],
                    'dest':[]
                }
    cursor = con.cursor()
    cursor.execute("SELECT JOURNEY_ID, DATE_OF_BOOKING, PRICE, SEAT_TYPE, SEAT_NO FROM BOOKS_FLIGHT WHERE CUSTOMER_ID=%s ORDER BY DATE_OF_BOOKING;", [cust_id])
    res = cursor.fetchall()
    if len(res)==0:
        messagebox.showwarning("Record not found!", "No bookings done yet.")
    else:
        homepage.destroy()
        dict_data['journey_ids']=[str(id[0]) for id in res]
        dict_data['date_book']=[str(id[1].strftime("%d-%m-%Y")) for id in res]
        dict_data['price']=[str(id[2]) for id in res]
        dict_data['seat_type']=[str(id[3]) for id in res]
        dict_data['seat_num']=[str(id[4]) for id in res]

        for journey in dict_data['journey_ids']:
            cursor.execute("SELECT START_CITY, DEST_CITY FROM ROUTE WHERE ROUTE_ID=(SELECT ROUTE_ID FROM FLIGHT WHERE FLIGHT_NO=(SELECT FLIGHT_NO FROM JOURNEY_FLIGHT WHERE JOURNEY_ID=%s));", [journey])
            cities=cursor.fetchmany(size=1)
            dict_data["start"].append(cities[0][0])
            dict_data["dest"].append(cities[0][1])
            cursor.execute("SELECT JOURNEY_DATE FROM JOURNEY_FLIGHT WHERE JOURNEY_ID=%s;", [journey])
            jdate=cursor.fetchmany(size=1)
            dict_data["date_journey"].append(jdate[0][0])


        root = tk.Tk()
        root.title('Flight Management System')
        root.geometry('720x420')
        root.resizable(height = False, width = False)
        container = tk.Frame(root, width=720, height=420, bg="blue")
        canvas = tk.Canvas(container, width=700, height=400)
        scrollbar = ttk.Scrollbar(container, orient="vertical", command=canvas.yview)
        scrollable_frame = ttk.Frame(canvas)

        scrollable_frame.bind(
            "<Configure>",
            lambda e: canvas.configure(
                scrollregion=canvas.bbox("all")
            )
        )

        canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
        canvas.configure(yscrollcommand=scrollbar.set)

        font10 = Font(family='Arial', size=10)
        font15 = Font(family='Arial', size=15)
        font20 = Font(family='Arial', size=20)
        font30 = Font(family='Arial', size=30, weight='bold')

        for i in range(len(dict_data['journey_ids'])):
            tk.Label(scrollable_frame, text="Booking No: "+str(i+1), font=font20).grid(column=0, row=0+(6*i), padx=50)
            tk.Label(scrollable_frame, text="Journey ID: "+dict_data['journey_ids'][i], font=font15).grid(column=0, row=1+(6*i), padx=50)
            tk.Label(scrollable_frame, text="Date of Booking: "+dict_data['date_book'][i], font=font10).grid(column=4, row=1+(6*i))

            tk.Label(scrollable_frame, text=dict_data['start'][i], font=font15).grid(column=0, row=2+(6*i))
            tk.Label(scrollable_frame, text=dict_data['dest'][i], font=font15).grid(column=4, row=2+(6*i))
            tk.Label(scrollable_frame, text=dict_data['date_journey'][i]).grid(column=2, row=1+(6*i), padx=(0, 50))


            tk.Label(scrollable_frame, text="---------------->", font=font20).grid(column=2, row=2+(6*i), padx=(0, 50))
            tk.Label(scrollable_frame, text="Seat:   "+dict_data['seat_type'][i]+"   "+dict_data['seat_num'][i], font=font10).grid(column=2, row=3+(6*i), padx=(0, 50), pady=(0, 30))
            tk.Label(scrollable_frame, text="Price: "+dict_data['price'][i], font=font10).grid(column=0, row=3+(6*i), pady=(0, 30))
            #tk.Label(scrollable_frame, text=dict_data['seat_num'][i]).grid(column=4, row=0+(6*i), padx=70)


            # tk.Label(scrollable_frame, text=dict_data['dest_airport'], font=font10).grid(column=4, row=3+(6*i))
            # tk.Label(scrollable_frame, text=dict_data['flight_id'][i], font=font10).grid(column=2, row=3+(6*i), sticky="N")

        n_rows = 30
        n_columns = 10
        for i in range(n_rows):
            root.grid_rowconfigure(i,  weight =1)
        for i in range(n_columns):
            root.grid_columnconfigure(i,  weight =1)

        container.pack()
        canvas.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")

        root.protocol("WM_DELETE_WINDOW", on_closing)

        root.mainloop()
Exemple #37
0
photo = PhotoImage(file="logo.png")
# setting the image as icon
root.iconphoto(False, photo)
#to make the size of the screen not expandable above the specified screen resolution
root.resizable(width='false', height='false')

#adding menu to the calculator
#creating a menubar
# we are calling the constructor of the imported Menu module class and pass in
# our main GUI instance
menubar = Menu(root)
# we configure our GUI to use the just created Menu as the
# menu for our GUI
root.config(menu=menubar)
#defining text font
helv15 = Font(family="Bradley Hand ITC", size=15, weight="bold")


class Calculator:
    value2 = 0.0
    operator1 = ""
    erase = False

    def __init__(self):
        self.internal_calc = False

    def __str__(self):
        return f'Scientific calculator'

    #configuring the menubar
    def to_exit(self):
Exemple #38
0
main_menu = Menu(root)
root.config(menu=main_menu)

fileMenu = Menu(main_menu)
main_menu.add_cascade(label='Программа', menu=fileMenu)

editMenu = Menu(main_menu)
main_menu.add_cascade(label='ProTools', menu=editMenu, state=DISABLED)

fileMenu.add_command(label='Лицензионное соглашение',
                     command=license_agreement)
fileMenu.add_command(label='Справка', command=faq)
fileMenu.add_separator()
fileMenu.add_command(label='Выход', command=_quit)

my_font = Font(family='Halvetica', size=10, weight='bold')

labelEUR = Label(root, text='  Валютная пара', font=my_font)
labelEUR.grid(row=1, column=1)

vEUR = [
    'EUR/USD', 'USD/JPY', 'GBP/USD', 'USD/CHF', 'EUR/CHF', 'AUD/USD',
    'USD/CAD', 'NZD/USD', 'EUR/GBP', 'EUR/JPY', 'GBP/JPY', 'AUD/JPY',
    'GBP/AUD', 'USD/CNH', 'XAU/USD', 'XAG/USD'
]
comboEUR = Combobox(root, values=vEUR, width=10)
comboEUR.set('EUR/USD')
comboEUR.grid(row=2, column=1)

labelStart = Label(root, text=' \nТочка старта', font=my_font)
labelStart.grid(row=3, column=1)
Exemple #39
0
    def __init__(self, master):
        master.title('Редактор файлов разметки')

        ################Шрифты###################
        italic_font = Font(family='Helvetica', size=12, slant='italic')
        bold_font = Font(family='Helvetica', size=12, weight='bold')
        underlined_font = Font(family='Helvetica', size=12, underline=1)
        overstrike_font = Font(family='Helvetica', size=12, overstrike=1)
        ###################################

        self.text_area = Text(master, undo=True)
        self.text_area.grid(row=2, column=0, columnspan=20)
        self.main_menu = Menu()
        master.config(menu=self.main_menu)
        # Создаем изображения
        self.paste_img = PhotoImage(file='images/ms_dos_pasteimg.PNG')
        self.copy_img = PhotoImage(file='images/ms_dos_copyimg.PNG')
        self.empty_checkbtn = PhotoImage(file='images/empty_checkbtn.png')
        self.full_checkbtn = PhotoImage(file='images/full_checkbtn.png')

        # Создаем меню File
        self.file_menu = Menu(self.main_menu, tearoff=0)
        self.main_menu.add_cascade(label='Файл', menu=self.file_menu)
        self.file_menu.add_command(label='Новый', command=self.new_file)
        self.file_menu.add_command(label='Открыть', command=self.open_file)
        self.file_menu.add_command(label='Сохранить', command=self.save_file)
        self.file_menu.add_command(label='Сохранить как',
                                   command=self.save_as_file)
        self.file_menu.add_separator()
        self.file_menu.add_command(label='Выход', command=master.quit)

        # Создаем меню Edit
        self.edit_menu = Menu(self.main_menu, tearoff=0)
        self.main_menu.add_cascade(label='Редактировать', menu=self.edit_menu)
        self.edit_menu.add_command(label='Отменить',
                                   command=self.text_area.edit_undo)
        self.edit_menu.add_command(label='Повторить',
                                   command=self.text_area.edit_redo)
        self.edit_menu.add_separator()
        self.edit_menu.add_command(label='Копировать', command=self.copy_text)
        self.edit_menu.add_command(label='Вырезать', command=self.cut_text)
        self.edit_menu.add_command(label='Вставить', command=self.paste_text)

        # Создаем кнопки
        # Кнопки копирования и вставления
        self.paste_btn = Button(master,
                                image=self.paste_img,
                                command=lambda: self.paste_text())
        self.paste_btn.grid(row=0, column=0)
        self.copy_btn = Button(master,
                               image=self.copy_img,
                               command=lambda: self.copy_text())
        self.copy_btn.grid(row=0, column=1)

        # Кнопки шрифтов
        self.italic_btn = Button(
            master,
            text='Н',
            font=italic_font,
            command=lambda: self.text_area.insert(END, '__'))
        self.italic_btn.grid(row=0, column=2)
        self.bold_btn = Button(
            master,
            text='Ж',
            font=bold_font,
            command=lambda: self.text_area.insert(END, '****'))
        self.bold_btn.grid(row=0, column=3)
        self.underline_btn = Button(
            master,
            text='П',
            font=underlined_font,
            command=lambda: self.text_area.insert(END, '<u></u>'))
        self.underline_btn.grid(row=0, column=4)
        self.overstrike_btn = Button(
            master,
            text='З',
            font=overstrike_font,
            command=lambda: self.text_area.insert(END, '~~~~'))
        self.overstrike_btn.grid(row=0, column=5)
        self.code_btn = Button(
            master,
            text='<>',
            command=lambda: self.text_area.insert(END, '``'))
        self.code_btn.grid(row=1, column=2)
        self.empty_btn = Button(
            master,
            image=self.empty_checkbtn,
            command=lambda: self.text_area.insert(END, '- [ ]'))
        self.empty_btn.grid(row=1, column=3)
        self.full_btn = Button(
            master,
            image=self.full_checkbtn,
            command=lambda: self.text_area.insert(END, '- [x]'))
        self.full_btn.grid(row=1, column=4)
        self.title1 = Button(master,
                             text='З1',
                             command=lambda: self.text_area.insert(END, '#'))
        self.title1.grid(row=0, column=6)
        self.title2 = Button(master,
                             text='З2',
                             command=lambda: self.text_area.insert(END, '##'))
        self.title2.grid(row=0, column=7)
        self.title3 = Button(master,
                             text='З3',
                             command=lambda: self.text_area.insert(END, '###'))
        self.title3.grid(row=0, column=8)
        self.title4 = Button(
            master,
            text='З4',
            command=lambda: self.text_area.insert(END, '####'))
        self.title4.grid(row=0, column=9)
        self.title5 = Button(
            master,
            text='З5',
            command=lambda: self.text_area.insert(END, '#####'))
        self.title5.grid(row=1, column=5)
        self.title6 = Button(
            master,
            text='З6',
            command=lambda: self.text_area.insert(END, '######'))
        self.title6.grid(row=1, column=6)
        self.quote = Button(master,
                            text='Ц',
                            command=lambda: self.text_area.insert(END, '>'))
        self.quote.grid(row=1, column=7)
        self.notenumlist = Button(
            master,
            text='НПС',
            command=lambda: self.text_area.insert(END, '* '))
        self.notenumlist.grid(row=1, column=8)
        self.enumlist = Button(
            master,
            text='ПС',
            command=lambda: self.text_area.insert(END, 'Номер. '))
        self.enumlist.grid(row=1, column=9)
        self.separator = Button(
            master,
            text='Рздл',
            command=lambda: self.text_area.insert(END, '***'))
        self.separator.grid(row=0, column=10)
        self.hyperlink = Button(
            master,
            text='ГС',
            command=lambda: self.text_area.insert(
                END, '[текст ссылки](ссылка "необязательая подсказка")'))
        self.hyperlink.grid(row=0, column=11)
        self.passable_hyperlink = Button(
            master,
            text='СГС',
            command=lambda: self.text_area.insert(
                END, '[айди ссылки]: ссылка "необязательая подсказка"'))
        self.passable_hyperlink.grid(row=1, column=11)
        self.picture = Button(
            master,
            text='Изоб.',
            command=lambda: self.text_area.insert(
                END, '![текст](/путь/к/изображению "Подсказка")'))
        self.picture.grid(row=1, column=10)
Exemple #40
0
from tkinter import *
from tkinter.font import Font

root = Tk()
my_font = Font(family="Helvetica",
               size=24,
               weight="bold",
               slant="italic",
               underline=1,
               overstrike=1)
'''fonts=list(())
for i in fonts:
    print(i)'''

txt = Text(root,
           height=5,
           width=30,
           font=my_font,
           wrap=WORD,
           padx=10,
           pady=10,
           bd=5,
           selectbackground="red")
txt.insert(INSERT, "Welcome you all")
txt.pack()

mainloop()
Exemple #41
0
    else:
        button.config(command=wel)


'''canvas = Canvas(width = 300, height = 200)
    # pack the canvas into a frame/form
canvas.pack(expand = YES, fill = BOTH)
    # load the .gif image file
    # put in your own gif file here, may need to add full path
gif1 = PhotoImage(file = 'LPU.Gif')
    # put gif image on canvas
  # pic's upper left corner (NW) on the canvas is at x=50 y=10
canvas.create_image(50, 10, image = gif1, anchor = NW)
    # run it ...'''
frame2 = Frame(top, width=300, height=300)
my_font2 = Font(family="Times New Roman", size=25)
name = Label(top, text="Registration number", font=('arial', 13, 'bold'))
password = Label(top, text="Password", font=('arial', 13, 'bold'))
entry1 = Entry(top, font=('arial', 13, 'bold'), bg="powder blue")
entry2 = Entry(top, show="*", font=('arial', 13, 'bold'), bg="powder blue")
button = Button(top, text="login", command=lambda: [click_me(), select()])
name.grid(row=0, column=0)
entry1.grid(row=0, column=1, sticky=W)
password.grid(row=1)
entry2.grid(row=1, column=1, sticky=W)
#tick=Checkbutton(top,text="keep me logged in")
#tick.grid(columnspan=2)
button.grid()
frame2.grid()
top.mainloop()
Exemple #42
0
    day, month, year = Date.split("-")
    train_no_length = len(train_no)
    if train_no_length < 5 or len(Date) > 10 or len(Date) < 7:
        messagebox.showerror("missing value", "something missing")
    elif train_no_length > 5:
        messagebox.showerror("to long", "train number is too long")
    else:
        webbrowser.open("https://runningstatus.in/status/" + str(train_no) +
                        "-on-" + year + month + day)
        l4 = tk.Label(root, text="thanks for using our app").grid(row=5,
                                                                  column=1)


fonts = Font(size=30,
             family='HelvLight',
             weight='bold',
             slant='italic',
             underline=1,
             overstrike=0)

l1 = ttk.Label(root, text="Welcome to running status", font=fonts)
l1.grid(row=0, columnspan=9, padx=10, pady=20)

labelframe = tk.LabelFrame(root, text="Enter train details")

l2 = tk.Label(labelframe, text="Enter train number", fg="blue").grid(row=0,
                                                                     column=0,
                                                                     padx=4,
                                                                     pady=4)
l3 = tk.Label(labelframe, text="Enter running date", fg="blue").grid(row=1,
                                                                     column=0,
                                                                     padx=4,
Exemple #43
0
    def __init__(self, master=None, **kw):
        """
        Construct a Calendar with parent master.

        STANDARD OPTIONS

            cursor, font, borderwidth, state

        WIDGET-SPECIFIC OPTIONS

            year, month: initially displayed month, default is current month
            day: initially selected day, if month or year is given but not
                day, no initial selection, otherwise, default is today
            locale: locale to use, e.g. 'fr_FR.utf-8'
                    (the locale need to be installed, otherwise it will
                     raise 'locale.Error: unsupported locale setting')
            selectmode: "none" or "day" (default) define whether the user
                        can change the selected day with a mouse click
            textvariable: StringVar that will contain the currently selected date as str
            background: background color of calendar border and month/year name
            foreground: foreground color of month/year name
            bordercolor: day border color
            selectbackground: background color of selected day
            selectforeground: foreground color of selected day
            disabledselectbackground: background color of selected day in disabled state
            disabledselectforeground: foreground color of selected day in disabled state
            normalbackground: background color of normal week days
            normalforeground: foreground color of normal week days
            othermonthforeground: foreground color of normal week days
                                  belonging to the previous/next month
            othermonthbackground: background color of normal week days
                                  belonging to the previous/next month
            othermonthweforeground: foreground color of week-end days
                                    belonging to the previous/next month
            othermonthwebackground: background color of week-end days
                                    belonging to the previous/next month
            weekendbackground: background color of week-end days
            weekendforeground: foreground color of week-end days
            headersbackground: background color of day names and week numbers
            headersforeground: foreground color of day names and week numbers
            disableddaybackground: background color of days in disabled state
            disableddayforeground: foreground color of days in disabled state

        VIRTUAL EVENTS

            A <<CalendarSelected>> event is generated each time the user
            selects a day with the mouse.
        """

        curs = kw.pop("cursor", "")
        font = kw.pop("font", "Liberation\ Sans 9")
        classname = kw.pop('class_', "Calendar")
        name = kw.pop('name', None)
        ttk.Frame.__init__(self,
                           master,
                           class_=classname,
                           cursor=curs,
                           name=name)
        self._style_prefixe = str(self)
        ttk.Frame.configure(self, style='main.%s.TFrame' % self._style_prefixe)

        self._textvariable = kw.pop("textvariable", None)

        self._font = Font(self, font)
        prop = self._font.actual()
        prop["size"] += 1
        self._header_font = Font(self, **prop)

        # state
        state = kw.get('state', 'normal')

        try:
            bd = int(kw.pop('borderwidth', 2))
        except ValueError:
            raise ValueError('expected integer for the borderwidth option.')

        # --- date
        today = self.date.today()

        if (("month" in kw) or ("year" in kw)) and ("day" not in kw):
            month = kw.pop("month", today.month)
            year = kw.pop('year', today.year)
            self._sel_date = None  # selected day
        else:
            day = kw.pop('day', today.day)
            month = kw.pop("month", today.month)
            year = kw.pop('year', today.year)
            try:
                self._sel_date = self.date(year, month, day)  # selected day
                if self._textvariable is not None:
                    self._textvariable.set(self._sel_date.strftime("%x"))
            except ValueError:
                self._sel_date = None

        self._date = self.date(year, month,
                               1)  # (year, month) displayed by the calendar

        # --- selectmode
        selectmode = kw.pop("selectmode", "day")
        if selectmode not in ("none", "day"):
            raise ValueError("'selectmode' option should be 'none' or 'day'.")
        # --- locale
        locale = kw.pop("locale", None)

        if locale is None:
            self._cal = calendar.TextCalendar(calendar.MONDAY)
        else:
            self._cal = calendar.LocaleTextCalendar(calendar.MONDAY, locale)

        # --- style
        self.style = ttk.Style(self)
        active_bg = self.style.lookup('TEntry', 'selectbackground',
                                      ('focus', ))
        dis_active_bg = self.style.lookup('TEntry', 'selectbackground',
                                          ('disabled', ))
        dis_bg = self.style.lookup('TLabel', 'background', ('disabled', ))
        dis_fg = self.style.lookup('TLabel', 'foreground', ('disabled', ))

        # --- properties
        options = [
            'cursor', 'font', 'borderwidth', 'state', 'selectmode',
            'textvariable', 'locale', 'selectbackground', 'selectforeground',
            'disabledselectbackground', 'disabledselectforeground',
            'normalbackground', 'normalforeground', 'background', 'foreground',
            'bordercolor', 'othermonthforeground', 'othermonthbackground',
            'othermonthweforeground', 'othermonthwebackground',
            'weekendbackground', 'weekendforeground', 'headersbackground',
            'headersforeground', 'disableddaybackground',
            'disableddayforeground'
        ]

        keys = list(kw.keys())
        for option in keys:
            if option not in options:
                del (kw[option])

        self._properties = {
            "cursor": curs,
            "font": font,
            "borderwidth": bd,
            "state": state,
            "locale": locale,
            "selectmode": selectmode,
            'textvariable': self._textvariable,
            'selectbackground': active_bg,
            'selectforeground': 'white',
            'disabledselectbackground': dis_active_bg,
            'disabledselectforeground': 'white',
            'normalbackground': 'white',
            'normalforeground': 'black',
            'background': 'gray30',
            'foreground': 'white',
            'bordercolor': 'gray70',
            'othermonthforeground': 'gray45',
            'othermonthbackground': 'gray93',
            'othermonthweforeground': 'gray45',
            'othermonthwebackground': 'gray75',
            'weekendbackground': 'gray80',
            'weekendforeground': 'gray30',
            'headersbackground': 'gray70',
            'headersforeground': 'black',
            'disableddaybackground': dis_bg,
            'disableddayforeground': dis_fg
        }
        self._properties.update(kw)

        # --- init calendar
        # --- *-- header: month - year
        header = ttk.Frame(self, style='main.%s.TFrame' % self._style_prefixe)

        f_month = ttk.Frame(header,
                            style='main.%s.TFrame' % self._style_prefixe)
        self._l_month = ttk.Button(f_month,
                                   style='L.%s.TButton' % self._style_prefixe,
                                   command=self._prev_month)
        self._header_month = ttk.Label(f_month,
                                       width=10,
                                       anchor='center',
                                       style='main.%s.TLabel' %
                                       self._style_prefixe,
                                       font=self._header_font)
        self._r_month = ttk.Button(f_month,
                                   style='R.%s.TButton' % self._style_prefixe,
                                   command=self._next_month)
        self._l_month.pack(side='left', fill="y")
        self._header_month.pack(side='left', padx=4)
        self._r_month.pack(side='left', fill="y")

        f_year = ttk.Frame(header,
                           style='main.%s.TFrame' % self._style_prefixe)
        self._l_year = ttk.Button(f_year,
                                  style='L.%s.TButton' % self._style_prefixe,
                                  command=self._prev_year)
        self._header_year = ttk.Label(f_year,
                                      width=4,
                                      anchor='center',
                                      style='main.%s.TLabel' %
                                      self._style_prefixe,
                                      font=self._header_font)
        self._r_year = ttk.Button(f_year,
                                  style='R.%s.TButton' % self._style_prefixe,
                                  command=self._next_year)
        self._l_year.pack(side='left', fill="y")
        self._header_year.pack(side='left', padx=4)
        self._r_year.pack(side='left', fill="y")

        f_month.pack(side='left', fill='x')
        f_year.pack(side='right')

        # --- *-- calendar
        self._cal_frame = ttk.Frame(self,
                                    style='cal.%s.TFrame' %
                                    self._style_prefixe)

        ttk.Label(self._cal_frame,
                  style='headers.%s.TLabel' % self._style_prefixe).grid(
                      row=0, column=0, sticky="eswn")

        for i, d in enumerate(self._cal.formatweekheader(3).split()):
            self._cal_frame.columnconfigure(i + 1, weight=1)
            ttk.Label(self._cal_frame,
                      font=self._font,
                      style='headers.%s.TLabel' % self._style_prefixe,
                      anchor="center",
                      text=d,
                      width=4).grid(row=0,
                                    column=i + 1,
                                    sticky="ew",
                                    pady=(0, 1))
        self._week_nbs = []
        self._calendar = []
        for i in range(1, 7):
            self._cal_frame.rowconfigure(i, weight=1)
            wlabel = ttk.Label(self._cal_frame,
                               style='headers.%s.TLabel' % self._style_prefixe,
                               font=self._font,
                               padding=2,
                               anchor="e",
                               width=2)
            self._week_nbs.append(wlabel)
            wlabel.grid(row=i, column=0, sticky="esnw", padx=(0, 1))
            self._calendar.append([])
            for j in range(1, 8):
                label = ttk.Label(self._cal_frame,
                                  style='normal.%s.TLabel' %
                                  self._style_prefixe,
                                  font=self._font,
                                  anchor="center")
                self._calendar[-1].append(label)
                label.grid(row=i,
                           column=j,
                           padx=(0, 1),
                           pady=(0, 1),
                           sticky="nsew")
                if selectmode is "day":
                    label.bind("<1>", self._on_click)

        # --- *-- pack main elements
        header.pack(fill="x", padx=2, pady=2)
        self._cal_frame.pack(fill="both", expand=True, padx=bd, pady=bd)

        self.config(state=state)

        # --- bindings
        self.bind('<<ThemeChanged>>', self._setup_style)

        self._setup_style()
        self._display_calendar()

        if self._textvariable is not None:
            try:
                self._textvariable_trace_id = self._textvariable.trace_add(
                    'write', self._textvariable_trace)
            except AttributeError:
                self._textvariable_trace_id = self._textvariable.trace(
                    'w', self._textvariable_trace)
Exemple #44
0
for i in range(0,size):
    for j in range(0,size):
        board[i][j]= Button(root, text = "",bg="#26282b")
        board[i][j].row=i
        board[i][j].col=j
        board[i][j].configure(command=board[i][j].onClick,width=root_width,height=root_height)
        board[i][j].grid(column=j,row=i) # set Button grid

for i in range(0,size):
    l=Label(root,text="",width=1,height=root_height,bg="black")
    l.grid(column=size+1,row=i)

for i in range(0,size):
    for j in range(0,size):
        label_board[i][j]=Button(root,text="",width=root_width,height=root_height,bg="#26282b",command=refresh)
        label_board[i][j].grid(column=size+2+j,row=i)
ab_label=Label(root,text="Alpha Beta Prunning",bg="black",fg="#ff004d")
ab_label.grid(column=0,row=size+1,columnspan=size)
mm_label=Label(root,text="Minimax",bg="black",fg="#00fff5")
mm_label.grid(column=size+1,row=size+1,columnspan=size)
#playAi()
#current="o"
#n_move+=1
font=Font(size=15)
indicator_label=Label(root,text="Please play on the left-side board.",bg="black",fg="#ffd700",font=font)
indicator_label.grid(column=10,row=18,columnspan=size)
plot(y1=time_array,y2=minmax_time_array)
movesplot(y1=ab_moves_array,y2=minmax_moves_array)
evalplot(y1=eval_scores_array)
root.mainloop()  #render screen
Exemple #45
0
class Calendar(ttk.Frame):
    """Calendar widget."""
    date = calendar.datetime.date
    timedelta = calendar.datetime.timedelta
    strptime = calendar.datetime.datetime.strptime
    strftime = calendar.datetime.datetime.strftime

    def __init__(self, master=None, **kw):
        """
        Construct a Calendar with parent master.

        STANDARD OPTIONS

            cursor, font, borderwidth, state

        WIDGET-SPECIFIC OPTIONS

            year, month: initially displayed month, default is current month
            day: initially selected day, if month or year is given but not
                day, no initial selection, otherwise, default is today
            locale: locale to use, e.g. 'fr_FR.utf-8'
                    (the locale need to be installed, otherwise it will
                     raise 'locale.Error: unsupported locale setting')
            selectmode: "none" or "day" (default) define whether the user
                        can change the selected day with a mouse click
            textvariable: StringVar that will contain the currently selected date as str
            background: background color of calendar border and month/year name
            foreground: foreground color of month/year name
            bordercolor: day border color
            selectbackground: background color of selected day
            selectforeground: foreground color of selected day
            disabledselectbackground: background color of selected day in disabled state
            disabledselectforeground: foreground color of selected day in disabled state
            normalbackground: background color of normal week days
            normalforeground: foreground color of normal week days
            othermonthforeground: foreground color of normal week days
                                  belonging to the previous/next month
            othermonthbackground: background color of normal week days
                                  belonging to the previous/next month
            othermonthweforeground: foreground color of week-end days
                                    belonging to the previous/next month
            othermonthwebackground: background color of week-end days
                                    belonging to the previous/next month
            weekendbackground: background color of week-end days
            weekendforeground: foreground color of week-end days
            headersbackground: background color of day names and week numbers
            headersforeground: foreground color of day names and week numbers
            disableddaybackground: background color of days in disabled state
            disableddayforeground: foreground color of days in disabled state

        VIRTUAL EVENTS

            A <<CalendarSelected>> event is generated each time the user
            selects a day with the mouse.
        """

        curs = kw.pop("cursor", "")
        font = kw.pop("font", "Liberation\ Sans 9")
        classname = kw.pop('class_', "Calendar")
        name = kw.pop('name', None)
        ttk.Frame.__init__(self,
                           master,
                           class_=classname,
                           cursor=curs,
                           name=name)
        self._style_prefixe = str(self)
        ttk.Frame.configure(self, style='main.%s.TFrame' % self._style_prefixe)

        self._textvariable = kw.pop("textvariable", None)

        self._font = Font(self, font)
        prop = self._font.actual()
        prop["size"] += 1
        self._header_font = Font(self, **prop)

        # state
        state = kw.get('state', 'normal')

        try:
            bd = int(kw.pop('borderwidth', 2))
        except ValueError:
            raise ValueError('expected integer for the borderwidth option.')

        # --- date
        today = self.date.today()

        if (("month" in kw) or ("year" in kw)) and ("day" not in kw):
            month = kw.pop("month", today.month)
            year = kw.pop('year', today.year)
            self._sel_date = None  # selected day
        else:
            day = kw.pop('day', today.day)
            month = kw.pop("month", today.month)
            year = kw.pop('year', today.year)
            try:
                self._sel_date = self.date(year, month, day)  # selected day
                if self._textvariable is not None:
                    self._textvariable.set(self._sel_date.strftime("%x"))
            except ValueError:
                self._sel_date = None

        self._date = self.date(year, month,
                               1)  # (year, month) displayed by the calendar

        # --- selectmode
        selectmode = kw.pop("selectmode", "day")
        if selectmode not in ("none", "day"):
            raise ValueError("'selectmode' option should be 'none' or 'day'.")
        # --- locale
        locale = kw.pop("locale", None)

        if locale is None:
            self._cal = calendar.TextCalendar(calendar.MONDAY)
        else:
            self._cal = calendar.LocaleTextCalendar(calendar.MONDAY, locale)

        # --- style
        self.style = ttk.Style(self)
        active_bg = self.style.lookup('TEntry', 'selectbackground',
                                      ('focus', ))
        dis_active_bg = self.style.lookup('TEntry', 'selectbackground',
                                          ('disabled', ))
        dis_bg = self.style.lookup('TLabel', 'background', ('disabled', ))
        dis_fg = self.style.lookup('TLabel', 'foreground', ('disabled', ))

        # --- properties
        options = [
            'cursor', 'font', 'borderwidth', 'state', 'selectmode',
            'textvariable', 'locale', 'selectbackground', 'selectforeground',
            'disabledselectbackground', 'disabledselectforeground',
            'normalbackground', 'normalforeground', 'background', 'foreground',
            'bordercolor', 'othermonthforeground', 'othermonthbackground',
            'othermonthweforeground', 'othermonthwebackground',
            'weekendbackground', 'weekendforeground', 'headersbackground',
            'headersforeground', 'disableddaybackground',
            'disableddayforeground'
        ]

        keys = list(kw.keys())
        for option in keys:
            if option not in options:
                del (kw[option])

        self._properties = {
            "cursor": curs,
            "font": font,
            "borderwidth": bd,
            "state": state,
            "locale": locale,
            "selectmode": selectmode,
            'textvariable': self._textvariable,
            'selectbackground': active_bg,
            'selectforeground': 'white',
            'disabledselectbackground': dis_active_bg,
            'disabledselectforeground': 'white',
            'normalbackground': 'white',
            'normalforeground': 'black',
            'background': 'gray30',
            'foreground': 'white',
            'bordercolor': 'gray70',
            'othermonthforeground': 'gray45',
            'othermonthbackground': 'gray93',
            'othermonthweforeground': 'gray45',
            'othermonthwebackground': 'gray75',
            'weekendbackground': 'gray80',
            'weekendforeground': 'gray30',
            'headersbackground': 'gray70',
            'headersforeground': 'black',
            'disableddaybackground': dis_bg,
            'disableddayforeground': dis_fg
        }
        self._properties.update(kw)

        # --- init calendar
        # --- *-- header: month - year
        header = ttk.Frame(self, style='main.%s.TFrame' % self._style_prefixe)

        f_month = ttk.Frame(header,
                            style='main.%s.TFrame' % self._style_prefixe)
        self._l_month = ttk.Button(f_month,
                                   style='L.%s.TButton' % self._style_prefixe,
                                   command=self._prev_month)
        self._header_month = ttk.Label(f_month,
                                       width=10,
                                       anchor='center',
                                       style='main.%s.TLabel' %
                                       self._style_prefixe,
                                       font=self._header_font)
        self._r_month = ttk.Button(f_month,
                                   style='R.%s.TButton' % self._style_prefixe,
                                   command=self._next_month)
        self._l_month.pack(side='left', fill="y")
        self._header_month.pack(side='left', padx=4)
        self._r_month.pack(side='left', fill="y")

        f_year = ttk.Frame(header,
                           style='main.%s.TFrame' % self._style_prefixe)
        self._l_year = ttk.Button(f_year,
                                  style='L.%s.TButton' % self._style_prefixe,
                                  command=self._prev_year)
        self._header_year = ttk.Label(f_year,
                                      width=4,
                                      anchor='center',
                                      style='main.%s.TLabel' %
                                      self._style_prefixe,
                                      font=self._header_font)
        self._r_year = ttk.Button(f_year,
                                  style='R.%s.TButton' % self._style_prefixe,
                                  command=self._next_year)
        self._l_year.pack(side='left', fill="y")
        self._header_year.pack(side='left', padx=4)
        self._r_year.pack(side='left', fill="y")

        f_month.pack(side='left', fill='x')
        f_year.pack(side='right')

        # --- *-- calendar
        self._cal_frame = ttk.Frame(self,
                                    style='cal.%s.TFrame' %
                                    self._style_prefixe)

        ttk.Label(self._cal_frame,
                  style='headers.%s.TLabel' % self._style_prefixe).grid(
                      row=0, column=0, sticky="eswn")

        for i, d in enumerate(self._cal.formatweekheader(3).split()):
            self._cal_frame.columnconfigure(i + 1, weight=1)
            ttk.Label(self._cal_frame,
                      font=self._font,
                      style='headers.%s.TLabel' % self._style_prefixe,
                      anchor="center",
                      text=d,
                      width=4).grid(row=0,
                                    column=i + 1,
                                    sticky="ew",
                                    pady=(0, 1))
        self._week_nbs = []
        self._calendar = []
        for i in range(1, 7):
            self._cal_frame.rowconfigure(i, weight=1)
            wlabel = ttk.Label(self._cal_frame,
                               style='headers.%s.TLabel' % self._style_prefixe,
                               font=self._font,
                               padding=2,
                               anchor="e",
                               width=2)
            self._week_nbs.append(wlabel)
            wlabel.grid(row=i, column=0, sticky="esnw", padx=(0, 1))
            self._calendar.append([])
            for j in range(1, 8):
                label = ttk.Label(self._cal_frame,
                                  style='normal.%s.TLabel' %
                                  self._style_prefixe,
                                  font=self._font,
                                  anchor="center")
                self._calendar[-1].append(label)
                label.grid(row=i,
                           column=j,
                           padx=(0, 1),
                           pady=(0, 1),
                           sticky="nsew")
                if selectmode is "day":
                    label.bind("<1>", self._on_click)

        # --- *-- pack main elements
        header.pack(fill="x", padx=2, pady=2)
        self._cal_frame.pack(fill="both", expand=True, padx=bd, pady=bd)

        self.config(state=state)

        # --- bindings
        self.bind('<<ThemeChanged>>', self._setup_style)

        self._setup_style()
        self._display_calendar()

        if self._textvariable is not None:
            try:
                self._textvariable_trace_id = self._textvariable.trace_add(
                    'write', self._textvariable_trace)
            except AttributeError:
                self._textvariable_trace_id = self._textvariable.trace(
                    'w', self._textvariable_trace)

    def __getitem__(self, key):
        """Return the resource value for a KEY given as string."""
        try:
            return self._properties[key]
        except KeyError:
            raise AttributeError("Calendar object has no attribute %s." % key)

    def __setitem__(self, key, value):
        if key not in self._properties:
            raise AttributeError("Calendar object has no attribute %s." % key)
        elif key is "locale":
            raise AttributeError("This attribute cannot be modified.")
        else:
            if key is "selectmode":
                if value is "none":
                    for week in self._calendar:
                        for day in week:
                            day.unbind("<1>")
                elif value is "day":
                    for week in self._calendar:
                        for day in week:
                            day.bind("<1>", self._on_click)
                else:
                    raise ValueError(
                        "'selectmode' option should be 'none' or 'day'.")
            elif key is 'textvariable':
                if self._sel_date is not None:
                    if value is not None:
                        value.set(self._sel_date.strftime("%x"))
                    try:
                        if self._textvariable is not None:
                            self._textvariable.trace_remove(
                                'write', self._textvariable_trace_id)
                        if value is not None:
                            self._textvariable_trace_id = value.trace_add(
                                'write', self._textvariable_trace)
                    except AttributeError:
                        if self._textvariable is not None:
                            self._textvariable.trace_vdelete(
                                'w', self._textvariable_trace_id)
                        if value is not None:
                            value.trace('w', self._textvariable_trace)
                self._textvariable = value
            elif key is 'borderwidth':
                try:
                    bd = int(value)
                    self._cal_frame.pack_configure(padx=bd, pady=bd)
                except ValueError:
                    raise ValueError(
                        'expected integer for the borderwidth option.')
            elif key is 'state':
                if value not in ['normal', 'disabled']:
                    raise ValueError(
                        "bad state '%s': must be disabled or normal" % value)
                else:
                    state = '!' * (value == 'normal') + 'disabled'
                    self._l_year.state((state, ))
                    self._r_year.state((state, ))
                    self._l_month.state((state, ))
                    self._r_month.state((state, ))
                    for child in self._cal_frame.children.values():
                        child.state((state, ))
            elif key is "font":
                font = Font(self, value)
                prop = font.actual()
                self._font.configure(**prop)
                prop["size"] += 1
                self._header_font.configure(**prop)
                size = max(prop["size"], 10)
                self.style.configure('R.%s.TButton' % self._style_prefixe,
                                     arrowsize=size)
                self.style.configure('L.%s.TButton' % self._style_prefixe,
                                     arrowsize=size)
            elif key is "normalbackground":
                self.style.configure('cal.%s.TFrame' % self._style_prefixe,
                                     background=value)
                self.style.configure('normal.%s.TLabel' % self._style_prefixe,
                                     background=value)
                self.style.configure('normal_om.%s.TLabel' %
                                     self._style_prefixe,
                                     background=value)
            elif key is "normalforeground":
                self.style.configure('normal.%s.TLabel' % self._style_prefixe,
                                     foreground=value)
            elif key is "bordercolor":
                self.style.configure('cal.%s.TFrame' % self._style_prefixe,
                                     background=value)
            elif key is "othermonthforeground":
                self.style.configure('normal_om.%s.TLabel' %
                                     self._style_prefixe,
                                     foreground=value)
            elif key is "othermonthbackground":
                self.style.configure('normal_om.%s.TLabel' %
                                     self._style_prefixe,
                                     background=value)
            elif key is "othermonthweforeground":
                self.style.configure('we_om.%s.TLabel' % self._style_prefixe,
                                     foreground=value)
            elif key is "othermonthwebackground":
                self.style.configure('we_om.%s.TLabel' % self._style_prefixe,
                                     background=value)
            elif key is "selectbackground":
                self.style.configure('sel.%s.TLabel' % self._style_prefixe,
                                     background=value)
            elif key is "selectforeground":
                self.style.configure('sel.%s.TLabel' % self._style_prefixe,
                                     foreground=value)
            elif key is "disabledselectbackground":
                self.style.map('sel.%s.TLabel' % self._style_prefixe,
                               background=[('disabled', value)])
            elif key is "disabledselectforeground":
                self.style.map('sel.%s.TLabel' % self._style_prefixe,
                               foreground=[('disabled', value)])
            elif key is "disableddaybackground":
                self.style.map('%s.TLabel' % self._style_prefixe,
                               background=[('disabled', value)])
            elif key is "disableddayforeground":
                self.style.map('%s.TLabel' % self._style_prefixe,
                               foreground=[('disabled', value)])
            elif key is "weekendbackground":
                self.style.configure('we.%s.TLabel' % self._style_prefixe,
                                     background=value)
                self.style.configure('we_om.%s.TLabel' % self._style_prefixe,
                                     background=value)
            elif key is "weekendforeground":
                self.style.configure('we.%s.TLabel' % self._style_prefixe,
                                     foreground=value)
            elif key is "headersbackground":
                self.style.configure('headers.%s.TLabel' % self._style_prefixe,
                                     background=value)
            elif key is "headersforeground":
                self.style.configure('headers.%s.TLabel' % self._style_prefixe,
                                     foreground=value)
            elif key is "background":
                self.style.configure('main.%s.TFrame' % self._style_prefixe,
                                     background=value)
                self.style.configure('main.%s.TLabel' % self._style_prefixe,
                                     background=value)
                self.style.configure('R.%s.TButton' % self._style_prefixe,
                                     background=value,
                                     bordercolor=value,
                                     lightcolor=value,
                                     darkcolor=value)
                self.style.configure('L.%s.TButton' % self._style_prefixe,
                                     background=value,
                                     bordercolor=value,
                                     lightcolor=value,
                                     darkcolor=value)
            elif key is "foreground":
                self.style.configure('R.%s.TButton' % self._style_prefixe,
                                     arrowcolor=value)
                self.style.configure('L.%s.TButton' % self._style_prefixe,
                                     arrowcolor=value)
                self.style.configure('main.%s.TLabel' % self._style_prefixe,
                                     foreground=value)
            elif key is "cursor":
                ttk.Frame.configure(self, cursor=value)
            self._properties[key] = value

    def _textvariable_trace(self, *args):
        if self._properties.get("selectmode") is "day":
            date = self._textvariable.get()
            if not date:
                self._remove_selection()
                self._sel_date = None
            else:
                try:
                    self._sel_date = self.strptime(date, "%x")
                except Exception as e:
                    if self._sel_date is None:
                        self._textvariable.set('')
                    else:
                        self._textvariable.set(self._sel_date.strftime('%x'))
                    raise type(e)("%r is not a valid date." % date)
                else:
                    self._date = self._sel_date.replace(day=1)
                    self._display_calendar()
                    self._display_selection()

    def _setup_style(self, event=None):
        """Configure style."""
        self.style.layout('L.%s.TButton' % self._style_prefixe,
                          [('Button.focus', {
                              'children': [('Button.leftarrow', None)]
                          })])
        self.style.layout('R.%s.TButton' % self._style_prefixe,
                          [('Button.focus', {
                              'children': [('Button.rightarrow', None)]
                          })])
        active_bg = self.style.lookup('TEntry', 'selectbackground',
                                      ('focus', ))

        sel_bg = self._properties.get('selectbackground')
        sel_fg = self._properties.get('selectforeground')
        dis_sel_bg = self._properties.get('disabledselectbackground')
        dis_sel_fg = self._properties.get('disabledselectforeground')
        dis_bg = self._properties.get('disableddaybackground')
        dis_fg = self._properties.get('disableddayforeground')
        cal_bg = self._properties.get('normalbackground')
        cal_fg = self._properties.get('normalforeground')
        hd_bg = self._properties.get("headersbackground")
        hd_fg = self._properties.get("headersforeground")
        bg = self._properties.get('background')
        fg = self._properties.get('foreground')
        bc = self._properties.get('bordercolor')
        om_fg = self._properties.get('othermonthforeground')
        om_bg = self._properties.get('othermonthbackground')
        omwe_fg = self._properties.get('othermonthweforeground')
        omwe_bg = self._properties.get('othermonthwebackground')
        we_bg = self._properties.get('weekendbackground')
        we_fg = self._properties.get('weekendforeground')

        self.style.configure('main.%s.TFrame' % self._style_prefixe,
                             background=bg)
        self.style.configure('cal.%s.TFrame' % self._style_prefixe,
                             background=bc)
        self.style.configure('main.%s.TLabel' % self._style_prefixe,
                             background=bg,
                             foreground=fg)
        self.style.configure('headers.%s.TLabel' % self._style_prefixe,
                             background=hd_bg,
                             foreground=hd_fg)
        self.style.configure('normal.%s.TLabel' % self._style_prefixe,
                             background=cal_bg,
                             foreground=cal_fg)
        self.style.configure('normal_om.%s.TLabel' % self._style_prefixe,
                             background=om_bg,
                             foreground=om_fg)
        self.style.configure('we_om.%s.TLabel' % self._style_prefixe,
                             background=omwe_bg,
                             foreground=omwe_fg)
        self.style.configure('sel.%s.TLabel' % self._style_prefixe,
                             background=sel_bg,
                             foreground=sel_fg)
        self.style.configure('we.%s.TLabel' % self._style_prefixe,
                             background=we_bg,
                             foreground=we_fg)
        size = max(self._header_font.actual()["size"], 10)
        self.style.configure('R.%s.TButton' % self._style_prefixe,
                             background=bg,
                             arrowcolor=fg,
                             arrowsize=size,
                             bordercolor=bg,
                             relief="flat",
                             lightcolor=bg,
                             darkcolor=bg)
        self.style.configure('L.%s.TButton' % self._style_prefixe,
                             background=bg,
                             arrowsize=size,
                             arrowcolor=fg,
                             bordercolor=bg,
                             relief="flat",
                             lightcolor=bg,
                             darkcolor=bg)

        self.style.map('R.%s.TButton' % self._style_prefixe,
                       background=[('active', active_bg)],
                       bordercolor=[('active', active_bg)],
                       relief=[('active', 'flat')],
                       darkcolor=[('active', active_bg)],
                       lightcolor=[('active', active_bg)])
        self.style.map('L.%s.TButton' % self._style_prefixe,
                       background=[('active', active_bg)],
                       bordercolor=[('active', active_bg)],
                       relief=[('active', 'flat')],
                       darkcolor=[('active', active_bg)],
                       lightcolor=[('active', active_bg)])
        self.style.map('sel.%s.TLabel' % self._style_prefixe,
                       background=[('disabled', dis_sel_bg)],
                       foreground=[('disabled', dis_sel_fg)])
        self.style.map(self._style_prefixe + '.TLabel',
                       background=[('disabled', dis_bg)],
                       foreground=[('disabled', dis_fg)])

    def _display_calendar(self):
        """Display the days of the current month (the one in self._date)."""
        year, month = self._date.year, self._date.month

        # update header text (Month, Year)
        header = self._cal.formatmonthname(year, month, 0, False)
        self._header_month.configure(text=header.title())
        self._header_year.configure(text=str(year))

        # update calendar shown dates
        cal = self._cal.monthdatescalendar(year, month)

        next_m = month + 1
        y = year
        if next_m == 13:
            next_m = 1
            y += 1
        if len(cal) < 6:
            if cal[-1][-1].month == month:
                i = 0
            else:
                i = 1
            cal.append(self._cal.monthdatescalendar(y, next_m)[i])
            if len(cal) < 6:
                cal.append(self._cal.monthdatescalendar(y, next_m)[i + 1])

        week_days = {i: 'normal' for i in range(7)}
        week_days[5] = 'we'
        week_days[6] = 'we'
        prev_m = (month - 2) % 12 + 1
        months = {
            month: '.%s.TLabel' % self._style_prefixe,
            next_m: '_om.%s.TLabel' % self._style_prefixe,
            prev_m: '_om.%s.TLabel' % self._style_prefixe
        }

        week_nb = self._date.isocalendar()[1]
        modulo = max(week_nb, 52)
        for i_week in range(6):
            self._week_nbs[i_week].configure(
                text=str((week_nb + i_week - 1) % modulo + 1))
            for i_day in range(7):
                style = week_days[i_day] + months[cal[i_week][i_day].month]
                txt = str(cal[i_week][i_day].day)
                self._calendar[i_week][i_day].configure(text=txt, style=style)
        self._display_selection()

    def _display_selection(self):
        """Highlight selected day."""
        if self._sel_date is not None:
            year = self._sel_date.year
            if year == self._date.year:
                _, w, d = self._sel_date.isocalendar()
                wn = self._date.isocalendar()[1]
                w -= wn
                w %= max(52, wn)
                if 0 <= w and w < 6:
                    self._calendar[w][d - 1].configure(style='sel.%s.TLabel' %
                                                       self._style_prefixe)

    def _remove_selection(self):
        """Remove highlight of selected day."""
        if self._sel_date is not None:
            year, month = self._sel_date.year, self._sel_date.month
            if year == self._date.year:
                _, w, d = self._sel_date.isocalendar()
                wn = self._date.isocalendar()[1]
                w -= wn
                w %= max(52, wn)
                if w >= 0 and w < 6:
                    if month == self._date.month:
                        if d < 6:
                            self._calendar[w][d - 1].configure(
                                style='normal.%s.TLabel' % self._style_prefixe)
                        else:
                            self._calendar[w][d - 1].configure(
                                style='we.%s.TLabel' % self._style_prefixe)
                    else:
                        if d < 6:
                            self._calendar[w][d - 1].configure(
                                style='normal_om.%s.TLabel' %
                                self._style_prefixe)
                        else:
                            self._calendar[w][d - 1].configure(
                                style='we_om.%s.TLabel' % self._style_prefixe)

    # --- callbacks
    def _next_month(self):
        """Display the next month."""
        year, month = self._date.year, self._date.month
        self._date = self._date + \
            self.timedelta(days=calendar.monthrange(year, month)[1])
        #        if month == 12:
        #            # don't increment year
        #            self._date = self._date.replace(year=year)
        self._display_calendar()

    def _prev_month(self):
        """Display the previous month."""
        self._date = self._date - self.timedelta(days=1)
        self._date = self._date.replace(day=1)
        self._display_calendar()

    def _next_year(self):
        """Display the next year."""
        year = self._date.year
        self._date = self._date.replace(year=year + 1)
        self._display_calendar()

    def _prev_year(self):
        """Display the previous year."""
        year = self._date.year
        self._date = self._date.replace(year=year - 1)
        self._display_calendar()

    # --- bindings
    def _on_click(self, event):
        """Select the day on which the user clicked."""
        if self._properties['state'] is 'normal':
            label = event.widget
            day = label.cget("text")
            style = label.cget("style")
            if style in [
                    'normal_om.%s.TLabel' % self._style_prefixe,
                    'we_om.%s.TLabel' % self._style_prefixe
            ]:
                if label in self._calendar[0]:
                    self._prev_month()
                else:
                    self._next_month()
            if day:
                day = int(day)
                year, month = self._date.year, self._date.month
                self._remove_selection()
                self._sel_date = self.date(year, month, day)
                self._display_selection()
                if self._textvariable is not None:
                    self._textvariable.set(self._sel_date.strftime("%x"))
                self.event_generate("<<CalendarSelected>>")

    # --- selection handling
    def selection_get(self):
        """
        Return currently selected date (datetime.date instance).
        Always return None if selectmode is "none".
        """

        if self._properties.get("selectmode") is "day":
            return self._sel_date
        else:
            return None

    def selection_set(self, date):
        """
        Set the selection to date.

        date can be either a datetime.date
        instance or a string corresponding to the date format "%x"
        in the Calendar locale.

        Do nothing if selectmode is "none".
        """
        if self._properties.get("selectmode") is "day" and self._properties[
                'state'] is 'normal':
            if date is None:
                self._remove_selection()
                self._sel_date = None
                if self._textvariable is not None:
                    self._textvariable.set('')
            else:
                if isinstance(date, self.date):
                    self._sel_date = date
                else:
                    try:
                        self._sel_date = self.strptime(date, "%x").date()
                    except Exception as e:
                        raise type(e)("%r is not a valid date." % date)
                if self._textvariable is not None:
                    self._textvariable.set(self._sel_date.strftime("%x"))
                self._date = self._sel_date.replace(day=1)
                self._display_calendar()
                self._display_selection()

    def get_date(self):
        """Return selected date as string."""
        if self._sel_date is not None:
            return self._sel_date.strftime("%x")
        else:
            return ""

    # --- other methods
    def keys(self):
        """Return a list of all resource names of this widget."""
        return list(self._properties.keys())

    def cget(self, key):
        """Return the resource value for a KEY given as string."""
        return self[key]

    def configure(self, **kw):
        """
        Configure resources of a widget.

        The values for resources are specified as keyword
        arguments. To get an overview about
        the allowed keyword arguments call the method keys.
        """
        for item, value in kw.items():
            self[item] = value

    def config(self, **kw):
        """
        Configure resources of a widget.

        The values for resources are specified as keyword
        arguments. To get an overview about
        the allowed keyword arguments call the method keys.
        """
        for item, value in kw.items():
            self[item] = value
Exemple #46
0
    def __init__(self):
        """Initialize widgets, methods."""

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    @staticmethod
    def quit_app(event=None):
        sys.exit(0)
Exemple #48
0
    def createWidgets(self):
        self.top = self.winfo_toplevel()

        self.style = Style()

        self.style.configure('TFrame1.TLabelframe', font=('宋体', 9))
        self.style.configure('TFrame1.TLabelframe.Label', font=('宋体', 9))
        self.Frame1 = LabelFrame(self.top,
                                 text='',
                                 style='TFrame1.TLabelframe')
        self.Frame1.place(relx=0.709, rely=0., relwidth=0.289, relheight=0.985)

        self.style.configure('TFrame2.TLabelframe', font=('宋体', 9))
        self.style.configure('TFrame2.TLabelframe.Label', font=('宋体', 9))
        self.Frame2 = LabelFrame(self.top,
                                 text='',
                                 style='TFrame2.TLabelframe')
        self.Frame2.place(relx=0.011, rely=0., relwidth=0.677, relheight=0.985)

        self.List1Var = StringVar(value='')
        self.List1Font = Font(font=('宋体', 9))
        self.List1 = Listbox(self.Frame1,
                             listvariable=self.List1Var,
                             font=self.List1Font)
        self.List1.place(relx=0.038,
                         rely=0.049,
                         relwidth=0.923,
                         relheight=0.924)

        self.IDVar = StringVar(value='歌单ID:')
        self.style.configure('TID.TLabel', anchor='w', font=('宋体', 9))
        self.ID = Label(self.Frame2,
                        text='Label1',
                        textvariable=self.IDVar,
                        style='TID.TLabel')
        self.ID.setText = lambda x: self.IDVar.set(x)
        self.ID.text = lambda: self.IDVar.get()
        self.ID.place(relx=0.016, rely=0.05, relwidth=0.46, relheight=0.128)

        self.PathVar = StringVar(value='下载地址')
        self.style.configure('TPath.TLabel', anchor='w', font=('宋体', 9))
        self.Path = Label(self.Frame2,
                          text='Label2',
                          textvariable=self.PathVar,
                          style='TPath.TLabel')
        self.Path.setText = lambda x: self.PathVar.set(x)
        self.Path.text = lambda: self.PathVar.get()
        self.Path.place(relx=0.016, rely=0.399, relwidth=0.46, relheight=0.128)
        self.Path.bind('<Button-1>', self.Path_Button_1)

        self.Text1Var = StringVar(value='')
        self.Text1 = Entry(self.Frame2,
                           textvariable=self.Text1Var,
                           font=('宋体', 9))
        self.Text1.setText = lambda x: self.Text1Var.set(x)
        self.Text1.text = lambda: self.Text1Var.get()
        self.Text1.place(relx=0.507,
                         rely=0.05,
                         relwidth=0.476,
                         relheight=0.128)

        self.Text2Var = StringVar(value='')
        self.Text2 = Entry(self.Frame2,
                           textvariable=self.Text2Var,
                           font=('宋体', 9))
        self.Text2.setText = lambda x: self.Text2Var.set(x)
        self.Text2.text = lambda: self.Text2Var.get()
        self.Text2.place(relx=0.507,
                         rely=0.399,
                         relwidth=0.411,
                         relheight=0.128)

        self.Path_buttonVar = StringVar(value='...')
        self.style.configure('TPath_button.TButton', font=('宋体', 9))
        self.Path_button = Button(self.Frame2,
                                  text='Command1',
                                  textvariable=self.Path_buttonVar,
                                  command=self.Path_button_Cmd,
                                  style='TPath_button.TButton')
        self.Path_button.setText = lambda x: self.Path_buttonVar.set(x)
        self.Path_button.text = lambda: self.Path_buttonVar.get()
        self.Path_button.place(relx=0.916,
                               rely=0.399,
                               relwidth=0.067,
                               relheight=0.128)

        self.StartVar = StringVar(value='Start')
        self.style.configure('TStart.TButton', font=('宋体', 9))
        self.Start = Button(self.Frame2,
                            text='Command2',
                            textvariable=self.StartVar,
                            command=self.Start_Cmd,
                            style='TStart.TButton')
        self.Start.setText = lambda x: self.StartVar.set(x)
        self.Start.text = lambda: self.StartVar.get()
        self.Start.place(relx=0.016,
                         rely=0.798,
                         relwidth=0.46,
                         relheight=0.178)

        self.QuitVar = StringVar(value='Quit')
        self.style.configure('TQuit.TButton', font=('宋体', 9))
        self.Quit = Button(self.Frame2,
                           text='Command3',
                           textvariable=self.QuitVar,
                           command=self.Quit_Cmd,
                           style='TQuit.TButton')
        self.Quit.setText = lambda x: self.QuitVar.set(x)
        self.Quit.text = lambda: self.QuitVar.get()
        self.Quit.place(relx=0.507,
                        rely=0.798,
                        relwidth=0.476,
                        relheight=0.178)
class DrtGlueDemo(object):
    def __init__(self, examples):
        # Set up the main window.
        self._top = Tk()
        self._top.title("DRT Glue Demo")

        # Set up key bindings.
        self._init_bindings()

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

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

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

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

        self._init_glue()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        self._populate_readingListbox()

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

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

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

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

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

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

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

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

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

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

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

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

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

        parent.config(menu=menubar)

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

    def _redraw(self):
        canvas = self._canvas

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

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

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

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

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

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

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

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

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

        else:
            self._select_previous_example()

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

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

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

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

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

        else:
            self._select_next_example()

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

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

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

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

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

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

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

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

        self._drs = None
        self._redraw()

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

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

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

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

            self._populate_readingListbox()

            self._exampleList.selection_set(index)

            self._drs = None
            self._redraw()

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

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

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

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

            self._redraw()
Exemple #50
0
class FontChooser(Toplevel):
    """Font chooser dialog."""

    def __init__(self, master, font_dict={}, text="Abcd", title="Font Chooser",
                 **kwargs):
        """
        Create a new FontChooser instance.
        Arguments:
            master : Tk or Toplevel instance
                master window
            font_dict : dict
                dictionnary, like the one returned by the ``actual`` method of a ``Font`` object:
                ::
                    {'family': str,
                     'size': int,
                     'weight': 'bold'/'normal',
                     'slant': 'italic'/'roman',
                     'underline': bool,
                     'overstrike': bool}
            text : str
                text to be displayed in the preview label
            title : str
                window title
            kwargs : dict
                additional keyword arguments to be passed to ``Toplevel.__init__``
        """
        Toplevel.__init__(self, master, **kwargs)
        self.title(title)
        self.resizable(False, False)
        self.protocol("WM_DELETE_WINDOW", self.quit)
        self._validate_family = self.register(self.validate_font_family)
        self._validate_size = self.register(self.validate_font_size)

        # --- variable storing the chosen font
        self.res = ""

        style = Style(self)
        style.configure("prev.TLabel", background="white")
        bg = style.lookup("TLabel", "background")
        self.configure(bg=bg)

        # --- family list
        self.fonts = list(set(families()))
        self.fonts.append("TkDefaultFont")
        self.fonts.sort()
        for i in range(len(self.fonts)):
            self.fonts[i] = self.fonts[i].replace(" ", "\ ")
        max_length = int(2.5 * max([len(font) for font in self.fonts])) // 3
        self.sizes = ["%i" % i for i in (list(range(6, 17)) + list(range(18, 32, 2)))]
        # --- font default
        font_dict["weight"] = font_dict.get("weight", "normal")
        font_dict["slant"] = font_dict.get("slant", "roman")
        font_dict["underline"] = font_dict.get("underline", False)
        font_dict["overstrike"] = font_dict.get("overstrike", False)
        font_dict["family"] = font_dict.get("family",
                                            self.fonts[0].replace('\ ', ' '))
        font_dict["size"] = font_dict.get("size", 10)

        # --- creation of the widgets
        # ------ style parameters (bold, italic ...)
        options_frame = Frame(self, relief='groove', borderwidth=2)
        self.font_family = StringVar(self, " ".join(self.fonts))
        self.font_size = StringVar(self, " ".join(self.sizes))
        self.var_bold = BooleanVar(self, font_dict["weight"] == "bold")
        b_bold = Checkbutton(options_frame, text=TR["Bold"],
                             command=self.toggle_bold,
                             variable=self.var_bold)
        b_bold.grid(row=0, sticky="w", padx=4, pady=(4, 2))
        self.var_italic = BooleanVar(self, font_dict["slant"] == "italic")
        b_italic = Checkbutton(options_frame, text=TR["Italic"],
                               command=self.toggle_italic,
                               variable=self.var_italic)
        b_italic.grid(row=1, sticky="w", padx=4, pady=2)
        self.var_underline = BooleanVar(self, font_dict["underline"])
        b_underline = Checkbutton(options_frame, text=TR["Underline"],
                                  command=self.toggle_underline,
                                  variable=self.var_underline)
        b_underline.grid(row=2, sticky="w", padx=4, pady=2)
        self.var_overstrike = BooleanVar(self, font_dict["overstrike"])
        b_overstrike = Checkbutton(options_frame, text=TR["Overstrike"],
                                   variable=self.var_overstrike,
                                   command=self.toggle_overstrike)
        b_overstrike.grid(row=3, sticky="w", padx=4, pady=(2, 4))
        # ------ Size and family
        self.var_size = StringVar(self)
        self.entry_family = Entry(self, width=max_length, validate="key",
                                  validatecommand=(self._validate_family, "%d", "%S",
                                                   "%i", "%s", "%V"))
        self.entry_size = Entry(self, width=4, validate="key",
                                textvariable=self.var_size,
                                validatecommand=(self._validate_size, "%d", "%P", "%V"))
        self.list_family = Listbox(self, selectmode="browse",
                                   listvariable=self.font_family,
                                   highlightthickness=0,
                                   exportselection=False,
                                   width=max_length)
        self.list_size = Listbox(self, selectmode="browse",
                                 listvariable=self.font_size,
                                 highlightthickness=0,
                                 exportselection=False,
                                 width=4)
        scroll_family = Scrollbar(self, orient='vertical',
                                  command=self.list_family.yview)
        scroll_size = Scrollbar(self, orient='vertical',
                                command=self.list_size.yview)
        self.preview_font = Font(self, **font_dict)
        if len(text) > 30:
            text = text[:30]
        self.preview = Label(self, relief="groove", style="prev.TLabel",
                             text=text, font=self.preview_font,
                             anchor="center")

        # --- widget configuration
        self.list_family.configure(yscrollcommand=scroll_family.set)
        self.list_size.configure(yscrollcommand=scroll_size.set)

        self.entry_family.insert(0, font_dict["family"])
        self.entry_family.selection_clear()
        self.entry_family.icursor("end")
        self.entry_size.insert(0, font_dict["size"])

        try:
            i = self.fonts.index(self.entry_family.get().replace(" ", "\ "))
        except ValueError:
            # unknown font
            i = 0
        self.list_family.selection_clear(0, "end")
        self.list_family.selection_set(i)
        self.list_family.see(i)
        try:
            i = self.sizes.index(self.entry_size.get())
            self.list_size.selection_clear(0, "end")
            self.list_size.selection_set(i)
            self.list_size.see(i)
        except ValueError:
            # size not in list
            pass

        self.entry_family.grid(row=0, column=0, sticky="ew",
                               pady=(10, 1), padx=(10, 0))
        self.entry_size.grid(row=0, column=2, sticky="ew",
                             pady=(10, 1), padx=(10, 0))
        self.list_family.grid(row=1, column=0, sticky="nsew",
                              pady=(1, 10), padx=(10, 0))
        self.list_size.grid(row=1, column=2, sticky="nsew",
                            pady=(1, 10), padx=(10, 0))
        scroll_family.grid(row=1, column=1, sticky='ns', pady=(1, 10))
        scroll_size.grid(row=1, column=3, sticky='ns', pady=(1, 10))
        options_frame.grid(row=0, column=4, rowspan=2,
                           padx=10, pady=10, ipadx=10)

        self.preview.grid(row=2, column=0, columnspan=5, sticky="eswn",
                          padx=10, pady=(0, 10), ipadx=4, ipady=4)

        button_frame = Frame(self)
        button_frame.grid(row=3, column=0, columnspan=5, pady=(0, 10), padx=10)

        Button(button_frame, text="Ok",
               command=self.ok).grid(row=0, column=0, padx=4, sticky='ew')
        Button(button_frame, text=TR["Cancel"],
               command=self.quit).grid(row=0, column=1, padx=4, sticky='ew')
        self.list_family.bind('<<ListboxSelect>>', self.update_entry_family)
        self.list_size.bind('<<ListboxSelect>>', self.update_entry_size,
                            add=True)
        self.list_family.bind("<KeyPress>", self.keypress)
        self.entry_family.bind("<Return>", self.change_font_family)
        self.entry_family.bind("<Tab>", self.tab)
        self.entry_size.bind("<Return>", self.change_font_size)

        self.entry_family.bind("<Down>", self.down_family)
        self.entry_size.bind("<Down>", self.down_size)

        self.entry_family.bind("<Up>", self.up_family)
        self.entry_size.bind("<Up>", self.up_size)

        # bind Ctrl+A to select all instead of go to beginning
        self.bind_class("TEntry", "<Control-a>", self.select_all)

        self.wait_visibility(self)
        self.grab_set()
        self.entry_family.focus_set()
        self.lift()

    def select_all(self, event):
        """Select all entry content."""
        event.widget.selection_range(0, "end")

    def keypress(self, event):
        """Select the first font whose name begin by the key pressed."""
        key = event.char.lower()
        l = [i for i in self.fonts if i[0].lower() == key]
        if l:
            i = self.fonts.index(l[0])
            self.list_family.selection_clear(0, "end")
            self.list_family.selection_set(i)
            self.list_family.see(i)
            self.update_entry_family()

    def up_family(self, event):
        """Navigate in the family listbox with up key."""
        try:
            i = self.list_family.curselection()[0]
            self.list_family.selection_clear(0, "end")
            if i <= 0:
                i = len(self.fonts)
            self.list_family.see(i - 1)
            self.list_family.select_set(i - 1)
        except TclError:
            self.list_family.selection_clear(0, "end")
            i = len(self.fonts)
            self.list_family.see(i - 1)
            self.list_family.select_set(i - 1)
        self.list_family.event_generate('<<ListboxSelect>>')

    def up_size(self, event):
        """Navigate in the size listbox with up key."""
        try:
            s = self.var_size.get()
            if s in self.sizes:
                i = self.sizes.index(s)
            elif s:
                sizes = list(self.sizes)
                sizes.append(s)
                sizes.sort(key=lambda x: int(x))
                i = sizes.index(s)
            else:
                i = 0
            self.list_size.selection_clear(0, "end")
            if i <= 0:
                i = len(self.sizes)
            self.list_size.see(i - 1)
            self.list_size.select_set(i - 1)
        except TclError:
            i = len(self.sizes)
            self.list_size.see(i - 1)
            self.list_size.select_set(i - 1)
        self.list_size.event_generate('<<ListboxSelect>>')

    def down_family(self, event):
        """Navigate in the family listbox with down key."""
        try:
            i = self.list_family.curselection()[0]
            self.list_family.selection_clear(0, "end")
            if i >= len(self.fonts):
                i = -1
            self.list_family.see(i + 1)
            self.list_family.select_set(i + 1)
        except TclError:
            self.list_family.selection_clear(0, "end")
            self.list_family.see(0)
            self.list_family.select_set(0)
        self.list_family.event_generate('<<ListboxSelect>>')

    def down_size(self, event):
        """Navigate in the size listbox with down key."""
        try:
            s = self.var_size.get()
            if s in self.sizes:
                i = self.sizes.index(s)
            elif s:
                sizes = list(self.sizes)
                sizes.append(s)
                sizes.sort(key=lambda x: int(x))
                i = sizes.index(s) - 1
            else:
                s = len(self.sizes) - 1
            self.list_size.selection_clear(0, "end")
            if i < len(self.sizes) - 1:
                self.list_size.selection_set(i + 1)
                self.list_size.see(i + 1)
            else:
                self.list_size.see(0)
                self.list_size.select_set(0)
        except TclError:
            self.list_size.selection_set(0)
        self.list_size.event_generate('<<ListboxSelect>>')

    def toggle_bold(self):
        """Update font preview weight."""
        b = self.var_bold.get()
        self.preview_font.configure(weight=["normal", "bold"][b])

    def toggle_italic(self):
        """Update font preview slant."""
        b = self.var_italic.get()
        self.preview_font.configure(slant=["roman", "italic"][b])

    def toggle_underline(self):
        """Update font preview underline."""
        b = self.var_underline.get()
        self.preview_font.configure(underline=b)

    def toggle_overstrike(self):
        """Update font preview overstrike."""
        b = self.var_overstrike.get()
        self.preview_font.configure(overstrike=b)

    def change_font_family(self, event=None):
        """Update font preview family."""
        family = self.entry_family.get()
        if family.replace(" ", "\ ") in self.fonts:
            self.preview_font.configure(family=family)

    def change_font_size(self, event=None):
        """Update font preview size."""
        size = int(self.var_size.get())
        self.preview_font.configure(size=size)

    def validate_font_size(self, d, ch, V):
        """Validation of the size entry content."""
        l = [i for i in self.sizes if i[:len(ch)] == ch]
        i = None
        if l:
            i = self.sizes.index(l[0])
        elif ch.isdigit():
            sizes = list(self.sizes)
            sizes.append(ch)
            sizes.sort(key=lambda x: int(x))
            i = min(sizes.index(ch), len(self.sizes))
        if i is not None:
            self.list_size.selection_clear(0, "end")
            self.list_size.selection_set(i)
            deb = self.list_size.nearest(0)
            fin = self.list_size.nearest(self.list_size.winfo_height())
            if V != "forced":
                if i < deb or i > fin:
                    self.list_size.see(i)
                return True
        if d == '1':
            return ch.isdigit()
        else:
            return True

    def tab(self, event):
        """Move at the end of selected text on tab press."""
        self.entry_family = event.widget
        self.entry_family.selection_clear()
        self.entry_family.icursor("end")
        return "break"

    def validate_font_family(self, action, modif, pos, prev_txt, V):
        """Completion of the text in the entry with existing font names."""
        if self.entry_family.selection_present():
            sel = self.entry_family.selection_get()
            txt = prev_txt.replace(sel, '')
        else:
            txt = prev_txt
        if action == "0":
            txt = txt[:int(pos)] + txt[int(pos) + 1:]
            return True
        else:
            txt = txt[:int(pos)] + modif + txt[int(pos):]
            ch = txt.replace(" ", "\ ")
            l = [i for i in self.fonts if i[:len(ch)] == ch]
            if l:
                i = self.fonts.index(l[0])
                self.list_family.selection_clear(0, "end")
                self.list_family.selection_set(i)
                deb = self.list_family.nearest(0)
                fin = self.list_family.nearest(self.list_family.winfo_height())
                index = self.entry_family.index("insert")
                self.entry_family.delete(0, "end")
                self.entry_family.insert(0, l[0].replace("\ ", " "))
                self.entry_family.selection_range(index + 1, "end")
                self.entry_family.icursor(index + 1)
                if V != "forced":
                    if i < deb or i > fin:
                        self.list_family.see(i)
                return True
            else:
                return False

    def update_entry_family(self, event=None):
        """Update family entry when an item is selected in the family listbox."""
        #  family = self.list_family.get("@%i,%i" % (event.x , event.y))
        family = self.list_family.get(self.list_family.curselection()[0])
        self.entry_family.delete(0, "end")
        self.entry_family.insert(0, family)
        self.entry_family.selection_clear()
        self.entry_family.icursor("end")
        self.change_font_family()

    def update_entry_size(self, event):
        """Update size entry when an item is selected in the size listbox."""
        #  size = self.list_size.get("@%i,%i" % (event.x , event.y))
        size = self.list_size.get(self.list_size.curselection()[0])
        self.var_size.set(size)
        self.change_font_size()

    def ok(self):
        """Validate choice."""
        self.res = self.preview_font.actual()
        self.quit()

    def get_res(self):
        """Return chosen font."""
        return self.res

    def quit(self):
        self.destroy()

def grap():
    top = Toplevel()
    Button(top, text='Slope Formula', command=Slope, height=0).pack()
    Button(top, text='Midpoint Formula', command=Midpoint, height=0).pack()
    Button(top, text='Coordinate Distance Formula', command=disf, height=0).pack()


# Main Page
root = Tk()
# root.geometry('400x500')


root.configure(bg='black')
title = Font(family='Times', size=20, weight='bold', slant='italic')
root.title('Math Formulas and Methods Cheat Sheet')

Label(root,
      text='MATH FORMULAS AND METHODS CHEAT SHEET',
      bg='black',
      fg='cyan',
      font=title).pack()

main_frame = Frame(root)
main_frame.pack(fill=BOTH, expand=1)

my_canvas = Canvas(main_frame)
my_canvas.pack(side=LEFT, fill=BOTH, expand=1)

my_scrollbar = ttk.Scrollbar(main_frame, orient=VERTICAL, command=my_canvas.yview)
btn_reset_set = Button(window,
                       text="Сбросить сеты",
                       bg="white",
                       fg="blue",
                       command=ResetSet)
btn_reset_set.place(x=450, y=300, relwidth=0.2, relheight=0.1)

# Спины БОЛЬШИЕ боковые

spin_big_left = Spinbox(window,
                        from_=0,
                        to=100,
                        textvariable=myvar_score_left,
                        width=3,
                        font=Font(family='Helvetica', size=36, weight='bold'),
                        command=UpdateSpin)
spin_big_left.place(x=50, y=100)
#spin.pack()
spin_big_right = Spinbox(window,
                         from_=0,
                         to=100,
                         textvariable=myvar_score_right,
                         width=3,
                         font=Font(family='Helvetica', size=36, weight='bold'),
                         command=UpdateSpin)
spin_big_right.place(x=520, y=100)

#Спины МАЛЕНЬКИЕ посередине
#Левый
spin_left = Spinbox(window,
def openFile(root, text, dirToOpen=None):
    if dirToOpen == None:
        dirToOpen = askopenfilename(parent=root,
                                    title='Choose file to open',
                                    filetypes=(("Notecalc documents (*.nxc)",
                                                "*.nxc"),
                                               ("Text documents (*.txt)",
                                                "*.txt"), ("All files",
                                                           "*.*")))
    dirToOpen = toPath(dirToOpen)

    with open(dirToOpen, 'r', encoding='utf-8') as file:
        text.delete('1.0', 'end')
        fileText = file.read()
        if str(dirToOpen).endswith(".nxc") == True:
            fileText = literal_eval(fileText)
            final = ""
            for (key, value, index) in fileText:
                if key == "text":
                    final += value
            text.insert('1.0', final)
            tagsInitIndexes = list()
            for (key, value, index) in fileText:
                if key == "tagon":
                    tagsInitIndexes.append(index)
                elif key == "tagoff":
                    tagInitIndex = tagsInitIndexes.pop(0)
                    if len(value) < 14:
                        size = globals.font.cget("size")
                        size = str(size)
                        if len(size) < 2:
                            size = "0" + size
                        sampleTag = "......." + size[0] + size[
                            1] + globals.colorConfig["def"]
                        size = int(size)
                        if "bt" in value:
                            sampleTag = replaceSubstring(
                                sampleTag, ".", "n", globals.formsIndex["n"])
                        elif "stit" in value:
                            sampleTag = replaceSubstring(
                                sampleTag, ".", "i", globals.formsIndex["i"])
                            sizeSubTitulo = size + 2
                            sizeSubTitulo = str(sizeSubTitulo)
                            if len(sizeSubTitulo) < 2:
                                sizeSubTitulo = "0" + sizeSubTitulo
                            sampleTag = replaceSubstring(
                                sampleTag,
                                sampleTag[globals.formsIndex["size"]],
                                sizeSubTitulo[0], globals.formsIndex["size"])
                            sampleTag = replaceSubstring(
                                sampleTag,
                                sampleTag[globals.formsIndex["size"] + 1],
                                sizeSubTitulo[1],
                                globals.formsIndex["size"] + 1)
                        elif "tit" in value:
                            if (sampleTag[globals.formsIndex["n"]] != "n"):
                                sampleTag = replaceSubstring(
                                    sampleTag, ".", "n",
                                    globals.formsIndex["n"])
                            sizeTitulo = size + 4
                            sizeTitulo = str(sizeTitulo)
                            if len(sizeTitulo) < 2:
                                sizeTitulo = "0" + sizeTitulo
                            sampleTag = replaceSubstring(
                                sampleTag,
                                sampleTag[globals.formsIndex["size"]],
                                sizeTitulo[0], globals.formsIndex["size"])
                            sampleTag = replaceSubstring(
                                sampleTag,
                                sampleTag[globals.formsIndex["size"] + 1],
                                sizeTitulo[1], globals.formsIndex["size"] + 1)
                        elif "it" in value:
                            if (sampleTag[globals.formsIndex["i"]] != "i"):
                                sampleTag = replaceSubstring(
                                    sampleTag, ".", "i",
                                    globals.formsIndex["i"])
                        elif "un" in value:
                            sampleTag = replaceSubstring(
                                sampleTag, ".", "s", globals.formsIndex["s"])
                        elif "tc" in value:
                            sampleTag = replaceSubstring(
                                sampleTag, ".", "t", globals.formsIndex["t"])
                        elif "cor" in value:
                            cor = value[3::]
                            sampleTag = "cor" + sampleTag[
                                globals.formsIndex["n"]:globals.
                                formsIndex["hex"]] + cor
                        # Pra manter a compatibilidade com os arquivos da antiga formatação
                        elif value.startswith("#"):
                            cor = value
                            sampleTag = "cor" + sampleTag[
                                globals.formsIndex["n"]:globals.
                                formsIndex["hex"]] + cor

                        fontDaFormatacao = Font(text, text.cget("font"))
                        fontSize = fontDaFormatacao.cget("size")

                        if "n" in sampleTag[globals.formsIndex["n"]:]:
                            fontDaFormatacao.config(weight="bold")
                        if "i" in sampleTag[globals.formsIndex["n"]:]:
                            fontDaFormatacao.config(slant="italic")
                        if "t" in sampleTag[globals.formsIndex["n"]:]:
                            fontDaFormatacao.config(overstrike=1)
                        if "s" in sampleTag[globals.formsIndex["n"]:]:
                            fontDaFormatacao.config(underline=1)

                        if (len(sampleTag) == 14):
                            size = sampleTag[5:7]
                        elif (len(sampleTag) == 16):
                            size = sampleTag[globals.formsIndex["size"]:globals
                                             .formsIndex["size"] + 2]

                        fontDaFormatacao.config(size=int(size))

                        cor = globals.configCores["padrao"]
                        prefixo = "..."
                        if sampleTag[0] == "c":
                            cor = sampleTag[globals.formsIndex["hex"]::]
                            prefixo = "cor"
                        elif globals.vsc == True:
                            if "n" in sampleTag[globals.
                                                formsIndex["n"]:] and int(
                                                    size) != fontSize + 4:
                                cor = globals.configCores["negrito"]
                                prefixo = "vbt"
                            if "n" in sampleTag[globals.
                                                formsIndex["n"]:] and int(
                                                    size) == fontSize + 4:
                                cor = globals.configCores["titulo"]
                                prefixo = "vtt"
                            if "i" in sampleTag[globals.
                                                formsIndex["n"]:] and int(
                                                    size) != fontSize + 2:
                                cor = globals.configCores["italico"]
                                prefixo = "vit"
                            if "i" in sampleTag[globals.
                                                formsIndex["n"]:] and int(
                                                    size) == fontSize + 2:
                                cor = globals.configCores["subtitulo"]
                                prefixo = "vst"
                            if "s" in sampleTag[globals.formsIndex["n"]:]:
                                cor = globals.configCores["sublinhado"]
                                prefixo = "vtc"
                            if "t" in sampleTag[globals.formsIndex["n"]:]:
                                cor = globals.configCores["tachado"]
                                prefixo = "vun"

                        sampleTag = prefixo + sampleTag[
                            globals.formsIndex["n"]:globals.
                            formsIndex["hex"]] + cor
                        text.tag_config(sampleTag,
                                        font=fontDaFormatacao,
                                        foreground=cor)

                        text.tag_add(sampleTag, f"{tagInitIndex}", f"{index}")

                    elif len(value) >= 14:
                        fontDaFormatacao = Font(text, text.cget("font"))
                        fontSize = fontDaFormatacao.cget("size")

                        if "n" in value[globals.formsIndex["n"]:]:
                            fontDaFormatacao.config(weight="bold")
                        if "i" in value[globals.formsIndex["n"]:]:
                            fontDaFormatacao.config(slant="italic")
                        if "t" in value[globals.formsIndex["n"]:]:
                            fontDaFormatacao.config(overstrike=1)
                        if "s" in value[globals.formsIndex["n"]:]:
                            fontDaFormatacao.config(underline=1)

                        if (len(value) == 14):
                            size = value[5:7]
                        elif (len(value) == 16):
                            size = value[globals.formsIndex["size"]:globals.
                                         formsIndex["size"] + 2]

                        fontDaFormatacao.config(size=int(size))

                        cor = globals.configCores["padrao"]
                        if value[0] == "v" and globals.vsc == True:
                            if value[:globals.formsIndex["n"]] == "vbt":
                                cor = globals.configCores["negrito"]
                            if value[:globals.formsIndex["n"]] == "vtt":
                                cor = globals.configCores["titulo"]
                            if value[:globals.formsIndex["n"]] == "vit":
                                cor = globals.configCores["italico"]
                            if value[:globals.formsIndex["n"]] == "vst":
                                cor = globals.configCores["subtitulo"]
                            if value[:globals.formsIndex["n"]] == "vun":
                                cor = globals.configCores["sublinhado"]
                            if value[:globals.formsIndex["n"]] == "vtc":
                                cor = globals.configCores["tachado"]
                        elif value[0] == "c":
                            cor = value[globals.formsIndex["hex"]::]

                        value = value[:globals.formsIndex["hex"]] + cor

                        text.tag_config(value,
                                        font=fontDaFormatacao,
                                        foreground=cor)

                        text.tag_add(value, f"{tagInitIndex}", f"{index}")

            text.edit_modified(False)
            globals.dirDeTrabalhoAtual = dirToOpen
            chdir(dirname(dirToOpen))
            root.title("Lolicalc " + str(globals.dirDeTrabalhoAtual))
            return True
        else:
            text.edit_modified(False)
            globals.dirDeTrabalhoAtual = dirToOpen
            chdir(dirname(dirToOpen))
            root.title("Lolicalc " + str(globals.dirDeTrabalhoAtual))
            text.insert('1.0', fileText)
            return True
Exemple #54
0
def start_up():
    root = Tk()
    root.title("Yahtzee Deluxe")
    list_of_names = []

    # music plays when the screen opens, do this until all of the players have been selected
    def initialize_music():
        pygame.mixer.init()
        pygame.mixer.music.load('yahtzee_music.mp3')
        pygame.mixer.music.play(999)

    # can enter up to four players
    def give_names():
        # function within a function so that the necessary variables are still in scope
        def submit_names():
            name_1 = first_entry.get()
            if name_1 and not name_1.isspace():
                list_of_names.append(name_1)
            name_2 = second_entry.get()
            if name_2 and not name_2.isspace():
                list_of_names.append(name_2)
            name_3 = third_entry.get()
            if name_3 and not name_3.isspace():
                list_of_names.append(name_3)
            name_4 = fourth_entry.get()
            if name_4 and not name_4.isspace():
                list_of_names.append(name_4)
            root.quit()

        # setup
        new_window = Toplevel(root)
        new_window.title("Enter player names")
        new_window.geometry("300x150")
        universal_font = Font(family="Times New Roman", size=12)

        # first player
        first_label = Label(new_window, text="Player #1", font=universal_font)
        first_label.grid(row=0)
        first_name = StringVar()
        first_entry = ttk.Entry(new_window, textvariable=first_name)
        first_entry.grid(row=0, column=1)

        # second player
        second_label = Label(new_window, text="Player #2", font=universal_font)
        second_label.grid(row=1)
        second_name = StringVar()
        second_entry = ttk.Entry(new_window, textvariable=second_name)
        second_entry.grid(row=1, column=1)

        # third player
        third_label = Label(new_window, text="Player #3", font=universal_font)
        third_label.grid(row=2)
        third_name = StringVar()
        third_entry = ttk.Entry(new_window, textvariable=third_name)
        third_entry.grid(row=2, column=1)

        # fourth player
        fourth_label = Label(new_window, text="Player #4", font=universal_font)
        fourth_label.grid(row=3)
        fourth_name = StringVar()
        fourth_entry = ttk.Entry(new_window, textvariable=fourth_name)
        fourth_entry.grid(row=3, column=1)

        # submit button
        submit_button = Button(new_window,
                               text="Submit",
                               command=submit_names,
                               font=universal_font)
        submit_button.grid(row=4, column=1)

    image = Image.open('yahtzee_pic.png')
    image = image.resize((1200, 800))
    image = ImageTk.PhotoImage(image)
    canvas = Canvas(width=1200, height=800)
    canvas.create_image(600, 400, image=image)
    canvas.pack()
    font = Font(family="Times New Roman", size=50, weight="bold")
    open_game_button = Button(root,
                              text="PLAY",
                              bg="red",
                              fg="orange",
                              font=font,
                              command=give_names,
                              anchor="center",
                              relief=GROOVE,
                              activeforeground="orange")
    open_game_button_window = canvas.create_window(50,
                                                   620,
                                                   anchor='nw',
                                                   window=open_game_button)
    initialize_music()

    root.mainloop()
    return list_of_names
Exemple #55
0
    def show(self):

        # Only allow one options view at a time # TODO Can be done with a global var, then a global instance of OptionsView is not needed
        if not self._showing:

            self._showing = True

            self._lineColorMap = self._textFrame.getLineColorMap()

            self._view = tk.Toplevel(self._root)
            self._view.title("Options")
            self._view.protocol("WM_DELETE_WINDOW", self._onClosing)

            self._view.iconbitmap(self._settings.get(Sets.ICON_PATH_FULL))

            self._setsDict = dict()

            ##############################
            # TAB CONTROL

            self._tabsFrame = tk.Frame(self._view)
            self._tabsFrame.grid(row=0, column=0, sticky="nsew")
            self._view.columnconfigure(0, weight=1)
            self._view.rowconfigure(0, weight=1)

            self._tabControl = Notebook(self._tabsFrame, padding=10)

            self._tabControl.grid(row=0, column=0, sticky=tk.N)
            self._tabList = list()

            ##############################
            # TEXT EXAMPLE

            logExample = self._loadLogExample()
            exampleTextFrameHeightMin = 400
            exampleTextFrameWidth = 650

            self._exampleTextFrame = tk.Frame(self._tabsFrame,
                                              height=exampleTextFrameHeightMin,
                                              width=exampleTextFrameWidth)
            self._exampleTextFrame.grid(row=0,
                                        column=1,
                                        padx=(0, 10),
                                        pady=(10, 10),
                                        sticky="nsew")
            self._exampleTextFrame.grid_propagate(False)
            self._tabsFrame.columnconfigure(1, weight=1)
            self._tabsFrame.rowconfigure(0, weight=1)

            tFont = Font(family=self._settings.get(Sets.TEXTAREA_FONT_FAMILY),
                         size=self._settings.get(Sets.TEXTAREA_FONT_SIZE))
            self._exampleText = tk.Text(self._exampleTextFrame,height=1, width=2,\
                                            background=self._settings.get(Sets.TEXTAREA_BACKGROUND_COLOR),\
                                            selectbackground=self._settings.get(Sets.TEXTAREA_SELECT_BACKGROUND_COLOR),\
                                            foreground=self._settings.get(Sets.TEXTAREA_COLOR),\
                                            font=tFont)
            self._exampleText.grid(row=0,
                                   column=0,
                                   padx=(0, 0),
                                   pady=(10, 0),
                                   sticky="nsew")
            self._exampleTextFrame.columnconfigure(0, weight=1)
            self._exampleTextFrame.rowconfigure(0, weight=1)

            self._updateExampleTextLineWrap(
                self._settings.get(Sets.TEXTAREA_LINE_WRAP))

            self._exampleText.insert(1.0, logExample)

            xscrollbar = tk.Scrollbar(self._exampleTextFrame,
                                      orient=tk.HORIZONTAL,
                                      command=self._exampleText.xview)
            xscrollbar.grid(row=1, column=0, sticky=tk.W + tk.E)
            self._exampleText["xscrollcommand"] = xscrollbar.set

            yscrollbar = tk.Scrollbar(self._exampleTextFrame,
                                      orient=tk.VERTICAL,
                                      command=self._exampleText.yview)
            yscrollbar.grid(row=0, column=1, sticky=tk.N + tk.S)
            self._exampleText["yscrollcommand"] = yscrollbar.set

            ###############
            # Tab: Line Coloring

            self._lineColoringFrame = tk.Frame(self._tabControl,
                                               padx=5,
                                               pady=5)
            self._lineColoringFrame.grid(row=0, column=0, sticky=tk.N)
            self._tabControl.add(self._lineColoringFrame, text="Line Coloring")
            self._tabList.append(self.GROUP_LINE_COLORING)

            self._setsDict.update(
                self._createLineColorRows(self._lineColoringFrame,
                                          self._lineColorMap))

            upButton = tk.Button(self._lineColoringFrame,
                                 text="UP",
                                 command=partial(self._editLineColorRow,
                                                 self.EDIT_UP))
            upButton.grid(row=0, column=2, padx=2)

            downButton = tk.Button(self._lineColoringFrame,
                                   text="DOWN",
                                   command=partial(self._editLineColorRow,
                                                   self.EDIT_DOWN))
            downButton.grid(row=1, column=2, padx=2)

            deleteButton = tk.Button(self._lineColoringFrame,
                                     text="Delete",
                                     command=partial(self._editLineColorRow,
                                                     self.EDIT_DELETE))
            deleteButton.grid(row=2, column=2, padx=2)
            self._lastFocusInRowId = ""
            self._lastFocusOutRowId = ""

            self._newButtonRow = len(self._lineColorMap)
            self._newButton = tk.Button(self._lineColoringFrame,
                                        text="New Line",
                                        command=partial(
                                            self._addNewEmptyLineColor))
            self._newButton.grid(row=self._newButtonRow,
                                 column=0,
                                 sticky=tk.W,
                                 padx=(2, 100),
                                 pady=2)

            self._deletedLineColorRows = list()

            ###############
            # Tab: Text Area

            self._textAreaFrame = tk.Frame(self._tabControl, padx=5, pady=5)
            self._textAreaFrame.grid(row=0, column=0, sticky=tk.N)
            self._tabControl.add(self._textAreaFrame, text="Text Area")
            self._tabList.append(self.GROUP_TEXT_AREA)

            setLines = list()
            setLines.append(
                self.SettingsLineTemplate(self.GROUP_TEXT_AREA,
                                          Sets.TEXTAREA_BACKGROUND_COLOR,
                                          "Background Color",
                                          self.ENTRY_TYPE_COLOR))
            setLines.append(
                self.SettingsLineTemplate(
                    self.GROUP_TEXT_AREA,
                    Sets.TEXTAREA_SELECT_BACKGROUND_COLOR,
                    "Background Color Select", self.ENTRY_TYPE_COLOR))
            setLines.append(
                self.SettingsLineTemplate(self.GROUP_TEXT_AREA,
                                          Sets.TEXTAREA_COLOR, "Text Color",
                                          self.ENTRY_TYPE_COLOR))
            setLines.append(
                self.SettingsLineTemplate(self.GROUP_TEXT_AREA,
                                          Sets.TEXTAREA_FONT_FAMILY,
                                          "Font Family",
                                          self.ENTRY_TYPE_STRING))
            setLines.append(
                self.SettingsLineTemplate(self.GROUP_TEXT_AREA,
                                          Sets.TEXTAREA_FONT_SIZE, "Font Size",
                                          self.ENTRY_TYPE_INT))
            setLines.append(
                self.SettingsLineTemplate(self.GROUP_TEXT_AREA,
                                          Sets.TEXTAREA_LINE_WRAP, "Line Wrap",
                                          self.ENTRY_TYPE_TOGGLE))

            self._setsDict.update(
                self._createStandardRows(self._textAreaFrame, setLines, 0))

            ###############
            # Tab: Search

            self._searchFrame = tk.Frame(self._tabControl, padx=5, pady=5)
            self._searchFrame.grid(row=0, column=0, sticky=tk.N)
            self._tabControl.add(self._searchFrame, text="Search")
            self._tabList.append(self.GROUP_SEARCH)

            setLines = list()
            setLines.append(
                self.SettingsLineTemplate(self.GROUP_SEARCH,
                                          Sets.SEARCH_MATCH_COLOR,
                                          "Search match background color",
                                          self.ENTRY_TYPE_COLOR))
            setLines.append(
                self.SettingsLineTemplate(self.GROUP_SEARCH,
                                          Sets.SEARCH_SELECTED_COLOR,
                                          "Search selected background color",
                                          self.ENTRY_TYPE_COLOR))
            setLines.append(
                self.SettingsLineTemplate(
                    self.GROUP_SEARCH, Sets.SEARCH_SELECTED_LINE_COLOR,
                    "Search selected line background color",
                    self.ENTRY_TYPE_COLOR))

            self._setsDict.update(
                self._createStandardRows(self._searchFrame, setLines, 0))

            ###############
            # Tab: Logging

            self._loggingFrame = tk.Frame(self._tabControl, padx=5, pady=5)
            self._loggingFrame.grid(row=0, column=0, sticky=tk.N)
            self._tabControl.add(self._loggingFrame, text="Logging")
            self._tabList.append(self.GROUP_LOGGING)

            setLines = list()
            setLines.append(
                self.SettingsLineTemplate(self.GROUP_LOGGING,
                                          Sets.LOG_FILE_PATH, "Log file path",
                                          self.ENTRY_TYPE_OTHER))
            setLines.append(
                self.SettingsLineTemplate(self.GROUP_LOGGING,
                                          Sets.LOG_FILE_BASE_NAME,
                                          "Log file base name",
                                          self.ENTRY_TYPE_OTHER))
            setLines.append(
                self.SettingsLineTemplate(self.GROUP_LOGGING,
                                          Sets.LOG_FILE_TIMESTAMP,
                                          "Time stamp", self.ENTRY_TYPE_OTHER))

            self._setsDict.update(
                self._createStandardRows(self._loggingFrame, setLines, 0))

            ##############################
            # CONTROL ROW

            self._optionsControlFrame = tk.Frame(self._view)
            self._optionsControlFrame.grid(row=1,
                                           column=0,
                                           padx=(10, 10),
                                           pady=(0, 10),
                                           sticky=tk.W + tk.E)

            self._optionsInfoLabel = tk.Label(self._optionsControlFrame,
                                              text="",
                                              justify=tk.LEFT)
            self._optionsInfoLabel.grid(row=0, column=0, sticky=tk.W)
            self._optionsControlFrame.columnconfigure(0, weight=1)

            self._optionsCancelButton = tk.Button(self._optionsControlFrame,
                                                  text="Cancel",
                                                  command=self._onClosing)
            self._optionsCancelButton.grid(row=0,
                                           column=1,
                                           padx=5,
                                           sticky=tk.E)

            self._optionsSaveButton = tk.Button(self._optionsControlFrame,
                                                text="Save",
                                                command=self._saveSettings)
            self._optionsSaveButton.grid(row=0, column=2, sticky=tk.E)
            if self._saving:
                self._optionsSaveButton.config(state=tk.DISABLED)
            else:
                self._optionsSaveButton.config(state=tk.NORMAL)

            self._tabControl.bind("<<NotebookTabChanged>>", self._tabChanged)
Exemple #56
0
    def _updateExampleText(self, group):

        #####################
        # Setup

        # Delete all search tags
        self._exampleText.tag_delete(Sets.SEARCH_SELECTED_LINE_COLOR)
        self._exampleText.tag_delete(Sets.SEARCH_MATCH_COLOR)
        self._exampleText.tag_delete(Sets.SEARCH_SELECTED_COLOR)

        # Delete all current line color tags
        tagNames = self._exampleText.tag_names()
        for tagName in tagNames:
            if Sets.LINE_COLOR_MAP in tagName:
                self._exampleText.tag_delete(tagName)

        entryName = "entry"
        if group == self.GROUP_TEXT_AREA:
            # General text area
            try:
                tFont = Font(family=self._setsDict[Sets.TEXTAREA_FONT_FAMILY].entries[entryName].var.get(),\
                            size=self._setsDict[Sets.TEXTAREA_FONT_SIZE].entries[entryName].var.get())
                self._exampleText.config(background=self._setsDict[Sets.TEXTAREA_BACKGROUND_COLOR].entries[entryName].var.get(),\
                                                selectbackground=self._setsDict[Sets.TEXTAREA_SELECT_BACKGROUND_COLOR].entries[entryName].var.get(),\
                                                foreground=self._setsDict[Sets.TEXTAREA_COLOR].entries[entryName].var.get(),\
                                                font=tFont)

                lineWrapString = self._setsDict[
                    Sets.TEXTAREA_LINE_WRAP].entries[entryName].var.get()
                if lineWrapString == "on":
                    self._updateExampleTextLineWrap(Sets.LINE_WRAP_ON)
                elif lineWrapString == "off":
                    self._updateExampleTextLineWrap(Sets.LINE_WRAP_OFF)

            except tk.TclError:
                pass

        elif group == self.GROUP_SEARCH:

            searchString = "Main"

            # Create search tags
            self._exampleText.tag_configure(Sets.SEARCH_SELECTED_LINE_COLOR, \
                                            background=self._setsDict[Sets.SEARCH_SELECTED_LINE_COLOR].entries[entryName].var.get(),\
                                            selectbackground=util.lightOrDarkenColor(self._setsDict[Sets.SEARCH_SELECTED_LINE_COLOR].entries[entryName].var.get(),Sets.SELECTED_LINE_DARKEN_COLOR))
            self._exampleText.tag_configure(Sets.SEARCH_MATCH_COLOR, \
                                            background=self._setsDict[Sets.SEARCH_MATCH_COLOR].entries[entryName].var.get(),\
                                            selectbackground=util.lightOrDarkenColor(self._setsDict[Sets.SEARCH_MATCH_COLOR].entries[entryName].var.get(),Sets.SELECTED_LINE_DARKEN_COLOR))
            self._exampleText.tag_configure(Sets.SEARCH_SELECTED_COLOR, \
                                            background=self._setsDict[Sets.SEARCH_SELECTED_COLOR].entries[entryName].var.get(), \
                                            selectbackground=util.lightOrDarkenColor(self._setsDict[Sets.SEARCH_SELECTED_COLOR].entries[entryName].var.get(),Sets.SELECTED_LINE_DARKEN_COLOR))

            # Do search
            countVar = tk.StringVar()
            results = list()
            start = 1.0
            while True:
                pos = self._exampleText.search(searchString,
                                               start,
                                               stopindex=tk.END,
                                               count=countVar,
                                               nocase=False,
                                               regexp=False)
                if not pos:
                    break
                else:
                    results.append((pos, pos + "+" + countVar.get() + "c"))
                    start = pos + "+1c"

            # Add search tags
            first = True
            for result in results:
                self._exampleText.tag_add(Sets.SEARCH_MATCH_COLOR, result[0],
                                          result[1])
                if first:
                    first = False
                    self._exampleText.tag_add(Sets.SEARCH_SELECTED_COLOR,
                                              result[0], result[1])
                    selectLine = result[0].split(".")[0]
                    self._exampleText.tag_add(Sets.SEARCH_SELECTED_LINE_COLOR,
                                              selectLine + ".0",
                                              selectLine + ".0+1l")

        if group == self.GROUP_LINE_COLORING or group == self.GROUP_SEARCH:

            # Get line color map from view
            tempLineColorMap = list()
            for rowId in sorted(self._setsDict.keys()):
                if Sets.LINE_COLOR_MAP in rowId:
                    lineInfo = dict()
                    lineInfo["regex"] = self._setsDict[rowId].entries[
                        "regex"].var.get()
                    lineInfo["color"] = self._setsDict[rowId].entries[
                        "color"].var.get()
                    lineInfo["tagName"] = TF.createLineColorTagName(
                        lineInfo["regex"])
                    tempLineColorMap.append(lineInfo)

            # Apply new line colors
            for lineInfo in tempLineColorMap:
                self._exampleText.tag_configure(lineInfo["tagName"],
                                                foreground=lineInfo["color"])

                countVar = tk.StringVar()
                start = 1.0
                while True:
                    pos = self._exampleText.search(lineInfo["regex"],
                                                   start,
                                                   stopindex=tk.END,
                                                   count=countVar,
                                                   nocase=False,
                                                   regexp=True)
                    if not pos:
                        break
                    else:
                        self._exampleText.tag_add(
                            lineInfo["tagName"], pos,
                            pos + "+" + countVar.get() + "c")
                        start = pos + "+1c"
    def __init__(self):
        """Initialize widgets, methods."""

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

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

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

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

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


        self.bind_all("<Control-n>", self.new)
        self.bind_all("<Control-o>", self.open)
        self.bind_all("<Control-s>", self.save)
        self.bind_all("<Control-q>", self.exit)
        self.bind_all("<Control-b>", self.bold)
        self.bind_all("<Control-i>", self.italic)
        self.bind_all("<Control-u>", self.underline)
        self.bind_all("<Control-T>", self.overstrike)
        self.bind_all("<Control-z>", self.undo)
        self.bind_all("<Control-y>", self.redo)

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

        # Frame configuration
        self.grid_columnconfigure(0, weight=1)
        self.resizable(True, True)
Exemple #58
0
        data.append((tree.set(row, col), row))
    for i,info in enumerate(sorted(data, key=lambda data: data[0], reverse=direction)):
        tree.move(info[1], '', i)
##    tree.heading(col, command=lambda vars_=vars_: vars_['SortBy'](tree, col, not direction),
##                 state='!selected alternate' if direction else 'selected !alternate')
    tree.heading(col, command=lambda: SortBy(tree, col, not direction))
    treeState[col]['selected'] = False if direction else True
    treeState[col]['alternate'] = True if direction else False
    if ttk.Style().theme_use() == 'aque':
        tree.heading(col, state='user1')
        treeState[col]['user1'] = True
    else:
        tree.heading(col, image=upArrow if direction else downArrow)
style = ttk.Style()
from tkinter.font import Font
font_ = Font(name=style.lookup('Heading', 'font'), exists=True)
globals().update(locals())
for col in title:
    name = col
    tree.heading(col, text=name, image=noArrow, anchor='w',
        command=lambda col=col: SortBy(tree, col, False))
    tree.column(col, width=font_.measure(name)+noArrow.width()+5)
font_ = Font(name=style.lookup('Treeview', 'font'), exists=True)
for i in data:
    tree.insert('', 'end', values=' '.join(i))
    for n in i:
        len_ = font_.measure(col+'  ')
        if tree.column(col, 'width') < len_:
            tree.column(col, width=len_)

## Code to do the sorting of the tree contents when clicked on