示例#1
0
文件: GUI.py 项目: CapnOdin/PySong
	def initVars(self):
		
		self.vcmdIsNum = GuiUtil.create_vcmd(self.master, {})
		self.vcmdTNI_10 = GuiUtil.create_vcmd(self.master, {"maxval" : 10})
		self.invcmd_10 = GuiUtil.create_invcmd(self.master, {"maxval" : 10})
		
		self.customFont = font.nametofont("TkTextFont").copy()
		self.customFontMedium = font.nametofont("TkTextFont").copy()
		self.customFontMedium["size"] = 12
		self.customFontLarge = font.nametofont("TkTextFont").copy()
		self.customFontLarge["size"] = 15
		
		self.EntryOptions    = {"font": self.customFontLarge}#, "validate": "key", "validatecommand": self.vcmdTNI_44, "invalidcommand": self.invcmd_44}
		self.EntryOptionsNum = {"font": self.customFontLarge, "justify": tk.RIGHT, "validate": "key", "validatecommand": self.vcmdIsNum}
		self.EntryOptions210 = {"font": self.customFontLarge, "justify": tk.RIGHT, "width": 2, "validate": "key", "validatecommand": self.vcmdTNI_10, "invalidcommand": self.invcmd_10}
		
		self.PathSaves = Util.getScriptPath() + "/Configs"
		
		self.FileOptionsJSON = {"initialdir": self.PathSaves, "filetypes": [("json", ".json"), ("all", "*")], "defaultextension": ".json"}
		
		self.BoolOptions = {"offvalue": "False", "onvalue": "True", "takefocus": False}
		
		self.widgetVars = {"name" : tk.StringVar(), "logo" : tk.StringVar(value = "Resources/UNF_Logo.svg"), "style" : tk.StringVar(value = "arabic"), "indexing" : tk.IntVar(value = 0), "booklet" : tk.BooleanVar(value = True)}
		
		self.LOADED = False
		self.TreeReady = True
		self.filename = ""
		self.tooltip = None
示例#2
0
    def fixfonts(self):
        #screen_width = self.winfo_screenwidth()
        #screen_height = self.winfo_screenheight()
        self.default_font = nametofont('TkDefaultFont')
        self.default_font.configure(size=10)

        self.menu_font = nametofont('TkMenuFont')
        self.menu_font.configure(size=10)
示例#3
0
 def test_font_eq(self):
     fontname = "TkDefaultFont"
     try:
         f = font.Font(name=fontname, exists=True)
     except tkinter._tkinter.TclError:
         f = font.Font(name=fontname, exists=False)
     font1 = font.nametofont(fontname)
     font2 = font.nametofont(fontname)
     self.assertIsNot(font1, font2)
     self.assertEqual(font1, font2)
     self.assertNotEqual(font1, font1.copy())
     self.assertNotEqual(font1, 0)
示例#4
0
    def __init__(self, msg, title, text, codebox, callback):
        """ Create ui object

        Parameters
        ----------
        msg : string
            text displayed in the message area (instructions...)
        title : str
            the window title
        text: str, list or tuple
            text displayed in textAres (editable)
        codebox: bool
            if True, dont wrap and width is set to 80 chars
        callback: function
            if set, this function will be called when OK is pressed

        Returns
        -------
        object
            The ui object
        """

        self.callback = callback

        self.boxRoot = tk.Tk()
        # self.boxFont = tk_Font.Font(
        #     family=global_state.PROPORTIONAL_FONT_FAMILY,
        #     size=global_state.PROPORTIONAL_FONT_SIZE)

        wrap_text = not codebox
        if wrap_text:
            self.boxFont = tk_Font.nametofont("TkTextFont")
            self.width_in_chars = global_state.prop_font_line_length
        else:
            self.boxFont = tk_Font.nametofont("TkFixedFont")
            self.width_in_chars = global_state.fixw_font_line_length

        # default_font.configure(size=global_state.PROPORTIONAL_FONT_SIZE)

        self.configure_root(title)

        self.create_msg_widget(msg)

        self.create_text_area(wrap_text)

        self.create_buttons_frame()

        self.create_cancel_button()

        self.create_ok_button()
示例#5
0
    def fixFonts(self):
        screen_width = self.winfo_screenwidth()
        screen_height = self.winfo_screenheight()
    #    print(screen_height)
#        print(screen_width)
        self.default_font = nametofont('TkDefaultFont')
#        print(self.default_font.actual())
        self.default_font.configure(size=16)
#        print(self.default_font.actual())

        self.menu_font = nametofont('TkMenuFont')
#        print(self.menu_font.actual())

        self.menu_font.configure(size=36)
示例#6
0
    def CreateWidgets(self):
        frameText = Frame(self, relief=SUNKEN, height=700)
        frameCommands = Frame(self, relief=SUNKEN)
        frameButtons = Frame(self)
        self.buttonOk = Button(frameButtons, text='Close', command=lambda b=1: self.Ok(b), takefocus=FALSE)
        self.buttonTwo = Button(frameButtons, text='Close2', command=lambda b=2: self.Ok(b), takefocus=FALSE)
        self.scrollbarView = Scrollbar(frameText, orient=VERTICAL, takefocus=FALSE, highlightthickness=0)
        self.textView = Text(frameText, wrap=WORD, highlightthickness=0, fg=self.fg, bg=self.bg, font=self.font, padx=8, pady=8)
        self.scrollbarView.config(command=self.textView.yview)
        self.textView.config(yscrollcommand=self.scrollbarView.set)

        self.commandPrompt = Label(frameCommands, text="> ")
        fixedFont = self.FindFont(["Consolas", "Lucida Console", "DejaVu Sans Mono"], self.fontsize_monospace)
        if not fixedFont:
            fixedFont = tkfont.nametofont('TkFixedFont').copy()
            fixedFont["size"]=self.fontsize_monospace
        self.commandEntry = Entry(frameCommands, takefocus=TRUE, font=fixedFont)
        self.commandEntry.bind('<Return>',self.user_cmd) 
        self.commandEntry.bind('<Extended-Return>',self.user_cmd) 
        self.commandEntry.bind('<KP_Enter>',self.user_cmd)
        self.commandEntry.bind('<F1>', self.f1_pressed)
        self.buttonOk.pack()
        self.buttonTwo.pack()
        self.scrollbarView.pack(side=RIGHT,fill=Y)
        self.textView.pack(side=LEFT,expand=TRUE,fill=BOTH)
        self.commandPrompt.pack(side=LEFT)
        self.commandEntry.pack(side=LEFT, expand=TRUE, fill=X, ipady=1)

        frameButtons.pack(side=BOTTOM,fill=X)
        frameText.pack(side=TOP,expand=TRUE,fill=BOTH)
        frameCommands.pack(side=BOTTOM, fill=X)
        self.commandEntry.focus_set()
示例#7
0
    def __init__(self, msg, title, choices, preselect, multiple_select, callback):

        self.callback = callback

        self.choices = choices

        self.width_in_chars = global_state.prop_font_line_length
        # Initialize self.selected_choices
        # This is the value that will be returned if the user clicks the close
        # icon
        # self.selected_choices = None

        self.multiple_select = multiple_select

        self.boxRoot = tk.Tk()

        self.boxFont = tk_Font.nametofont("TkTextFont")

        self.config_root(title)

        self.set_pos(global_state.window_position)  # GLOBAL POSITION

        self.create_msg_widget(msg)

        self.create_choicearea()

        self.create_ok_button()

        self.create_cancel_button()

        self. create_special_buttons()
        
        self.preselect_choice(preselect)

        self.choiceboxWidget.focus_force()
示例#8
0
文件: psfm.py 项目: grahamgower/psfm
    def fontsize(self, sz_diff):
        """
        Change font sizes by sz_diff.
        """

        for fname in font.names():
            f = font.nametofont(fname)
            sz = f.configure()["size"]

            if sz < 0:
                # use negative numbers if tk does. 
                sz -= sz_diff
            else:
                sz += sz_diff

            if abs(sz) <= 4 or abs(sz) >= 64:
                # don't be stupid
                continue

            f.configure(size=sz)

        # The treeview does not change row height automatically.
        style = ttk.Style()
        rowheight = style.configure("Treeview").get("rowheight")
        if rowheight is None:
            # The style doesn't have this set to start with.
            # Shit like this makes ttk styling useless for portability.
            rowheight = 20
        rowheight += sz_diff

        if rowheight <= 10 or rowheight >= 140:
            # getting ridiculous
            return

        style.configure("Treeview", rowheight=rowheight+sz_diff)
示例#9
0
    def __init__(self, msg, title, choices, images, default_choice, cancel_choice, callback):
        """ Create ui object

        Parameters
        ----------
        msg : string
            text displayed in the message area (instructions...)
        title : str
            the window title
        choices : iterable of strings
            build a button for each string in choices
        images : iterable of filenames, or an iterable of iterables of filenames
            displays each image
        default_choice : string
            one of the strings in choices to be the default selection
        cancel_choice : string
            if X or <esc> is pressed, it appears as if this button was pressed.
        callback: function
            if set, this function will be called when any button is pressed.


        Returns
        -------
        object
            The ui object
        """
        self._title = title
        self._msg = msg
        self._choices = choices
        self._default_choice = default_choice
        self._cancel_choice = cancel_choice
        self.callback = callback
        self._choice_text = None
        self._choice_rc = None
        self._images = list()

        self.boxRoot = tk.Tk()
        # self.boxFont = tk_Font.Font(
        #     family=global_state.PROPORTIONAL_FONT_FAMILY,
        #     size=global_state.PROPORTIONAL_FONT_SIZE)

        self.boxFont = tk_Font.nametofont("TkFixedFont")
        self.width_in_chars = global_state.fixw_font_line_length

        # default_font.configure(size=global_state.PROPORTIONAL_FONT_SIZE)

        self.configure_root(title)

        self.create_msg_widget(msg)

        self.create_images_frame()

        self.create_images(images)

        self.create_buttons_frame()

        self.create_buttons(choices, default_choice)
示例#10
0
文件: gui.py 项目: pkesist/buildpal
 def __init__(self, parent, columns, **kwargs):
     Treeview.__init__(self, parent,
         columns=tuple(c['cid'] for c in columns[1:]), **kwargs)
     heading_font = font.nametofont('TkHeadingFont')
     for c in columns:
         width = max(heading_font.measure(c['text']) + 15, c['minwidth'])
         self.column(c['cid'], width=width, minwidth=c['minwidth'],
             anchor=c['anchor'])
         self.heading(c['cid'], text=c['text'])
示例#11
0
文件: main.py 项目: bekar/tk_xmlview
    def loadTags(self, txtwig):
        self.txtwig = txtwig
        font_name = txtwig['font']
        b = tkFont.nametofont(font_name).copy()
        b.config(weight="bold")

        txtwig.tag_config("tags", foreground="purple", font=b)
        txtwig.tag_config("attribs", font=b)
        txtwig.tag_config("values", foreground="blue")
示例#12
0
    def CreateWidgets(self):
        frameText = Frame(self, relief=SUNKEN, height=700)
        frameCommands = Frame(self, relief=SUNKEN)
        self.scrollbarView = Scrollbar(frameText, orient=VERTICAL, takefocus=FALSE, highlightthickness=0)
        self.textView = Text(frameText, wrap=WORD, highlightthickness=0, fg=self.fg, bg=self.bg, font=self.font, padx=8, pady=8)
        self.scrollbarView.config(command=self.textView.yview)
        self.textView.config(yscrollcommand=self.scrollbarView.set)

        self.commandPrompt = Label(frameCommands, text="> ")
        fixedFont = self.FindFont(["Consolas", "Lucida Console", "DejaVu Sans Mono"], self.fontsize_monospace)
        if not fixedFont:
            fixedFont = tkfont.nametofont('TkFixedFont').copy()
            fixedFont["size"] = self.fontsize_monospace
        self.commandEntry = Entry(frameCommands, takefocus=TRUE, font=fixedFont)
        self.commandEntry.bind('<Return>', self.user_cmd)
        self.commandEntry.bind('<Extended-Return>', self.user_cmd)
        self.commandEntry.bind('<KP_Enter>', self.user_cmd)
        self.commandEntry.bind('<F1>', self.f1_pressed)
        self.commandEntry.bind('<Up>', self.up_pressed)
        self.commandEntry.bind('<Down>', self.down_pressed)
        self.scrollbarView.pack(side=RIGHT, fill=Y)
        self.textView.pack(side=LEFT, expand=TRUE, fill=BOTH)
        # configure the text tags
        self.textView.tag_configure('userinput', font=fixedFont, foreground='maroon', spacing1=10, spacing3=4, lmargin1=20, lmargin2=20, rmargin=20)
        self.textView.tag_configure('dim', foreground='brown')
        self.textView.tag_configure('bright', foreground='black', font=self.boldFond)
        self.textView.tag_configure('ul', foreground='black', font=self.underlinedFond)
        self.textView.tag_configure('rev', foreground=self.bg, background=self.fg)
        self.textView.tag_configure('living', foreground='black', font=self.boldFond)
        self.textView.tag_configure('player', foreground='black', font=self.boldFond)
        self.textView.tag_configure('item', foreground='black', font=self.boldFond)
        self.textView.tag_configure('exit', foreground='black', font=self.boldFond)
        self.textView.tag_configure('location', foreground='navy', font=self.boldFond)
        self.textView.tag_configure('monospaced', font=fixedFont)
        self.textView.tag_configure('black', foreground='black')
        self.textView.tag_configure('red', foreground='red')
        self.textView.tag_configure('green', foreground='green')
        self.textView.tag_configure('yellow', foreground='yellow')
        self.textView.tag_configure('blue', foreground='blue')
        self.textView.tag_configure('magenta', foreground='magenta')
        self.textView.tag_configure('cyan', foreground='cyan')
        self.textView.tag_configure('white', foreground='white')
        self.textView.tag_configure('bg:black', background='black')
        self.textView.tag_configure('bg:red', background='red')
        self.textView.tag_configure('bg:green', background='green')
        self.textView.tag_configure('bg:yellow', background='yellow')
        self.textView.tag_configure('bg:blue', background='blue')
        self.textView.tag_configure('bg:magenta', background='magenta')
        self.textView.tag_configure('bg:cyan', background='cyan')
        self.textView.tag_configure('bg:white', background='white')

        # pack
        self.commandPrompt.pack(side=LEFT)
        self.commandEntry.pack(side=LEFT, expand=TRUE, fill=X, ipady=1)
        frameText.pack(side=TOP, expand=TRUE, fill=BOTH)
        frameCommands.pack(side=BOTTOM, fill=X)
        self.commandEntry.focus_set()
示例#13
0
 def __init__(self, master=None):
     root = Tk()
     root.tk.call('tk', 'scaling', 20.0)
     Frame.__init__(self, master)
     self.pack
     self.grid()
     myfont = nametofont('TkDefaultFont')
     myfont.configure(size=36)
     print(dir(myfont))
     self.create_board()
示例#14
0
文件: main.py 项目: bekar/tk_zoomText
 def resize(self, d=1):
     self.container.grid_propagate(False)
     font_names = [ self.tag_cget(t, "font") for t in self.tag_names() ]
     font_names.append(self['font'])
     for name in set(font_names):
         try:
             font = tkFont.nametofont(name)
             s = abs(font["size"]); #print(s)
             font.config(size=max(s+2*d, 8))
         except:
             continue
示例#15
0
文件: gui.py 项目: rsmith-nl/lamprop
 def initialize(self):
     """Create the GUI."""
     # Set the font
     default_font = nametofont("TkDefaultFont")
     default_font['size'] = 12
     self.option_add("*Font", default_font)
     # General commands and bindings
     self.bind_all('q', self.do_exit)
     # Create widgets.
     # First row
     prbut = ttk.Button(self, text="File:", command=self.do_fileopen)
     prbut.grid(row=0, column=0, sticky='w')
     fnlabel = ttk.Label(self, anchor='w', textvariable=self.lamfile)
     fnlabel.grid(row=0, column=1, columnspan=4, sticky='ew')
     # Second row
     rldbut = ttk.Button(self, text="Reload", command=self.do_reload)
     rldbut.grid(row=1, column=0, sticky='w')
     # Third row
     cb = partial(self.on_laminate, event=0)
     chkengprop = ttk.Checkbutton(
         self, text='Engineering properties', variable=self.engprop,
         command=cb
     )
     chkengprop.grid(row=2, column=0, columnspan=3, sticky='w')
     # Fourth row
     chkmat = ttk.Checkbutton(
         self, text='ABD & abd matrices', variable=self.matrices,
         command=cb
     )
     chkmat.grid(row=3, column=0, columnspan=3, sticky='w')
     # Fifth row
     cxlam = ttk.Combobox(self, state='readonly', justify='left')
     cxlam.grid(row=4, column=0, columnspan=5, sticky='we')
     cxlam.bind("<<ComboboxSelected>>", self.on_laminate)
     self.cxlam = cxlam
     # Sixth row
     fixed = nametofont('TkFixedFont')
     fixed['size'] = 12
     res = ScrolledText(self, state='disabled', font=fixed)
     res.grid(row=5, column=0, columnspan=5, sticky='ew')
     self.result = res
示例#16
0
 def alter_fonts(self, normal=None, bold=None, initial=False):
   label_w = next(self.iter_all_label_widgets())
   if normal is None:
     first_font = nametofont(label_w.cget('font'))
     cnormal = dict(first_font.configure())
     cnormal['weight'] = 'normal'
   else:
     cnormal = dict(normal.configure())
   if bold is None:
     first_font = nametofont(label_w.cget('font'))
     cbold = dict(first_font.configure())
     cbold['weight'] = 'bold'
   else:
     cbold = dict(bold.configure())
   if initial:
     self.fonts['normal'] = Font(**cnormal)
     self.fonts['bold'] = Font(**cbold)
     [w.configure(font=self.fonts['normal'])
      for w in self.iter_all_label_widgets()]
   else:
     self.fonts['normal'].configure(**cnormal)
     self.fonts['bold'].configure(**cbold)
示例#17
0
 def draw(self, scale):
     height = scale*self.bar.get_height()
     width = scale*self.bar.get_width()
     xpos = scale*self.bar.get_xpos()
     ypos = scale*self.bar.get_ypos()
     canvas_height = scale*CANVAS_HEIGHT
     self.main_rect = self.canvas.create_rectangle(xpos - width/2, ypos - height/2, xpos + width/2, ypos + height/2, fill=self.bar.color)
     if self.bar.get_id() != None and self.bar.get_id() != -1:
         self.id_text = self.canvas.create_text(xpos, ypos)
         idfont = font.nametofont("TkDefaultFont")
         idfont.configure(size=int(20*scale))
         self.canvas.itemconfig(self.id_text, text=self.bar.get_id(), font=idfont, fill="white")
     self.drawn = True
示例#18
0
    def create_tags(self):
        super().create_tags() # for url tag
        # Don't modify predefined fonts!
        baseFont = tkfont.nametofont("TkDefaultFont")
        size = baseFont.cget("size") # -ve is pixels +ve is points
        bodyFont = tkfont.Font(family=baseFont.cget("family"), size=size)
        titleFont = tkfont.Font(family=baseFont.cget("family"),
                size=((size - 8) if size < 0 else (size + 3)),
                weight=tkfont.BOLD)

        self.text.config(font=bodyFont)
        self.text.tag_config("title", font=titleFont,
                foreground="navyblue", spacing1=3, spacing3=5)
        self.text.tag_config("versions", foreground="darkgreen")
        self.text.tag_config("above5", spacing1=5)
        self.text.tag_config("above3", spacing1=3)
示例#19
0
 def init(gui, ctrl, window, master, focus, resize=False):
     ctrl.widget = ttk.Frame(master)
     form = tkwrap.Form(ctrl.widget, column=ctrl.depth)
     
     if ctrl.depth:
         font = nametofont("TkDefaultFont")
         ctrl.top = font.metrics("linespace")
         ctrl.side = font_size(font["size"])
         ctrl.padding = font_size(font["size"] / 2)
         for level in range(ctrl.depth):
             form.master.columnconfigure(level, minsize=ctrl.side)
             col = ctrl.depth * 2 + 2 - level - 1
             form.master.columnconfigure(col, minsize=ctrl.side)
     
     place = gui.controls[Form].place_fields
     return place(gui, ctrl, ctrl.fields, window, form, 0, focus)
示例#20
0
    def __init__(self, parent, width=10, height=4, font="TkDefaultFont"):
        self.font = nametofont(font)
        self.bold_font = self.font.copy()
        self.italic_font = self.font.copy()

        self.bold_font['weight'] = 'bold'
        self.italic_font['slant'] = 'italic'

        super().__init__(
            parent,
            width=width,
            height=height,
            wrap="word",
            font=self.font,
        )
        self.tag_config(
            "underline",
            underline=1,
        )
        self.tag_config(
            "bold",
            font=self.bold_font,
        )
        self.tag_config(
            "italic",
            font=self.italic_font,
        )
        self.tag_config(
            "invert",
            background='black',
            foreground='white',
        )
        self.tag_config(
            "indent",
            # Indent the first line slightly, but indent the following
            # lines more to line up with the text.
            lmargin1="10",
            lmargin2="25",
        )
        self.tag_config(
            "hrule",
            relief="sunken",
            borderwidth=1,
            # This makes the line-height very short.
            font=tkFont(size=1),
        )
        self['state'] = "disabled"
示例#21
0
文件: main.py 项目: bekar/tk_lineno
    def resize(self, d=1):
        '''Text() font resize for key binding Ctrl + {Scroll,+,-,0}'''

        self.config(state="normal")
        self.container.grid_propagate(False)

        font_names = [ self.tag_cget(t, "font") for t in self.tag_names() ]
        font_names.append(self['font'])

        for name in set(font_names):
            try:
                font = tkFont.nametofont(name)
                s = abs(font["size"]); #print(s)
                font.config(size=max(s+2*d, 8))
            except:
                continue

        self.config(state="disable")
示例#22
0
 def show(self):
     self.leave()
     self.tip = tk.Toplevel(self.master)
     self.tip.withdraw()  # Don't show until we have the geometry
     self.tip.wm_overrideredirect(True)  # No window decorations etc.
     if TkUtil.mac():
         self.tip.tk.call("::tk::unsupported::MacWindowStyle",
                          "style", self.tip._w, "help", "none")
     label = ttk.Label(self.tip, text=self.text, padding=1,
                       background=self.background, wraplength=480,
                       relief=None if TkUtil.mac() else tk.GROOVE,
                       font=tkfont.nametofont("TkTooltipFont"))
     label.pack()
     x, y = self.position()
     self.tip.wm_geometry("+{}+{}".format(x, y))
     self.tip.deiconify()
     if self.master.winfo_viewable():
         self.tip.transient(self.master)
     self.tip.update_idletasks()
     self.timerId = self.master.after(self.showTime, self.hide)
示例#23
0
#!/usr/bin/python3

from tkinter import *
import tkinter.font as font

root = Tk()

font.nametofont('TkDefaultFont').configure(size=48)

root.title("tkinterEntry04.py")
root.geometry('400x300')
#root.geometry('600x400')
#root.geometry('1200x1000')

def evaluate(event):
    print(str(entry.get()))
    ID = (str(entry.get()))
#    print(str(eval(entry.get())))
#    ID = (str(eval(entry.get())))
    entry.delete(0,END)
    print ("ID: ",ID)

Label(root, text="Your SAIT ID").pack()
entry = Entry(root)
entry.focus_set()
entry.bind("<Return>", evaluate)
entry.pack(pady=10, padx=10)

root.mainloop()

示例#24
0
 def __init__(self, master, column=0):
     self.master = master
     self.column = column
     self.master.columnconfigure(column + 1, weight=1)
     en = font_size(nametofont("TkDefaultFont")["size"] / 2)
     self.master.columnconfigure(column + 0, pad=en)
示例#25
0
 def init_fonts(self):
     self.bigfont = font.nametofont("TkDefaultFont")
     self.bigfont.configure(size=48)
     self.scorefont = font.nametofont("TkDefaultFont")
     self.scorefont.configure(size=20)
示例#26
0
文件: piiio.py 项目: kensuke/CrowPi2
def create_frame(parent, pin):
    upper = True if pin[0] % 2 == 1 else False
    disabled = True if pin[4] == -2 else False

    frame = tk.Frame(parent, bd=1, relief=tk.SUNKEN)
    #       col= 0  1 ... 18 19
    # row=0     39 37 ...  3  1 # upper
    # row=1     40 38 ...  4  2
    frame.grid(row=0 if upper else 1,
               column=int((40 - (pin[0] + (1 if upper else 0))) / 2))

    # top-frame-row=0 # upper
    #   inner-row=0 Description       label
    #             1 BCM No.           label
    #             2 UP    HIGH   inframe  outframe
    #               DOWN  LOW
    #             3 IN    OUT         ioframe
    #             4 Mode Str          label
    #             5 Button            butframe
    #             6 PYH No.           label
    # - - - - - - -  - - - - mirror
    # top-frame-row=1
    #   inner-row=0 PYH No.
    #             1 Button
    #             2 Mode Str
    #             3 IN    OUT
    #             4 UP    HIGH
    #               DOWN  LOW
    #             5 BCM No.
    #             6 Description

    label_desc = tk.Label(frame, text=pin[3])
    label_desc.grid(row=0 if upper else 6, column=0,
                    columnspan=2)  #*** inner-row
    label_bcm = tk.Label(frame, text=pin[2])
    label_bcm.grid(row=1 if upper else 5, column=0,
                   columnspan=2)  #*** inner-row

    label_mode = tk.Label(frame, text=mode_table[pin[4]])
    label_mode.grid(row=4 if upper else 2, column=0,
                    columnspan=2)  #*** inner-row

    label_phy = tk.Label(frame, text=str(pin[0]))
    label_phy.grid(row=6 if upper else 0, column=0,
                   columnspan=2)  #*** inner-row

    # input PULL_UP or DOWN # TODO: NONE?
    inframe = tk.Frame(frame, bd=1, relief=tk.SUNKEN)
    inframe.grid(row=2 if upper else 4, column=0, sticky=tk.E)  #*** inner-row

    in_pud = tk.StringVar(value='NONE')
    in_pud_up = tk.Radiobutton(inframe, text='', variable=in_pud, value='UP')
    in_pud_none = tk.Radiobutton(inframe,
                                 text='',
                                 variable=in_pud,
                                 value='NONE')
    in_pud_down = tk.Radiobutton(inframe,
                                 text='',
                                 variable=in_pud,
                                 value='DOWN')
    in_pud_up.grid(row=0, column=0)
    in_pud_none.grid(row=1, column=0)
    in_pud_down.grid(row=2, column=0)

    # output HIGH or LOW
    out_hl = tk.StringVar(value='LOW')

    def high_low_selected(event):
        print('GPIO.output(' + str(pin[2]) + ', ' + out_hl.get() + ') # ' +
              pin[3])
        GPIO.output(pin[2], GPIO.LOW if out_hl.get() == 'LOW' else GPIO.HIGH)

    outframe = tk.Frame(frame, bd=1, relief=tk.SUNKEN)
    outframe.grid(row=2 if upper else 4, column=1, sticky=tk.W)  #*** inner-row

    out_high = tk.Radiobutton(outframe, text='', variable=out_hl, value='HIGH')
    out_low = tk.Radiobutton(outframe, text='', variable=out_hl, value='LOW')
    out_high.bind("<ButtonPress-1>", high_low_selected)
    out_low.bind("<ButtonPress-1>", high_low_selected)
    out_high.grid(row=0, column=0)
    out_low.grid(row=1, column=0)

    # input or output
    ioframe = tk.Frame(frame, bd=1, relief=tk.SUNKEN)
    ioframe.grid(row=3 if upper else 3, column=0, columnspan=2)  #*** inner-row

    #GPIO.IN, GPIO.OUT, GPIO.SPI, GPIO.I2C, GPIO.HARD_PWM, GPIO.SERIAL, GPIO.UNKNOWN
    inout = tk.StringVar(value='IN' if pin[4] == GPIO.IN else 'OUT')
    inout_in = tk.Radiobutton(ioframe, text='', variable=inout, value='IN')
    inout_out = tk.Radiobutton(ioframe, text='', variable=inout, value='OUT')
    inout_in.grid(row=0, column=0)
    inout_out.grid(row=0, column=1)

    # vertical button: https://stackoverflow.com/questions/38008389/is-it-possible-to-have-a-vertical-oriented-button-in-tkinter
    def button_pressed(event):
        #print('button['+str(pin[0])+'] inout['+inout.get()+'] in['+in_pud.get()+'] out['+out_hl.get()+']')
        #print(pin)

        # open or close
        GPIO.setmode(GPIO.BCM)
        if inout.get() == 'IN':
            GPIO.setup(pin[2],
                       GPIO.IN,
                       pull_up_down=GPIO.PUD_UP
                       if in_pud.get() == 'UP' else GPIO.PUD_DOWN)
            val = GPIO.input(pin[2])
            print(val)
        else:
            GPIO.setup(pin[2], GPIO.OUT)

    butframe = tk.Frame(frame, bd=0, relief=tk.SUNKEN)
    butframe.grid(row=5 if upper else 1, column=0,
                  columnspan=2)  #*** inner-row

    but_label = pin[3] if pin[1] == -1 else 'IO' + str(pin[1])
    font = tkfont.nametofont("TkDefaultFont")
    height = 35  #font.measure(but_label) + 4 # set static size
    width = font.metrics()['linespace'] + 4

    # raised, sunken, flat, ridge, solid, and groove
    canvas = tk.Canvas(butframe,
                       height=height,
                       width=width,
                       borderwidth=2,
                       relief='ridge' if disabled else 'raised')
    canvas.create_text((4, 4),
                       angle="270",
                       anchor="sw",
                       text=but_label,
                       font=font)
    canvas.state = tk.NORMAL if pin[4] != -1 else tk.DISABLED
    #    if not disabled:
    canvas.bind(
        "<ButtonPress-1>",
        button_pressed)  #lambda ev: ev.widget.configure(relief="sunken"))
    canvas.grid()

    # tooltip: https://stackoverflow.com/questions/3221956/how-do-i-display-tooltips-in-tkinter/61879204#61879204
    #balloon = tix.Balloon(parent, bg="white", title="Help")
    #balloon.bind_widget(frame, balloonmsg=pin[3] + '\ninout['+inout.get()+']\nin['+in_pud.get()+']\nout['+out_hl.get()+']')

    return frame
示例#27
0
def get_text_font(text):
    font = text["font"]
    if isinstance(font, str):
        return tkfont.nametofont(font)
    else:
        return font
import srctools
import tk_tools
import utils
from BEE2_config import ConfigFile
from srctools import Property
from tk_tools import TK_ROOT

LOGGER = utils.getLogger(__name__)

voice_item = None

UI = {}

TABS = {}

QUOTE_FONT = font.nametofont('TkHeadingFont').copy()
QUOTE_FONT['weight'] = 'bold'

SP_IMG = img.png('icons/quote_sp')
COOP_IMG = img.png('icons/quote_coop')

# Friendly names given to certain response channels.
RESPONSE_NAMES = {
    'death_goo': _('Death - Toxic Goo'),
    'death_turret': _('Death - Turrets'),
    'death_crush': _('Death - Crusher'),
    'death_laserfield': _('Death - LaserField'),
}

config = config_mid = config_resp = None  # type: ConfigFile
示例#29
0
    def __init__(self, parent, linewidget, open=False, filename=None):

        HighlightingText.__init__(self, parent)

        self.list = parent.get_notebook()

        self.linewidget = linewidget

        self.recent_files_path = os.path.join(MrPythonConf.GetUserCfgDir(),
                                              'recent-files.lst')

        self.apply_bindings()

        try:
            sys.ps1
        except AttributeError:
            sys.ps1 = ''

        # usetabs true  -> literal tab characters are used by indent and
        #                  dedent cmds, possibly mixed with spaces if
        #                  indentwidth is not a multiple of tabwidth,
        #                  which will cause Tabnanny to nag!
        #         false -> tab characters are converted to spaces by indent
        #                  and dedent cmds, and ditto TAB keystrokes
        # Although use-spaces=0 can be configured manually in config-main.def,
        # configuration of tabs v. spaces is not supported in the configuration
        # dialog.  MRPYTHON promotes the preferred Python indentation: use spaces!
        usespaces = MrPythonConf.GetOption('main',
                                           'Indent',
                                           'use-spaces',
                                           type='bool')
        self.usetabs = not usespaces

        # tabwidth is the display width of a literal tab character.
        # CAUTION:  telling Tk to use anything other than its default
        # tab setting causes it to use an entirely different tabbing algorithm,
        # treating tab stops as fixed distances from the left margin.
        # Nobody expects this, so for now tabwidth should never be changed.
        self.tabwidth = 8  # must remain 8 until Tk is fixed.

        # indentwidth is the number of screen characters per indent level.
        # The recommended Python indentation is four spaces.
        self.indentwidth = self.tabwidth
        self.set_notabs_indentwidth()

        # If context_use_ps1 is true, parsing searches back for a ps1 line;
        # else searches for a popular (if, def, ...) Python stmt.
        self.context_use_ps1 = False

        # When searching backwards for a reliable place to begin parsing,
        # first start num_context_lines[0] lines back, then
        # num_context_lines[1] lines back if that didn't work, and so on.
        # The last value should be huge (larger than the # of lines in a
        # conceivable file).
        # Making the initial values larger slows things down more often.
        self.num_context_lines = 50, 500, 5000000
        self.per = per = self.Percolator(self)
        self.undo = undo = self.UndoDelegator()
        per.insertfilter(undo)

        self.undo_block_start = undo.undo_block_start
        self.undo_block_stop = undo.undo_block_stop
        undo.set_saved_change_hook(self.saved_change_hook)

        self.io = io = self.IOBinding(self)
        io.set_filename_change_hook(self.filename_change_hook)

        self.color = None  # initialized below in self.ResetColorizer

        self.good_load = False
        if open:
            if filename:
                if os.path.exists(filename) and not os.path.isdir(filename):
                    if io.loadfile(filename):
                        self.good_load = True
                        is_py_src = self.ispythonsource(filename)
                else:
                    io.set_filename(filename)
            else:
                self.good_load = self.io.open(editFile=filename)
        else:
            self.good_load = True

        self.ResetColorizer()
        self.saved_change_hook()
        self.askyesno = tkMessageBox.askyesno
        self.askinteger = tkSimpleDialog.askinteger

        # specific font
        self.font = nametofont(self.cget('font')).copy()
        self.configure(font=self.font)
示例#30
0
catcher_start_x = canvas_width / 2 - catcher_width / 2
catcher_start_y = canvas_height - catcher_height - 20
catcher_start_x2 = catcher_start_x + catcher_width
catcher_start_y2 = catcher_start_y + catcher_height

catcher = c.create_arc(catcher_start_x,
                       catcher_start_y,
                       catcher_start_x2,
                       catcher_start_y2,
                       start=200,
                       extent=140,
                       style='arc',
                       outline=catcher_color,
                       width=3)

game_font = font.nametofont('TkFixedFont')
game_font.config(size=18)

score = 0
score_text = c.create_text(10,
                           10,
                           anchor='nw',
                           font=game_font,
                           fill='darkblue',
                           text='Score: ' + str(score))

lives_remaining = 3
lives_text = c.create_text(canvas_width - 10,
                           10,
                           anchor='ne',
                           font=game_font,
	def __init__(self, master):
		tk.Frame.__init__(self, master)
		
		###############################################
		# first, set up non-ui class members
		# this variable is used in this new print function, very important
		self.last_print_was_progress = False
		# payload is pointer to currently selected main() func, helptext is the currently selected help string
		self.payload = None
		self.helptext = ""
		# list of all possible displayed names in the OptionMenu, with assoc helptext and mainfunc
		self.all_script_list = all_script_list
		
		###############################################
		# second, build the dropdown menu
		# frame that holds the dropdown + the label
		self.which_script_frame = tk.Frame(master)
		self.which_script_frame.pack(side=tk.TOP, padx=10, pady=5)
		lab = tk.Label(self.which_script_frame, text="Active script:")
		lab.pack(side=tk.LEFT)

		# underlying variable tied to the dropdown menu, needed to run self.change_mode when the selection changes
		self.optionvar = tk.StringVar(master)
		self.optionvar.trace("w", self.change_mode)
		self.optionvar.set(self.all_script_list[0][0])
		# build the acutal dropdown menu
		self.which_script = tk.OptionMenu(self.which_script_frame, self.optionvar, *[x[0] for x in self.all_script_list])
		self.which_script.pack(side=tk.LEFT, padx=10)
		
		###############################################
		# third, build the GUI control buttons
		self.control_frame = tk.Frame(master, relief=tk.RAISED, borderwidth=1)
		self.control_frame.pack(side=tk.TOP, fill='x', padx=10, pady=5)
		
		self.run_butt = tk.Button(self.control_frame, text="RUN", width=7, command=lambda: run_as_thread(self.do_the_thing))
		button_default_font = self.run_butt.cget("font")
		# print(button_default_font)
		# RUN button has bigger font than the other buttons
		self.run_butt.configure(font=(button_default_font, 18))
		self.run_butt.pack(side=tk.LEFT, padx=10, pady=10)
		
		# help
		self.help_butt = tk.Button(self.control_frame, text="Help", width=10, command=self.help_func)
		self.help_butt.pack(side=tk.LEFT, padx=10, pady=10)
		
		# clear
		self.clear_butt = tk.Button(self.control_frame, text="Clear", width=10, command=self.clear_func)
		self.clear_butt.pack(side=tk.LEFT, padx=10, pady=10)
		
		# debug checkbox
		self.debug_check_var = tk.IntVar()
		self.debug_check = tk.Checkbutton(self.control_frame, text="show extra info", variable=self.debug_check_var)
		self.debug_check.pack(side=tk.RIGHT, padx=10, pady=10)
		
		###############################################
		# fourth, build the "scrolledtext" object to serve as my output terminal
		# doesn't need a frame, already has a frame built into it kinda
		self.edit_space = tkst.ScrolledText(
			master=master,
			wrap='word',  # wrap text at full words only
			width=100,  # characters
			height=25,  # text lines
			bg='beige'  # background color of edit area
		)
		self.edit_space.pack(fill='both', expand=True, padx=8, pady=8)
		self.edit_space.configure(state='disabled')
		# get the default font & measure size of a space char in this font
		self.edit_space_font = tkfont.nametofont(self.edit_space.cget("font"))
		self.edit_space_unit = self.edit_space_font.measure(" ")

		###############################################
		# fifth, overwrite the core function pointers to use new GUI methods
		
		# VERY IMPORTANT: overwrite the default print function with one that goes to the GUI
		core.MY_PRINT_FUNC = self.my_write
		# VERY IMPORTANT: overwrite the default simple-choice function with one that makes a popup
		core.MY_SIMPLECHOICE_FUNC = gui_inputpopup_trigger
		# VERY IMPORTANT: overwrite the default general input function with one that makes a popup
		core.MY_GENERAL_INPUT_FUNC = gui_inputpopup_trigger
		# VERY IMPORTANT: overwrite the default fileprompt function with one that uses a popup filedialogue
		core.MY_FILEPROMPT_FUNC = gui_fileprompt
		# also this
		core.MY_JUSTIFY_STRINGLIST = self.gui_justify_stringlist
		
		# print version & instructions
		self.print_header()
		# start the popup loop
		self.spin_to_handle_inputs()
		# load the initial script to populate payload & helptext
		self.change_mode()
		
		# done with init
		return
示例#32
0
def init_widgets():
    """Make all the window components."""
    win.columnconfigure(0, weight=1)
    win.transient(master=TK_ROOT)
    tk_tools.set_window_icon(win)
    win.protocol("WM_DELETE_WINDOW", quit)
    win.bind("<Escape>", quit)

    pane = PanedWindow(
        win,
        orient=VERTICAL,
        sashpad=2,  # Padding above/below panes
        sashwidth=3,  # Width of border
        sashrelief=RAISED,  # Raise the border between panes
    )
    UI['pane'] = pane
    pane.grid(row=1, column=0, sticky='NSEW')
    win.rowconfigure(1, weight=1)

    UI['tabs'] = ttk.Notebook(pane)
    UI['tabs'].enable_traversal()  # Add keyboard shortcuts
    pane.add(UI['tabs'])
    pane.paneconfigure(UI['tabs'], minsize=50)

    trans_frame = ttk.Frame(pane)
    trans_frame.rowconfigure(1, weight=1)
    trans_frame.columnconfigure(0, weight=1)

    ttk.Label(
        trans_frame,
        text=_('Transcript:'),
    ).grid(
        row=0,
        column=0,
        sticky=W,
    )

    trans_inner_frame = ttk.Frame(trans_frame, borderwidth=2, relief='sunken')
    trans_inner_frame.grid(row=1, column=0, sticky='NSEW')
    trans_inner_frame.rowconfigure(0, weight=1)
    trans_inner_frame.columnconfigure(0, weight=1)

    default_bold_font = font.nametofont('TkDefaultFont').copy()
    default_bold_font['weight'] = 'bold'

    UI['trans'] = Text(
        trans_inner_frame,
        width=10,
        height=4,
        wrap='word',
        relief='flat',
        state='disabled',
        font='TkDefaultFont',
    )
    UI['trans_scroll'] = tk_tools.HidingScroll(
        trans_inner_frame,
        orient=VERTICAL,
        command=UI['trans'].yview,
    )
    UI['trans'].tag_config(
        'bold',
        font=default_bold_font,
    )
    UI['trans']['yscrollcommand'] = UI['trans_scroll'].set
    UI['trans_scroll'].grid(row=0, column=1, sticky='NS')
    UI['trans'].grid(row=0, column=0, sticky='NSEW')

    ttk.Button(
        win,
        text=_('Save'),
        command=save,
    ).grid(row=2, column=0)

    # Don't allow resizing the transcript box to be smaller than the
    # original size.
    trans_frame.update_idletasks()
    pane.paneconfigure(trans_frame, minsize=trans_frame.winfo_reqheight())
import tkinter as tk
from tkinter import ttk
import tkinter.font as font
try:  #if the application is run on windows it looks nicer, but not on mac or linux
    from ctypes import wind11
    wind11.shcore.SetProcessDpiAwareness(1)
except:
    pass

root = tk.Tk()
root.title("Distance Converter")

font.nametofont("TkDefaultFont").configure(
    size=15)  #changes font for all text except entry
#must change font within entry func
style = ttk.Style(root)
print(style.theme_names())
print(style.theme_use("aqua"))

meters_value = tk.StringVar()
feet_value = tk.StringVar(value="Feet shown here")


def calculate_feet(*args):
    try:
        meters = float(meters_value.get())
        feet = meters * 3.28084
        feet_value.set(
            f"{feet:.3f}"
        )  #feet:.3f is pretty much set precision. 3 is for 3 decimals, f is for floats
    except ValueError:
示例#34
0
    def __init__(self, playlists: list[Playlist], defaults: dict):

        root = ThemedTk(theme='black')
        root.option_add('*tearOff', tk.FALSE)
        root.wm_title("btecify")
        root.wm_iconbitmap('assets\\btecify.ico')
        root.resizable(width=False, height=False)
        root.wm_iconify()
        root.wm_deiconify()

        for namefont in tkfont.names(root):
            rootfont = tkfont.nametofont(namefont)
            rootfont.config(family="Lucida Console")

        def _onclose():
            self.output = ["EXIT"]
            root.destroy()

        root.protocol("WM_DELETE_WINDOW", _onclose)

        self.selectedplaylist = tk.StringVar()
        self.playlists = playlists
        self._generateplaylistnames()
        self.songqueuevar = tk.StringVar(value=[])
        self.volume = tk.IntVar(value=50)
        self.seek = tk.DoubleVar(value=0)
        self.songlistvar = tk.StringVar(value=[])
        self.playlistsongsvar = tk.StringVar(value=[])
        self.progressbarvar = tk.IntVar(value=0)
        self.songsearchqueryvar = tk.StringVar(value="")
        self.extrainfoplaylistsvar = tk.StringVar(value=[])
        self.searchfunc = searchsongname
        self.discordpresencevar = tk.BooleanVar(value=defaults['discord'])

        self.keybinds: list[tuple[str, str]] = []

        # CONSOLE
        consolewindow = tk.Toplevel(root)
        consolewindow.wm_title("Console Logs")
        consolewindow.wm_protocol("WM_DELETE_WINDOW",
                                  lambda: consolewindow.wm_withdraw())
        consolewindow.wm_withdraw()
        consolewindow.wm_resizable(False, False)

        consolewindowframe = ttk.Frame(consolewindow,
                                       padding=5,
                                       relief="groove")
        consolewindowframe.grid()

        consolewindowtext = tk.Text(consolewindowframe,
                                    foreground='white',
                                    background='black',
                                    state='disabled',
                                    width=100,
                                    height=40)
        consolewindowtext.grid(row=0, column=0)

        consolewindowtextscrollbar = ttk.Scrollbar(
            consolewindowframe,
            orient=tk.VERTICAL,
            command=consolewindowtext.yview)
        consolewindowtext['yscrollcommand'] = consolewindowtextscrollbar.set
        consolewindowtextscrollbar.grid(row=0, column=1, sticky='ns')

        def resetconsolewindow(*args):
            consolewindowtext.yview_moveto(1.0)

        consolewindowtext.bind('<Visibility>', resetconsolewindow)
        consolewindowtext.bind('<FocusIn>', resetconsolewindow)

        # KEYBINDS
        keybindwindow = tk.Toplevel(root)
        keybindwindow.wm_title("Keybindings")
        keybindwindow.wm_protocol("WM_DELETE_WINDOW",
                                  lambda: keybindwindow.wm_withdraw())
        keybindwindow.wm_resizable(False, False)
        keybindwindow.wm_withdraw()

        keybindwindowframe = ttk.Frame(keybindwindow,
                                       padding=5,
                                       relief='groove')
        keybindwindowframe.grid()

        keybindlistframe = ttk.Frame(keybindwindowframe,
                                     padding=3,
                                     relief='groove')
        keybindlistframe.grid(row=0, column=0)

        keybindings = [i for i in defaults['keybinds']]
        keybindlist = []
        for x in range(len(keybindings)):
            kbname = str(keybindings[x])
            newframe = ttk.Frame(keybindlistframe)
            newframe.grid(column=0, row=x)

            newlabel = ttk.Label(
                newframe,
                text=kbname + ": ",
                width=max(map(lambda a: len(a), keybindings)) + 2)
            newlabel.grid(row=0, column=0)

            keybindtextvariable = tk.StringVar("")
            newentry = ttk.Entry(newframe, textvariable=keybindtextvariable)
            newentry.grid(row=0, column=1)
            newentry.bind('<FocusIn>',
                          lambda *args: self._addchange('keybinds'))

            keybindlist.append((kbname, keybindtextvariable))

        keybindbuttonsframe = ttk.Frame(keybindwindowframe,
                                        padding=3,
                                        relief='groove')
        keybindbuttonsframe.grid(row=1, column=0)

        keybindbuttondefault = ttk.Button(
            keybindbuttonsframe,
            text="RESET TO DEFAULTS",
            command=lambda: self._setoutput("defaultkeybinds"))
        keybindbuttondefault.grid(row=0, column=0)

        keybindbuttonconfirm = ttk.Button(
            keybindbuttonsframe,
            text="CONFIRM KEYBINDINGS",
            command=lambda: self._setoutput(
                "updatekeybinds", [(i[0], i[1].get()) for i in keybindlist]))
        keybindbuttonconfirm.grid(row=0, column=1)

        # MENU
        menubar = tk.Menu(root)
        root.configure(menu=menubar)

        menuplaylist = tk.Menu(menubar)
        menusong = tk.Menu(menubar)
        menufile = tk.Menu(menubar)

        menubar.add_cascade(menu=menuplaylist, label="Playlist")
        menubar.add_cascade(menu=menusong, label="Song")
        menubar.add_cascade(menu=menufile, label="File")

        menubar.add_separator()

        menubar.add_command(label="Playlist: None", state="disabled")
        menubarplaylistlabelindex = len(menubar.winfo_children()) + 1

        menuplaylist.add_command(label="New...", command=self._newplaylist)
        menuplaylist.add_command(label="Delete", command=self._deleteplaylist)
        menuplaylist.add_command(label="Rename...",
                                 command=self._renameplaylist)
        menuplaylist.add_command(label="Copy...", command=self._copyplaylist)
        menuplaylist.add_separator()
        menuplaylist.add_command(label="Reset watched",
                                 command=self._unwatchplaylist)
        menuplaylist.add_command(label="Requeue", command=self._requeue)
        menuplaylist.add_separator()
        menuplaylist.add_command(label="Reset from Youtube",
                                 command=self._resetfromyoutube)

        menusong.add_command(label="New...", command=self._newsong)
        menusong.add_command(label="Delete",
                             command=lambda: self._setoutput(
                                 "deletesongs", *self._getselectedsongs()))
        menusong.add_separator()
        menusong.add_command(label="Add selected songs to selected playlist",
                             command=self._addsongtoplaylist)
        menusong.add_command(
            label="Remove selected songs from selected playlist",
            command=lambda: self._setoutput("removesongsfromplaylist",
                                            self._getselectedplaylist(),
                                            self._getselectedsongs()))
        menusong.add_separator()
        menusong.add_command(label="Play selected song",
                             command=self._playselectedsong)
        menusong.add_command(label="Play random song",
                             command=lambda: self._setoutput("randomsong"))

        menufile.add_command(label="View console logs...",
                             command=consolewindow.wm_deiconify)
        menufile.add_command(
            label="Open data directory...",
            command=lambda: self._setoutput("opendatadirectory"))
        menufile.add_separator()
        menufile.add_command(label="Change keybinds...",
                             command=keybindwindow.wm_deiconify)
        menufile.add_separator()
        menufile.add_checkbutton(
            label="Discord Presence",
            command=lambda: self._setoutput('discordpresence',
                                            self.discordpresencevar.get()),
            variable=self.discordpresencevar)
        menufile.add_separator()
        menufile.add_command(label="Change API key...",
                             command=lambda: self._setoutput("newapikey"))
        menufile.add_separator()
        menufile.add_command(label="Login Details...",
                             command=self._logindetails)
        menufile.add_command(label="Sync playlist to btecify servers",
                             command=lambda: self._setoutput("syncwithserver"))

        # PRIMARY FRAME

        primaryframe = ttk.Frame(root)
        primaryframe.grid()

        # QUEUE
        queuelabelframe = ttk.Labelframe(primaryframe,
                                         text="Song queue",
                                         relief='groove',
                                         borderwidth=5)
        queuelabelframe.grid(column=0,
                             row=0,
                             columnspan=2,
                             rowspan=2,
                             sticky='nswe')

        queuelist = mylistbox(queuelabelframe,
                              height=15,
                              listvariable=self.songqueuevar,
                              width=50,
                              exportselection=False,
                              selectmode=tk.MULTIPLE)
        queuelistscrollbar = ttk.Scrollbar(queuelabelframe,
                                           orient=tk.VERTICAL,
                                           command=queuelist.yview)

        queuelist.grid(column=0, row=0, sticky='nswe')
        queuelistscrollbar.grid(column=1, row=0, sticky='ns')

        queuelist['yscrollcommand'] = queuelistscrollbar.set

        # PLAYER INFORMATION
        playingframe = ttk.Labelframe(primaryframe,
                                      text="Playing Song",
                                      relief='groove',
                                      padding=5)
        playingframe.grid(column=2, row=0, sticky='new')

        songinfo = ttk.Label(
            playingframe,
            text=
            f"No playlist\nNo song playing\nNo song author\nNo duration\n{PLAYINGINFOPLACEHOLDER}",
            justify=tk.CENTER,
            anchor=tk.CENTER)
        songinfo.grid(column=0, row=0, sticky='ew')

        songdesc = ttk.Label(playingframe,
                             text="",
                             justify=tk.CENTER,
                             anchor=tk.CENTER)
        songdesc.grid(column=0, row=1)

        songprogress = ttk.Progressbar(playingframe,
                                       orient=tk.HORIZONTAL,
                                       mode='determinate',
                                       variable=self.progressbarvar)
        songprogress.grid(column=0, row=3, sticky='wes')

        songseeker = ttk.Scale(playingframe, from_=0, to=1, variable=self.seek)
        songseeker.grid(column=0, row=4, sticky='wes')
        songseeker.bind("<ButtonPress-1>",
                        lambda *args: self.changes.update({'seeking': True}))
        songseeker.bind("<ButtonRelease-1>",
                        lambda *args: self.changes.update({'seeking': False}))

        playingframe.grid_rowconfigure((0, 1, 2, 3), weight=1)

        # SONG SELECTION AND SONG VIEWING
        songselectionandviewingframe = ttk.Frame(primaryframe)
        songselectionandviewingframe.grid(column=3,
                                          row=0,
                                          columnspan=2,
                                          rowspan=2)

        songlistnotebook = ttk.Notebook(songselectionandviewingframe)
        songlistnotebook.grid(column=0, row=0)

        songlistframe = ttk.Frame(songlistnotebook, padding=1)

        songlist = mylistbox(songlistframe,
                             height=15,
                             listvariable=self.songlistvar,
                             selectmode=tk.MULTIPLE,
                             bg="#282828",
                             disabledforeground="gray80",
                             fg="white",
                             activestyle='dotbox',
                             selectbackground="#282828",
                             selectforeground="red2",
                             width=50,
                             exportselection=False)
        songlistscrollbar = ttk.Scrollbar(songlistframe,
                                          orient=tk.VERTICAL,
                                          command=songlist.yview)
        ################################################################################################################

        playlistsongsframe = ttk.Frame(songlistnotebook, padding=1)

        playlistsongslist = mylistbox(playlistsongsframe,
                                      height=15,
                                      listvariable=self.playlistsongsvar,
                                      selectmode=tk.MULTIPLE,
                                      bg="#282828",
                                      disabledforeground="gray80",
                                      fg="white",
                                      activestyle='dotbox',
                                      selectbackground="#282828",
                                      selectforeground="red2",
                                      width=50,
                                      exportselection=False)
        playlistsongslistscrollbar = ttk.Scrollbar(
            playlistsongsframe,
            orient=tk.VERTICAL,
            command=playlistsongslist.yview)
        ################################################################################################################

        _songlistsearchchangedcommand = root._register(
            self._songlistsearchchanged)
        songsearchentry = ttk.Entry(
            songselectionandviewingframe,
            validate="all",
            validatecommand=(_songlistsearchchangedcommand, '%V'),
            textvariable=self.songsearchqueryvar,
        )

        self.completeselectedsongs: list[Song] = []

        resetsonglistselectionbutton = ttk.Button(
            songselectionandviewingframe,
            text="RESET SELECTION|SELECTED: 0",
            command=lambda: self._addchange("resetselectedsongs"))

        songlist.grid(row=0, column=0, columnspan=2)
        songlistscrollbar.grid(row=0, column=2, sticky='wns')

        playlistsongslist.grid(row=0, column=0, columnspan=2)
        playlistsongslistscrollbar.grid(row=0, column=2, sticky='wns')

        songsearchentry.grid(row=1, column=0, sticky='ews')
        resetsonglistselectionbutton.grid(row=2, column=0, sticky='nw')

        songlist['yscrollcommand'] = songlistscrollbar.set
        playlistsongslist['yscrollcommand'] = playlistsongslistscrollbar.set

        songlistnotebook.add(songlistframe, text="Song list")
        songlistnotebook.add(playlistsongsframe, text="empty")

        # BOTTOM LEFT LOGO
        btecifyiconimage = tk.PhotoImage(file="assets/btecify64.png")
        btecifyiconlabel = ttk.Label(primaryframe, image=btecifyiconimage)
        btecifyiconlabel.grid(column=0, row=2, sticky='ws')

        # PLAYLIST SELECT
        playlistselectframe = ttk.LabelFrame(primaryframe,
                                             text="Playlist select",
                                             relief='groove',
                                             padding=3)
        playlistselectframe.grid(row=2, column=3, sticky='wn')

        playlistselectcombobox = ttk.Combobox(
            playlistselectframe,
            values=self.playlistnames,
            textvariable=self.selectedplaylist,
            width=26,
            state='readonly')
        self.selectedplaylist.trace_add(
            mode="write", callback=self._playlistcomboboxvalueupdated)
        playlistselectcombobox.set(playlists[0].name)
        playlistselectcombobox.grid(sticky='ewn')

        playlistselectbutton = ttk.Button(playlistselectframe,
                                          text="SWITCH TO PLAYLIST",
                                          command=self._chooseplaylist)
        playlistselectbutton.grid(row=1, sticky='s')

        # PLAYER BUTTONS
        bottommiddleframe = ttk.LabelFrame(primaryframe,
                                           text="Player controls",
                                           relief='groove',
                                           padding=5)
        bottommiddleframe.grid(column=2, row=1, sticky='wnse')

        pausebutton = ttk.Button(bottommiddleframe,
                                 text="PAUSE",
                                 command=self._pause)
        pausebutton.grid(row=0, column=0, columnspan=3, sticky='ew')

        skipbutton = ttk.Button(bottommiddleframe,
                                text="SKIP",
                                command=self._skip)
        skipbutton.grid(row=1, sticky='w')

        loopbutton = ttk.Button(bottommiddleframe,
                                text="LOOP: DISABLED",
                                command=lambda: self._setoutput("loop"))
        loopbutton.grid(row=1, column=1, padx=120)

        removesongbutton = ttk.Button(bottommiddleframe,
                                      text="REMOVE SONG",
                                      command=self._playerremovesongbutton)
        removesongbutton.grid(row=1, column=2, sticky='e')

        volumeslider = ttk.LabeledScale(bottommiddleframe,
                                        from_=0,
                                        to=100,
                                        variable=self.volume,
                                        compound='bottom')
        volumeslider.scale.set(defaults['volume'])
        volumeslider.scale.configure(command=self._volchange)
        volumeslider.label.update()
        volumeslider.grid(row=2, columnspan=3, sticky='ew')

        bottommiddleframe.grid_rowconfigure((0, 1, 2), weight=1)
        bottommiddleframe.grid_columnconfigure((0, 1), weight=1)

        # EXTRA SONG INFORMATION
        extrasonginfoframe = ttk.Labelframe(primaryframe,
                                            text="Song Info",
                                            relief="sunken",
                                            padding=3)
        extrasonginfoframe.grid(row=2, column=1, columnspan=2, sticky="nesw")

        extrasonginfoname = ttk.Label(extrasonginfoframe,
                                      text="NO SONG",
                                      justify=tk.LEFT,
                                      anchor="w")
        extrasonginfoname.grid(row=0, column=0, sticky="nesw")

        extrasonginfoplaylistlabelframe = ttk.Labelframe(extrasonginfoframe,
                                                         text="In Playlists",
                                                         relief="groove",
                                                         padding=5)
        extrasonginfoplaylistlabelframe.grid(row=1, column=0, sticky="w")

        extrasonginfoplaylists = mylistbox(
            extrasonginfoplaylistlabelframe,
            height=5,
            selectmode="browse",
            listvariable=self.extrainfoplaylistsvar,
            exportselection=False)
        extrasonginfoplaylists.grid(row=0, column=0, sticky="")

        extrasonginfoplaylistsresetbutton = ttk.Button(
            extrasonginfoplaylistlabelframe,
            text="RESET",
            command=lambda: extrasonginfoplaylists.selection_clear(
                0, 100000) or self.extraplaylistselection.clear(
                ))  # Executes two statements in one lambda.

        extrasonginfoplaylistsresetbutton.grid(row=1, column=0, sticky='nesw')

        extrasonginfobuttonsframe = ttk.Frame(extrasonginfoplaylistlabelframe,
                                              padding=2)
        extrasonginfobuttonsframe.grid(row=0, column=1, sticky='nesw')

        extrasonginforemovebutton = ttk.Button(
            extrasonginfobuttonsframe,
            text="REMOVE SONG FROM PLAYLISTS",
            command=self._extrasonginforemovebuttonfunc)
        extrasonginforemovebutton.grid(row=0, column=0, sticky='')

        extrasonginfoopensong = ttk.Button(
            extrasonginfobuttonsframe,
            text="OPEN IN YOUTUBE",
            command=lambda: self._setoutput("openinyoutube", [
                *self.completeselectedsongs
            ] or [self._getselectedsong()]))
        extrasonginfoopensong.grid(row=1, column=0, sticky='')

        def _updatebasedonvalues():
            extrasongselectedplaylistvalues = self._getextrasongselectedplaylists(
                extrasonginfoplaylists)
            if self.changes[
                    'songinfo'] or extrasongselectedplaylistvalues != self.extraplaylistselection:
                if self.playingsong is not None:
                    self.progressbarvar.set(value=self.progressbar)
                    playlistofthissong = self.playlistwhichsongisfrom
                    if playlistofthissong is None:
                        playlistofthissong = "Played manually"
                        removesongbutton.configure(state='disabled')
                    else:
                        playlistofthissong = playlistofthissong.name
                        removesongbutton.configure(state='active')
                    songinfo['text'] = (
                        f"{playlistofthissong}\n{self.playingsong.name[:len(PLAYINGINFOPLACEHOLDER)]}\n{self.playingsong.author}\n{self.playingsong.duration}\n"
                        + PLAYINGINFOPLACEHOLDER)
                    if self.paused:
                        songdesc['text'] = "PAUSED"
                        pausebutton['text'] = "PLAY"
                    else:
                        songdesc['text'] = "PLAYING"
                        pausebutton['text'] = "PAUSE"

                if self.loop:
                    loopbutton['text'] = "LOOP: ENABLED"
                else:
                    loopbutton['text'] = "LOOP: DISABLED"

                targetsong = self._getselectedsong()
                if targetsong is not None:
                    extrasonginfoname['text'] = targetsong.name[:(
                        queuelist.cget("width") //
                        3) + len(PLAYINGINFOPLACEHOLDER)]
                    self.playlistswithtargetsong = list(
                        filter(lambda a: targetsong in a.getsongs(),
                               self.playlists))
                    self.extrainfoplaylistsvar.set(
                        [i.name for i in self.playlistswithtargetsong])
                    extrasonginfoplaylists.selection_clear(0, 1000000)
                    self.extraplaylistselection.extend([
                        i for i in extrasongselectedplaylistvalues
                        if i not in self.extraplaylistselection
                    ])

                    for i, v in enumerate(self.extraplaylistselection):
                        if v in self.playlistswithtargetsong:
                            extrasonginfoplaylists.selection_set(
                                self.playlistswithtargetsong.index(v))
                        else:
                            self.extraplaylistselection.remove(v)
                else:
                    extrasonginfoname['text'] = "NO SONG"
                    self.extrainfoplaylistsvar.set([])
                    extrasonginfoplaylists.selection_clear(0, 10000)

                self._addchange('songinfo', False)

            if self.changes['resetselectedsongs']:
                songlist.selection_clear(0, 100000000)
                queuelist.selection_clear(0, 100000)
                playlistsongslist.selection_clear(0, 100000)

                self.completeselectedsongs = []
                resetsonglistselectionbutton.configure(
                    text=f"RESET SELECTION   |   SELECTED: 0")
                self._addchange('songinfo')
                self._addchange('resetselectedsongs', False)

            currentlyselectedsonglistvalues = self._getselectedvalues(
                songlist, self.displaysonglist)
            currentlyselectedqueuevalues = self._getselectedvalues(
                queuelist, self.songqueue)
            currentlyselectedplaylistsongsvalues = self._getselectedvalues(
                playlistsongslist, self.displayplaylistsongs)
            displayablesongsinsonglist = set([
                i for i in self.displaysonglistnew
                if i in self.completeselectedsongs
            ])
            displayablesongsinqueuelist = set([
                i for i in self.songqueuenew if i in self.completeselectedsongs
            ])
            displayablesongsinplaylistsongslist = set([
                i for i in self.displayplaylistsongsnew
                if i in self.completeselectedsongs
            ])

            if self.changes['songlist'] or (
                    currentlyselectedsonglistvalues !=
                    displayablesongsinsonglist
            ) or (displayablesongsinqueuelist != currentlyselectedqueuevalues
                  ) or (displayablesongsinplaylistsongslist !=
                        currentlyselectedplaylistsongsvalues):
                if self.changes['songlist']:
                    self._songlistsearchchanged()
                    self.songlistvar.set(
                        value=[i.name for i in self.displaysonglistnew])
                    self.playlistsongsvar.set(
                        value=[i.name for i in self.displayplaylistsongsnew])
                    self.displaysonglist = self.displaysonglistnew
                    self.displayplaylistsongs = self.displayplaylistsongsnew

                    songlist.selection_clear(0, 1000000)
                    queuelist.selection_clear(0, 1000000)
                    playlistsongslist.selection_clear(0, 10000)

                    self._addchange('songinfo')
                    self._addchange('songlist', False)
                else:
                    self.completeselectedsongs.extend([
                        i for i in currentlyselectedsonglistvalues
                        if i not in self.completeselectedsongs
                    ])
                    self.completeselectedsongs.extend([
                        i for i in currentlyselectedqueuevalues
                        if i not in self.completeselectedsongs
                    ])
                    self.completeselectedsongs.extend([
                        i for i in currentlyselectedplaylistsongsvalues
                        if i not in self.completeselectedsongs
                    ])
                    for song in self.completeselectedsongs:
                        if song:
                            if song in self.displaysonglistnew:
                                songlist.selection_set(
                                    self.displaysonglistnew.index(song))
                            if song in self.songqueuenew:
                                queuelist.selection_set(
                                    self.songqueuenew.index(song))
                            if song in self.displayplaylistsongsnew:
                                playlistsongslist.selection_set(
                                    self.displayplaylistsongsnew.index(song))
                    self._addchange('songinfo')
                    resetsonglistselectionbutton.configure(
                        text=
                        f"RESET SELECTION   |   SELECTED: {len(self.completeselectedsongs)}"
                    )

            if self.changes['songqueue']:
                queuelist.selection_clear(0, 100000)
                self.songqueue = self.songqueuenew
                self.songqueuevar.set(value=[
                    f"{i+1:>3}: {v.name}" for i, v in enumerate(self.songqueue)
                ])
                self._addchange('songqueue', False)

            if self.changes['playlistoptions']:
                self._generateplaylistnames()
                playlistselectcombobox['values'] = self.playlistnames
                self._addchange('songinfo')
                self._addchange('playlistoptions', False)

            if self.changes['progressbar']:
                self.progressbarvar.set(value=self.progressbar)
                self._addchange('progressbar', False)

            if self.changes['playlistcomboboxupdate']:
                playlist = self._getselectedplaylist()
                label = "Playlist: "
                if playlist:
                    label += playlist.name
                else:
                    label += "None"
                menubar.entryconfigure(menubarplaylistlabelindex, label=label)

                songlistnotebook.tab(1, text=self._getselectedplaylist().name)
                self._addchange("songlist")
                self._addchange('playlistcomboboxupdate', False)

            if self.changes['updatelogs']:
                logstoadd = self.newlogs[len(self.logs):]
                consolewindowtext['state'] = 'normal'
                for log in logstoadd:
                    logstr = ""
                    timevalues = log[0]
                    logstr += f"{timevalues.tm_hour:0>2}:{timevalues.tm_min:0>2}:{timevalues.tm_sec:0>2}: "
                    for obj in log[1]:
                        objstring = str(obj).replace("\n", "\n\t  ")
                        logstr += objstring + " "
                    consolewindowtext.insert('end', logstr + "\n\n")
                consolewindowtext['state'] = 'disabled'

                self.logs = self.newlogs
                self._addchange('updatelogs', False)

            if self.changes['seeking']:
                val = self.seek.get()
                if 0 < val < 1:
                    self._setoutput('seek', self.seek.get())

            if self.changes['keybinds']:
                for kbset in keybindlist:
                    for j in self.keybinds:
                        if j[0] == kbset[0]:
                            kbset[1].set(j[1])
                self._addchange("keybinds", False)

            root.after(10, _updatebasedonvalues)

        _updatebasedonvalues()

        G.musicgui = self
        root.mainloop()
示例#35
0
 def init_fonts(self):
     self.bigfont = font.nametofont("TkDefaultFont")
     self.bigfont.configure(size=48)
     self.scorefont = font.nametofont("TkDefaultFont")
     self.scorefont.configure(size=20)
示例#36
0
    def __init__(
            self,
            tk,
            lst,
            has_none=True,
            has_def=True,
            none_desc=(('line', 'Do not add anything.'),),
            title='BEE2',
            callback=_NO_OP,
            callback_params=(),
            attributes=(),
            ):
        """Create a window object.

        Read from .selected_id to get the currently-chosen Item name, or None
        if the <none> Item is selected.
        Args:
        - tk: Must be a Toplevel window, either the tk() root or another
        window if needed.
        - lst: A list of Item objects, defining the visible items.
        - If has_none is True, a <none> item will be added to the beginning
          of the list.
        - If has_def is True, the 'Reset to Default' button will appear,
          which resets to the suggested item.
        - none_desc holds an optional description for the <none> Item,
          which can be used to describe what it results in.
        - title is the title of the selector window.
        - callback is a function to be called whenever the selected item
         changes.
        - callback_params is a list of additional values which will be
          passed to the callback function.
          The first arguement to the callback is always the selected item ID.
        - full_context controls if the short or long names are used for the
          context menu.
        - attributes is a list of AttrDef tuples.
          Each tuple should contain an ID, display text, and default value.
          If the values are True or False a check/cross will be displayed,
          otherwise they're a string.
        """
        self.noneItem = Item('NONE', '', desc=none_desc)
        self.noneItem.icon = img.png('BEE2/none_96')
        self.disp_label = StringVar()
        self.display = None
        self.disp_btn = None
        self.chosen_id = None
        self.callback = callback
        self.callback_params = callback_params
        self.suggested = None
        self.has_def = has_def

        if has_none:
            self.item_list = [self.noneItem] + lst
        else:
            self.item_list = lst
        self.selected = self.item_list[0]
        self.orig_selected = self.selected
        self.parent = tk
        self._readonly = False

        self.win = Toplevel(tk)
        self.win.withdraw()
        self.win.title("BEE2 - " + title)
        self.win.transient(master=tk)
        self.win.resizable(True, True)
        self.win.iconbitmap('../BEE2.ico')
        self.win.protocol("WM_DELETE_WINDOW", self.exit)
        self.win.bind("<Escape>", self.exit)

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

        # PanedWindow allows resizing the two areas independently.
        self.pane_win = PanedWindow(
            self.win,
            orient=HORIZONTAL,
            sashpad=2,  # Padding above/below panes
            sashwidth=3,  # Width of border
            sashrelief=RAISED,  # Raise the border between panes
        )
        self.pane_win.grid(row=0, column=0, sticky="NSEW")
        self.win.columnconfigure(0, weight=1)
        self.win.rowconfigure(0, weight=1)

        self.wid = {}
        shim = ttk.Frame(self.pane_win, relief="sunken")
        shim.rowconfigure(0, weight=1)
        shim.columnconfigure(0, weight=1)

        # We need to use a canvas to allow scrolling.
        self.wid_canvas = Canvas(shim, highlightthickness=0)
        self.wid_canvas.grid(row=0, column=0, sticky="NSEW")

        # Add another frame inside to place labels on.
        self.pal_frame = ttk.Frame(self.wid_canvas)
        self.wid_canvas.create_window(1, 1, window=self.pal_frame, anchor="nw")

        self.wid_scroll = ttk.Scrollbar(
            shim,
            orient=VERTICAL,
            command=self.wid_canvas.yview,
        )
        self.wid_scroll.grid(row=0, column=1, sticky="NS")
        self.wid_canvas['yscrollcommand'] = self.wid_scroll.set

        if utils.MAC:
            # Labelframe doesn't look good here on OSX
            self.sugg_lbl = ttk.Label(
                self.pal_frame,
                # Draw lines with box drawing characters
                text="\u250E\u2500Suggested\u2500\u2512"
            )
        else:
            self.sugg_lbl = ttk.LabelFrame(
                self.pal_frame,
                text="Suggested",
                labelanchor=N,
                height=50,
            )

        # Holds all the widgets which provide info for the current item.
        self.prop_frm = ttk.Frame(self.pane_win, borderwidth=4, relief='raised')
        self.prop_frm.columnconfigure(1, weight=1)

        # Border around the selected item icon.
        self.prop_icon_frm = ttk.Frame(
            self.prop_frm,
            borderwidth=4,
            relief='raised',
            width=ICON_SIZE,
            height=ICON_SIZE,
            )
        self.prop_icon_frm.grid(row=0, column=0, columnspan=4)

        self.prop_icon = ttk.Label(self.prop_icon_frm)
        self.prop_icon.img = img.png('BEE2/blank_96')
        self.prop_icon['image'] = self.prop_icon.img
        self.prop_icon.grid(row=0, column=0)

        self.prop_name = ttk.Label(
            self.prop_frm,
            text="Item",
            justify=CENTER,
            font=("Helvetica", 12, "bold"),
            )
        self.prop_name.grid(row=1, column=0, columnspan=4)
        self.prop_author = ttk.Label(self.prop_frm, text="Author")
        self.prop_author.grid(row=2, column=0, columnspan=4)

        self.prop_desc_frm = ttk.Frame(self.prop_frm, relief="sunken")
        self.prop_desc_frm.grid(row=4, column=0, columnspan=4, sticky="NSEW")
        self.prop_desc_frm.rowconfigure(0, weight=1)
        self.prop_desc_frm.columnconfigure(0, weight=1)
        self.prop_frm.rowconfigure(4, weight=1)

        self.prop_desc = tkRichText(
            self.prop_desc_frm,
            width=40,
            height=4,
            font="TkSmallCaptionFont",
            )
        self.prop_desc.grid(
            row=0,
            column=0,
            padx=(2, 0),
            pady=2,
            sticky='NSEW',
            )

        self.prop_scroll = ttk.Scrollbar(
            self.prop_desc_frm,
            orient=VERTICAL,
            command=self.prop_desc.yview,
            )
        self.prop_scroll.grid(
            row=0,
            column=1,
            sticky="NS",
            padx=(0, 2),
            pady=2,
        )
        self.prop_desc['yscrollcommand'] = self.prop_scroll.set

        ttk.Button(
            self.prop_frm,
            text="OK",
            command=self.save,
            ).grid(
                row=6,
                column=0,
                padx=(8, 8),
                )

        if self.has_def:
            self.prop_reset = ttk.Button(
                self.prop_frm,
                text="Reset to Default",
                command=self.sel_suggested,
                )
            self.prop_reset.grid(
                row=6,
                column=1,
                sticky='EW',
                )

        ttk.Button(
            self.prop_frm,
            text="Cancel",
            command=self.exit,
            ).grid(
                row=6,
                column=2,
                padx=(8, 8),
                )

        self.win.option_add('*tearOff', False)
        self.context_menu = Menu(self.win)

        self.norm_font = font.nametofont('TkMenuFont')

        # Make a font for showing suggested items in the context menu
        self.sugg_font = self.norm_font.copy()
        self.sugg_font['weight'] = font.BOLD

        # Make a font for previewing the suggested item
        self.mouseover_font = self.norm_font.copy()
        self.mouseover_font['slant'] = font.ITALIC
        self.context_var = IntVar()

        # Re-order items appropriately.
        #
        self.item_list.sort(
            # Alphabetical order
            key=lambda it: it.longName
        )
        self.item_list.sort(
            # Sort by group name
            key=lambda it: it.group.casefold() if it.group else ''
        )
        self.item_list.sort(
            # Make non-grouped items go first
            key=lambda it: 2 if it.group else 1
        )

        for ind, item in enumerate(self.item_list):
            if item == self.noneItem:
                item.button = ttk.Button(
                    self.pal_frame,
                    image=item.icon,
                    )
                item.context_lbl = '<None>'
            else:
                item.button = ttk.Button(
                    self.pal_frame,
                    text=item.shortName,
                    image=item.icon,
                    compound='top',
                    )
            self.context_menu.add_radiobutton(
                label=item.context_lbl,
                command=functools.partial(self.sel_item_id, item.name),
                var=self.context_var,
                value=ind,
                )

            item.win = self.win
            utils.bind_leftclick(
                item.button,
                functools.partial(self.sel_item, item),
            )
            utils.bind_leftclick_double(
                item.button,
                self.save,
            )
        self.flow_items(None)
        self.wid_canvas.bind("<Configure>", self.flow_items)

        self.pane_win.add(shim)
        self.pane_win.add(self.prop_frm)

        # Force a minimum size for the two parts
        self.pane_win.paneconfigure(shim, minsize=100, stretch='always')
        self.prop_frm.update_idletasks()  # Update reqwidth()
        self.pane_win.paneconfigure(
            self.prop_frm,
            minsize=200,
            stretch='never',
        )

        if attributes:
            attr_frame = ttk.Frame(self.prop_frm)
            attr_frame.grid(
                row=5,
                column=0,
                columnspan=3,
                sticky=EW,
            )

            self.attr = {}
            # Add in all the attribute labels
            for index, (at_id, desc, value) in enumerate(attributes):
                desc_label = ttk.Label(
                    attr_frame,
                    text=desc,
                )
                self.attr[at_id] = val_label = ttk.Label(
                    attr_frame,
                )
                val_label.default = value
                if isinstance(value, bool):
                    # It's a tick/cross label
                    val_label['image'] = (
                        ICON_CHECK
                        if value else
                        ICON_CROSS,
                    )
                # Position in a 2-wide grid
                desc_label.grid(
                    row=index // 2,
                    column=(index % 2)*2,
                    sticky=E,
                )
                val_label.grid(
                    row=index // 2,
                    column=(index % 2)*2 + 1,
                    sticky=W,
                )
        else:
            self.attr = None
示例#37
0
    def create_view(self):
        """Draw the window."""

        # root
        self.root = tk.Tk()
        self.root.title("Comic Crawler")

        # setup theme on linux
        if sys.platform.startswith("linux"):
            try:
                ttk.Style().theme_use("clam")
            except tk.TclError:
                pass

        # adjust scale, dimension
        scale = get_scale(self.root)
        if scale < 1:
            scale = 1.0

        self.root.geometry("{w}x{h}".format(w=int(500 * scale),
                                            h=int(400 * scale)))

        if scale != 1:
            old_scale = self.root.tk.call('tk', 'scaling')
            self.root.tk.call("tk", "scaling", old_scale * scale)

        # Use pt for builtin fonts
        for name in ("TkDefaultFont", "TkTextFont", "TkHeadingFont",
                     "TkMenuFont", "TkFixedFont", "TkTooltipFont",
                     "TkCaptionFont", "TkSmallCaptionFont", "TkIconFont"):
            f = font.nametofont(name)
            size = f.config()["size"]
            if size < 0:
                size = int(-size / 96 * 72)
                f.config(size=size)

        # Treeview doesn't scale its rowheight
        ttk.Style().configure("Treeview", rowheight=int(20 * scale))

        # url label
        tk.Label(self.root, text="輸入連結︰").pack(anchor="w")

        # url entry
        entry_url = ttk.Entry(self.root)
        entry_url.pack(fill="x")
        self.entry_url = entry_url

        # bunch of buttons
        self.create_btn_bar()

        # notebook
        self.notebook = ttk.Notebook(self.root)
        self.notebook.pack(expand=True, fill="both")

        # download manager
        frame = ttk.Frame(self.notebook)
        self.notebook.add(frame, text="任務列表")

        # mission table
        self.view_table = create_mission_table(frame)

        # library
        frame = ttk.Frame(self.notebook)
        self.notebook.add(frame, text="圖書館")

        # library buttons
        btn_bar = ttk.Frame(frame)
        btn_bar.pack()

        self.btn_update = ttk.Button(btn_bar, text="檢查更新")
        self.btn_update.pack(side="left")

        self.btn_download_update = ttk.Button(btn_bar, text="下載更新")
        self.btn_download_update.pack(side="left")

        # library treeview scrollbar container
        frame_lib = ttk.Frame(frame)
        frame_lib.pack(expand=True, fill="both")

        # library table
        self.library_table = create_mission_table(frame_lib)

        # domain list
        frame = ttk.Frame(self.notebook)
        self.notebook.add(frame, text="支援的網域")

        table = Table(frame,
                      columns=[{
                          "id": "host",
                          "text": "域名"
                      }, {
                          "id": "mod",
                          "text": "模組",
                          "anchor": "center"
                      }],
                      tv_opt={"show": "headings"})

        for domain in list_domain():
            table.add({"host": domain, "mod": domain_index[domain].name})

        # batch analyzer
        frame = ttk.Frame(self.notebook)
        self.notebook.add(frame, text="批次加入")

        btn_bar = ttk.Frame(frame)
        btn_bar.pack()

        self.btn_batch_analyze = ttk.Button(btn_bar, text="開始分析")
        self.btn_batch_analyze.pack(side="left")

        self.btn_batch_analyze_stop = ttk.Button(btn_bar, text="停止分析")
        self.btn_batch_analyze_stop.pack(side="left")

        self.text_batch_analyze = create_scrollable_text(frame)

        # status bar
        statusbar = ttk.Label(self.root, text="Comic Crawler", anchor="e")
        statusbar.pack(anchor="e")
        self.statusbar = statusbar
示例#38
0
 def __init_fonts(self):
     self.bigfont = font.nametofont("TkDefaultFont")
     self.bigfont.configure(size=int(48))
     self.scorefont = font.nametofont("TkDefaultFont")
     self.scorefont.configure(size=int(20))
示例#39
0
    def __init__(
        self,
        tk,
        lst,
        *,  # Make all keyword-only for readability
        has_none=True,
        has_def=True,
        sound_sys: FileSystem = None,
        modal=False,
        # i18n: 'None' item description
        none_desc=_('Do not add anything.'),
        none_attrs: dict = EmptyMapping,
        title='BEE2',
        desc='',
        readonly_desc='',
        callback: Callable[..., None] = None,
        callback_params=(),
        attributes=()):
        """Create a window object.

        Read from .selected_id to get the currently-chosen Item name, or None
        if the <none> Item is selected.
        Args:
        - tk: Must be a Toplevel window, either the tk() root or another
        window if needed.
        - lst: A list of Item objects, defining the visible items.
        - If has_none is True, a <none> item will be added to the beginning
          of the list.
        - If has_def is True, the 'Reset to Default' button will appear,
          which resets to the suggested item.
        - If snd_sample_sys is set, a '>' button will appear next to names
          to play the associated audio sample for the item.
          The value should be a FileSystem to look for samples in.
        - none_desc holds an optional description for the <none> Item,
          which can be used to describe what it results in.
        - title is the title of the selector window.
        - callback is a function to be called whenever the selected item
         changes.
        - callback_params is a list of additional values which will be
          passed to the callback function.
          The first argument to the callback is always the selected item ID.
        - full_context controls if the short or long names are used for the
          context menu.
        - attributes is a list of AttrDef tuples.
          Each tuple should contain an ID, display text, and default value.
          If the values are True or False a check/cross will be displayed,
          otherwise they're a string.
        - desc is descriptive text to display on the window, and in the widget
          tooltip.
        - readonly_desc will be displayed on the widget tooltip when readonly.
        - modal: If True, the window will block others while open.
        """
        self.noneItem = Item(
            name=_('NONE'),
            short_name='',
            icon='BEE2/none_96.png',
            desc=none_desc,
            attributes=dict(none_attrs),
        )

        # The textbox on the parent window.
        self.display = None  # type: tk_tools.ReadOnlyEntry

        # Variable associated with self.display.
        self.disp_label = StringVar()

        # The '...' button to open our window.
        self.disp_btn = None  # type: ttk.Button

        # ID of the currently chosen item
        self.chosen_id = None

        # Callback function, and positional arugments to pass
        if callback is not None:
            self.callback = callback
            self.callback_params = list(callback_params)
        else:
            self.callback = None
            self.callback_params = ()

        # Item object for the currently suggested item.
        self.suggested = None

        # Should we have the 'reset to default' button?
        self.has_def = has_def
        self.description = desc
        self.readonly_description = readonly_desc

        if has_none:
            self.item_list = [self.noneItem] + lst
        else:
            self.item_list = lst
        try:
            self.selected = self.item_list[0]  # type: Item
        except IndexError:
            LOGGER.error('No items for window "{}"!', title)
            # We crash without items, forcefully add the None item in so at
            # least this works.
            self.item_list = [self.noneItem]
            self.selected = self.noneItem

        self.orig_selected = self.selected
        self.parent = tk
        self._readonly = False
        self.modal = modal

        self.win = Toplevel(tk)
        self.win.withdraw()
        self.win.title("BEE2 - " + title)
        self.win.transient(master=tk)

        # Allow resizing in X and Y.
        self.win.resizable(True, True)

        tk_tools.set_window_icon(self.win)

        # Run our quit command when the exit button is pressed, or Escape
        # on the keyboard.
        self.win.protocol("WM_DELETE_WINDOW", self.exit)
        self.win.bind("<Escape>", self.exit)

        # Allow navigating with arrow keys.
        self.win.bind("<KeyPress>", self.key_navigate)

        # A map from group name -> header widget
        self.group_widgets = {}
        # A map from folded name -> display name
        self.group_names = {}
        self.grouped_items = defaultdict(list)
        # A list of folded group names in the display order.
        self.group_order = []

        # The maximum number of items that fits per row (set in flow_items)
        self.item_width = 1

        if desc:
            self.desc_label = ttk.Label(
                self.win,
                text=desc,
                justify=LEFT,
                anchor=W,
                width=5,  # Keep a small width, so this doesn't affect the
                # initial window size.
            )
            self.desc_label.grid(row=0, column=0, sticky='EW')

        # PanedWindow allows resizing the two areas independently.
        self.pane_win = PanedWindow(
            self.win,
            orient=HORIZONTAL,
            sashpad=2,  # Padding above/below panes
            sashwidth=3,  # Width of border
            sashrelief=RAISED,  # Raise the border between panes
        )
        self.pane_win.grid(row=1, column=0, sticky="NSEW")
        self.win.columnconfigure(0, weight=1)
        self.win.rowconfigure(1, weight=1)

        self.wid = {}
        shim = ttk.Frame(self.pane_win, relief="sunken")
        shim.rowconfigure(0, weight=1)
        shim.columnconfigure(0, weight=1)

        # We need to use a canvas to allow scrolling.
        self.wid_canvas = Canvas(shim, highlightthickness=0)
        self.wid_canvas.grid(row=0, column=0, sticky="NSEW")

        # Add another frame inside to place labels on.
        self.pal_frame = ttk.Frame(self.wid_canvas)
        self.wid_canvas.create_window(1, 1, window=self.pal_frame, anchor="nw")

        self.wid_scroll = tk_tools.HidingScroll(
            shim,
            orient=VERTICAL,
            command=self.wid_canvas.yview,
        )
        self.wid_scroll.grid(row=0, column=1, sticky="NS")
        self.wid_canvas['yscrollcommand'] = self.wid_scroll.set

        utils.add_mousewheel(self.wid_canvas, self.win)

        if utils.MAC:
            # Labelframe doesn't look good here on OSX
            self.sugg_lbl = ttk.Label(
                self.pal_frame,
                # Draw lines with box drawing characters
                text="\u250E\u2500" + _("Suggested") + "\u2500\u2512",
            )
        else:
            self.sugg_lbl = ttk.LabelFrame(
                self.pal_frame,
                text=_("Suggested"),
                labelanchor=N,
                height=50,
            )

        # Holds all the widgets which provide info for the current item.
        self.prop_frm = ttk.Frame(self.pane_win,
                                  borderwidth=4,
                                  relief='raised')
        self.prop_frm.columnconfigure(1, weight=1)

        # Border around the selected item icon.
        width, height = img.tuple_size(ICON_SIZE_LRG)
        self.prop_icon_frm = ttk.Frame(
            self.prop_frm,
            borderwidth=4,
            relief='raised',
            width=width,
            height=height,
        )
        self.prop_icon_frm.grid(row=0, column=0, columnspan=4)

        self.prop_icon = ttk.Label(
            self.prop_icon_frm,
            image=img.color_square(img.PETI_ITEM_BG, ICON_SIZE_LRG),
        )
        self.prop_icon.grid(row=0, column=0)

        name_frame = ttk.Frame(self.prop_frm)

        self.prop_name = ttk.Label(
            name_frame,
            text="Item",
            justify=CENTER,
            width=-10,
            font=("Helvetica", 12, "bold"),
        )
        name_frame.grid(row=1, column=0, columnspan=4)
        name_frame.columnconfigure(0, weight=1)
        self.prop_name.grid(row=0, column=0)

        # For music items, add a '>' button to play sound samples
        if sound_sys is not None and sound.initiallised:
            self.samp_button = samp_button = ttk.Button(
                name_frame,
                text=BTN_PLAY,
                width=1,
            )
            samp_button.grid(row=0, column=1)
            add_tooltip(
                samp_button,
                _("Play a sample of this item."),
            )

            def set_samp_play():
                samp_button['text'] = BTN_PLAY

            def set_samp_stop():
                samp_button['text'] = BTN_STOP

            self.sampler = sound.SamplePlayer(
                stop_callback=set_samp_play,
                start_callback=set_samp_stop,
                system=sound_sys,
            )
            samp_button['command'] = self.sampler.play_sample
            utils.bind_leftclick(self.prop_icon, self.sampler.play_sample)
            samp_button.state(('disabled', ))
        else:
            self.sampler = None

        self.prop_author = ttk.Label(self.prop_frm, text="Author")
        self.prop_author.grid(row=2, column=0, columnspan=4)

        self.prop_desc_frm = ttk.Frame(self.prop_frm, relief="sunken")
        self.prop_desc_frm.grid(row=4, column=0, columnspan=4, sticky="NSEW")
        self.prop_desc_frm.rowconfigure(0, weight=1)
        self.prop_desc_frm.columnconfigure(0, weight=1)
        self.prop_frm.rowconfigure(4, weight=1)

        self.prop_desc = tkRichText(
            self.prop_desc_frm,
            width=40,
            height=4,
            font="TkSmallCaptionFont",
        )
        self.prop_desc.grid(
            row=0,
            column=0,
            padx=(2, 0),
            pady=2,
            sticky='NSEW',
        )

        self.prop_scroll = tk_tools.HidingScroll(
            self.prop_desc_frm,
            orient=VERTICAL,
            command=self.prop_desc.yview,
        )
        self.prop_scroll.grid(
            row=0,
            column=1,
            sticky="NS",
            padx=(0, 2),
            pady=2,
        )
        self.prop_desc['yscrollcommand'] = self.prop_scroll.set

        ttk.Button(
            self.prop_frm,
            text=_("OK"),
            command=self.save,
        ).grid(
            row=6,
            column=0,
            padx=(8, 8),
        )

        if self.has_def:
            self.prop_reset = ttk.Button(
                self.prop_frm,
                text=_("Reset to Default"),
                command=self.sel_suggested,
            )
            self.prop_reset.grid(
                row=6,
                column=1,
                sticky='EW',
            )

        ttk.Button(
            self.prop_frm,
            text=_("Cancel"),
            command=self.exit,
        ).grid(
            row=6,
            column=2,
            padx=(8, 8),
        )

        self.win.option_add('*tearOff', False)
        self.context_menu = Menu(self.win)

        self.norm_font = tk_font.nametofont('TkMenuFont')

        # Make a font for showing suggested items in the context menu
        self.sugg_font = self.norm_font.copy()
        self.sugg_font['weight'] = tk_font.BOLD

        # Make a font for previewing the suggested item
        self.mouseover_font = self.norm_font.copy()
        self.mouseover_font['slant'] = tk_font.ITALIC
        self.context_var = IntVar()

        # The headers for the context menu
        self.context_menus = {}

        # Sort alphabetically, preferring a sort key if present.
        self.item_list.sort(key=lambda it: it.sort_key or it.longName)

        for ind, item in enumerate(self.item_list):  # type: int, Item
            if item == self.noneItem:
                item.button = ttk.Button(
                    self.pal_frame,
                    image=item.icon,
                )
                item.context_lbl = '<None>'
            else:
                item.button = ttk.Button(
                    self.pal_frame,
                    text=item.shortName,
                    image=item.icon,
                    compound='top',
                )

            group_key = item.group.casefold()
            self.grouped_items[group_key].append(item)

            if group_key not in self.group_names:
                # If the item is groupless, use 'Other' for the header.
                self.group_names[group_key] = item.group or _('Other')

            if not item.group:
                # Ungrouped items appear directly in the menu.
                menu = self.context_menu
            else:
                try:
                    menu = self.context_menus[group_key]
                except KeyError:
                    self.context_menus[group_key] = menu = Menu(
                        self.context_menu, )

            menu.add_radiobutton(
                label=item.context_lbl,
                command=functools.partial(self.sel_item_id, item.name),
                var=self.context_var,
                value=ind,
            )

            item.win = self.win

            @utils.bind_leftclick(item.button)
            def click_item(event=None, *, _item=item):
                """Handle clicking on the item.

                If it's already selected, save and close the window.
                """
                # We need to capture the item in a default, since it's
                # the same variable in different iterations
                if _item is self.selected:
                    self.save()
                else:
                    self.sel_item(_item)

        # Convert to a normal dictionary, after adding all items.
        self.grouped_items = dict(self.grouped_items)

        # Figure out the order for the groups - alphabetical.
        # Note - empty string should sort to the beginning!
        self.group_order[:] = sorted(self.grouped_items.keys())

        for index, (key, menu) in enumerate(
                sorted(self.context_menus.items(), key=itemgetter(0)),
                # We start with the ungrouped items, so increase the index
                # appropriately.
                start=len(self.grouped_items.get('', ()))):
            self.context_menu.add_cascade(
                menu=menu,
                label=self.group_names[key],
            )
            # Set a custom attribute to keep track of the menu's index.
            menu.index = index

        for group_key, text in self.group_names.items():
            self.group_widgets[group_key] = GroupHeader(
                self,
                text,
            )
            self.group_widgets[group_key].should_show = True

        self.flow_items(None)
        self.wid_canvas.bind("<Configure>", self.flow_items)

        self.pane_win.add(shim)
        self.pane_win.add(self.prop_frm)

        # Force a minimum size for the two parts
        self.pane_win.paneconfigure(shim, minsize=100, stretch='always')
        self.prop_frm.update_idletasks()  # Update reqwidth()
        self.pane_win.paneconfigure(
            self.prop_frm,
            minsize=200,
            stretch='never',
        )

        if attributes:
            attr_frame = ttk.Frame(self.prop_frm)
            attr_frame.grid(
                row=5,
                column=0,
                columnspan=3,
                sticky=EW,
            )

            self.attr = {}
            # Add in all the attribute labels
            for index, attr in enumerate(attributes):
                desc_label = ttk.Label(
                    attr_frame,
                    text=attr.desc,
                )
                self.attr[attr.id] = val_label = ttk.Label(attr_frame, )
                val_label.default = attr.default
                val_label.type = attr.type
                if attr.type is AttrTypes.BOOL:
                    # It's a tick/cross label
                    val_label['image'] = (ICON_CHECK
                                          if attr.default else ICON_CROSS, )
                elif attr.type is AttrTypes.COLOR:
                    # A small colour swatch.
                    val_label.configure(relief=RAISED, )
                    # Show the color value when hovered.
                    add_tooltip(val_label)

                # Position in a 2-wide grid
                desc_label.grid(
                    row=index // 2,
                    column=(index % 2) * 2,
                    sticky=E,
                )
                val_label.grid(
                    row=index // 2,
                    column=(index % 2) * 2 + 1,
                    sticky=W,
                )
        else:
            self.attr = None
        if self.chkBtnQ.get():
            msg += self.print_treasure(type_q(multiplier))

        if self.chkBtnR.get():
            msg += self.print_treasure(type_r(multiplier))

        if self.chkBtnS.get():
            msg += self.print_treasure(type_s(multiplier))

        if self.chkBtnT.get():
            msg += self.print_treasure(type_t(multiplier))

        if self.chkBtnU.get():
            msg += self.print_treasure(type_u(multiplier))

        if self.chkBtnV.get():
            msg += self.print_treasure(type_v(multiplier))

        return msg


#main section
root = Tk()
root.title("BF Treasure Generator")
#root.geometry('500x500')
default_font = font.nametofont("TkDefaultFont")
default_font.configure(size=20)

app = Application(root)

root.mainloop()
示例#41
0
import functools

from app.tooltip import add_tooltip, set_tooltip
from app import tk_tools
from localisation import gettext

from typing import List, Iterator, Optional

UP_ARROW = '\u25B3'
DN_ARROW = '\u25BD'
ELLIPSIS = '\u2026'

ROW_HEIGHT = 16
ROW_PADDING = 2

BODY_FONT = font.nametofont('TkDefaultFont')

style = ttk.Style()
style.configure(
    'CheckDetails.TCheckbutton',
    background='white',
)

# An event generated when items are all unchecked.
# Use to disable buttons when needed
EVENT_NO_CHECKS = '<<NoItemsChecked>>'
EVENT_HAS_CHECKS = '<<ItemsChecked>>'


def truncate(text, width):
    """Truncate text to fit in the given space."""
示例#42
0
 def set_font(self, *args):
     font_size = self.settings['font size'].get()
     font_names = ('TkDefaultFont', 'TkMenuFont', 'TkTextFont')
     for font_name in font_names:
         tk_font = nametofont(font_name)
         tk_font.config(size=font_size)
示例#43
0
 def create_fonts(self):
     self.font_mono = tkfont.Font(family="Courier", size=10)
     fontname = ttk.Style().lookup("TLabel", "font")
     self.font_label_bold = tkfont.nametofont(fontname).copy()
     self.font_label_bold.configure(weight="bold")
示例#44
0
            output.sameAs = menu.entrycget(0, "label")
        else:
            var.set("None")

    def handleFocusOut(self, event):
        self.root.destroy()

def setLabelAndOutputModeFunc(var, label, output, i):
    def func():
        var.set(label)
        output.setMode(i)
    return func

def setLabelAndSameAsFunc(var, sameAs, output):
    def func():
        var.set(sameAs)
        output.sameAs = sameAs
    return func

if os.environ.get('BLOCK_BUTTON') == "1":
    if os.fork() != 0:
        root = Tk()
        if DEFAULT_FONT_FAMILY and DEFAULT_FONT_SIZE:
            font.nametofont("TkDefaultFont").config(family=DEFAULT_FONT_FAMILY, size=DEFAULT_FONT_SIZE)
        manager = MonitorManager(root)
        root.mainloop()
    else:
        print(DESKTOP_SYMBOL)
else:
    print(DESKTOP_SYMBOL)
示例#45
0
import tkinter as tk
import tkinter.font as tkfont
win = tk.Tk()
win.geometry('400x300')
win.title('Show Canvas')
default_font = tkfont.nametofont('TkDefaultFont')
default_font.configure(size=15)
#photo = tk.PhotoImage(file='python.PNG')
gs = tk.Canvas(win, width=400, heigh=300)
gs.pack()
gs.create_rectangle(50, 20, 150, 80)
gs.create_rectangle(80, 60, 200, 100, fill='#FF0000')
gs.create_line(200, 200, 200, 200, fill='green')
gs.create_line(200, 160, 320, 160, fill='#FF0000')
win.mainloop()
示例#46
0
    def _configure_tags(self):
        main_font = tkfont.nametofont("TkDefaultFont")

        bold_font = main_font.copy()
        bold_font.configure(weight="bold", size=main_font.cget("size"))

        italic_font = main_font.copy()
        italic_font.configure(slant="italic", size=main_font.cget("size"))

        h1_font = main_font.copy()
        h1_font.configure(size=round(main_font.cget("size") * 1.4), weight="bold")

        h2_font = main_font.copy()
        h2_font.configure(size=round(main_font.cget("size") * 1.3), weight="bold")

        h3_font = main_font.copy()
        h3_font.configure(size=main_font.cget("size"), weight="bold")

        small_font = main_font.copy()
        small_font.configure(size=round(main_font.cget("size") * 0.8))
        small_italic_font = italic_font.copy()
        small_italic_font.configure(size=round(main_font.cget("size") * 0.8))

        # Underline on font looks better than underline on tag
        underline_font = main_font.copy()
        underline_font.configure(underline=True)

        self.tag_configure("h1", font=h1_font, spacing3=5)
        self.tag_configure("h2", font=h2_font, spacing3=5)
        self.tag_configure("h3", font=h3_font, spacing3=5)
        self.tag_configure("p", spacing1=0, spacing3=10, spacing2=0)
        self.tag_configure("line_block", spacing1=0, spacing3=10, spacing2=0)
        self.tag_configure("em", font=italic_font)
        self.tag_configure("strong", font=bold_font)

        # TODO: hyperlink syntax options may require different background as well
        self.tag_configure(
            "a",
            **{**get_syntax_options_for_tag("hyperlink"), "underline": False},
            font=underline_font
        )
        self.tag_configure("small", font=small_font)
        self.tag_configure("light", foreground="gray")
        self.tag_configure("remark", font=small_italic_font)
        self.tag_bind("a", "<ButtonRelease-1>", self._hyperlink_click)
        self.tag_bind("a", "<Enter>", self._hyperlink_enter)
        self.tag_bind("a", "<Leave>", self._hyperlink_leave)

        self.tag_configure("topic_title", lmargin2=16, font=bold_font)
        self.tag_configure("topic_body", lmargin1=16, lmargin2=16)
        self.tag_configure(
            "code",
            font="TkFixedFont",
            # wrap="none", # TODO: needs automatic hor-scrollbar and better padding mgmt
            # background="#eeeeee"
        )
        # if ui_utils.get_tk_version_info() >= (8,6,6):
        #    self.tag_configure("code", lmargincolor=self["background"])

        for i in range(1, 6):
            self.tag_configure("list%d" % i, lmargin1=i * 10, lmargin2=i * 10 + 10)

        toti_code_font = bold_font.copy()
        toti_code_font.configure(
            family=tk.font.nametofont("TkFixedFont").cget("family"), size=bold_font.cget("size")
        )
        self.tag_configure("topic_title_code", font=toti_code_font)
        self.tag_raise("topic_title_code", "code")
        self.tag_raise("topic_title_code", "topic_title")
        self.tag_raise("a", "topic_title")

        # TODO: topic_title + em
        self.tag_raise("em", "topic_title")
        self.tag_raise("a", "em")
        self.tag_raise("a", "topic_body")
        self.tag_raise("a", "topic_title")

        if ui_utils.get_tk_version_info() >= (8, 6, 6):
            self.tag_configure("sel", lmargincolor=self["background"])
        self.tag_raise("sel")
示例#47
0
    def __init__(
            self,
            tk,
            lst,
            has_none=True,
            has_def=True,
            none_desc=(('line', 'Do not add anything.'),),
            title='BEE2',
            callback=_NO_OP,
            callback_params=(),
            ):
        """Create a window object.

        Read from .selected_id to get the currently-chosen Item name, or None
        if the <none> Item is selected.
        Args:
        - tk: Must be a Toplevel window, either the tk() root or another
        window if needed.
        - lst: A list of Item objects, defining the visible items.
        - If has_none is True, a <none> item will be added to the beginning
          of the list.
        - If has_def is True, the 'Reset to Default' button will appear,
          which resets to the suggested item.
        - none_desc holds an optional description for the <none> Item,
          which can be used to describe what it results in.
        - title is the title of the selector window.
        - callback is a function to be called whenever the selected item
         changes.
        - callback_params is a list of additional values which will be
          passed to the callback function.
          The first arguement to the callback is always the selected item ID.
        - full_context controls if the short or long names are used for the
          context menu.
        """
        self.noneItem = Item('NONE', '', desc=none_desc)
        self.noneItem.icon = img.png('BEE2/none_96')
        self.disp_label = StringVar()
        self.display = None
        self.disp_btn = None
        self.chosen_id = None
        self.callback = callback
        self.callback_params = callback_params
        self.suggested = None
        self.has_def = has_def

        if has_none:
            self.item_list = [self.noneItem] + lst
        else:
            self.item_list = lst
        self.selected = self.item_list[0]
        self.orig_selected = self.selected
        self.parent = tk
        self._readonly = False

        self.win = Toplevel(tk)
        self.win.withdraw()
        self.win.title("BEE2 - " + title)
        self.win.transient(master=tk)
        self.win.resizable(True, True)
        self.win.iconbitmap('../BEE2.ico')
        self.win.protocol("WM_DELETE_WINDOW", self.exit)
        self.win.bind("<Escape>", self.exit)

        # PanedWindow allows resizing the two areas independently.
        self.pane_win = ttk.Panedwindow(self.win, orient=HORIZONTAL)
        self.pane_win.grid(row=0, column=0, sticky="NSEW")

        self.wid = {}
        shim = ttk.Frame(self.pane_win, relief="sunken")
        self.win.rowconfigure(0, weight=1)
        self.win.columnconfigure(0, weight=1)
        shim.rowconfigure(0, weight=1)
        shim.columnconfigure(0, weight=1)

        # We need to use a canvas to allow scrolling.
        self.wid_canvas = Canvas(shim, highlightthickness=0)
        self.wid_canvas.grid(row=0, column=0, sticky="NSEW")

        # Add another frame inside to place labels on.
        self.pal_frame = ttk.Frame(self.wid_canvas)
        self.wid_canvas.create_window(1, 1, window=self.pal_frame, anchor="nw")

        self.wid_scroll = ttk.Scrollbar(
            shim,
            orient=VERTICAL,
            command=self.wid_canvas.yview,
        )
        self.wid_scroll.grid(row=0, column=1, sticky="NS")
        self.wid_canvas['yscrollcommand'] = self.wid_scroll.set

        self.sugg_lbl = ttk.LabelFrame(
            self.pal_frame,
            text="Suggested",
            labelanchor=N,
            height=50,
        )

        # Holds all the widgets which provide info for the current item.
        self.prop_frm = ttk.Frame(self.pane_win, borderwidth=4, relief='raised')
        self.prop_frm.columnconfigure(1, weight=1)

        # Border around the selected item icon.
        self.prop_icon_frm = ttk.Frame(
            self.prop_frm,
            borderwidth=4,
            relief='raised',
            width=ICON_SIZE,
            height=ICON_SIZE,
            )
        self.prop_icon_frm.grid(row=0, column=0, columnspan=4)

        self.prop_icon = ttk.Label(self.prop_icon_frm)
        self.prop_icon.img = img.png('BEE2/blank_96')
        self.prop_icon['image'] = self.prop_icon.img
        self.prop_icon.grid(row=0, column=0)

        self.prop_name = ttk.Label(
            self.prop_frm,
            text="Item",
            justify=CENTER,
            font=("Helvetica", 12, "bold"),
            )
        self.prop_name.grid(row=1, column=0, columnspan=4)
        self.prop_author = ttk.Label(self.prop_frm, text="Author")
        self.prop_author.grid(row=2, column=0, columnspan=4)

        self.prop_desc_frm = ttk.Frame(self.prop_frm, relief="sunken")
        self.prop_desc_frm.grid(row=4, column=0, columnspan=4, sticky="NSEW")
        self.prop_desc_frm.rowconfigure(0, weight=1)
        self.prop_desc_frm.columnconfigure(0, weight=1)
        self.prop_frm.rowconfigure(4, weight=1)

        self.prop_desc = tkRichText(
            self.prop_desc_frm,
            width=40,
            height=16,
            font="TkSmallCaptionFont",
            )
        self.prop_desc.grid(
            row=0,
            column=0,
            padx=(2, 0),
            pady=2,
            sticky='NSEW',
            )

        self.prop_scroll = ttk.Scrollbar(
            self.prop_desc_frm,
            orient=VERTICAL,
            command=self.prop_desc.yview,
            )
        self.prop_scroll.grid(
            row=0,
            column=1,
            sticky="NS",
            padx=(0, 2),
            pady=2,
        )
        self.prop_desc['yscrollcommand'] = self.prop_scroll.set

        ttk.Button(
            self.prop_frm,
            text="OK",
            command=self.save,
            ).grid(
                row=5,
                column=0,
                padx=(8, 8),
                )

        if self.has_def:
            self.prop_reset = ttk.Button(
                self.prop_frm,
                text="Reset to Default",
                command=self.sel_suggested,
                )
            self.prop_reset.grid(
                row=5,
                column=1,
                sticky='EW',
                )

        ttk.Button(
            self.prop_frm,
            text="Cancel",
            command=self.exit,
            ).grid(
                row=5,
                column=2,
                padx=(8, 8),
                )

        self.win.option_add('*tearOff', False)
        self.context_menu = Menu(self.win)

        self.norm_font = font.nametofont('TkMenuFont')

        # Make a font for showing suggested items in the context menu
        self.sugg_font = self.norm_font.copy()
        self.sugg_font['weight'] = font.BOLD

        # Make a font for previewing the suggested item
        self.mouseover_font = self.norm_font.copy()
        self.mouseover_font['slant'] = font.ITALIC
        self.context_var = IntVar()

        # Re-order items appropriately.
        #
        self.item_list.sort(
            # Alphabetical order
            key=lambda it: it.longName
        )
        self.item_list.sort(
            # Sort by group name
            key=lambda it: it.group.casefold() if it.group else ''
        )
        self.item_list.sort(
            # Make non-grouped items go first
            key=lambda it: 2 if it.group else 1
        )

        for ind, item in enumerate(self.item_list):
            if item == self.noneItem:
                item.button = ttk.Button(
                    self.pal_frame,
                    image=item.icon,
                    )
                item.context_lbl = '<None>'
            else:
                item.button = ttk.Button(
                    self.pal_frame,
                    text=item.shortName,
                    image=item.icon,
                    compound='top',
                    )
            self.context_menu.add_radiobutton(
                label=item.context_lbl,
                command=functools.partial(self.sel_item_id, item.name),
                var=self.context_var,
                value=ind,
                )

            item.win = self.win
            item.button.bind(
                "<Button-1>",
                functools.partial(self.sel_item, item),
            )
            item.button.bind("<Double-Button-1>", self.save)
        self.flow_items(None)
        self.wid_canvas.bind("<Configure>", self.flow_items)

        self.pane_win.add(shim, weight=1)
        self.pane_win.add(self.prop_frm)
示例#48
0
    def create_widgets(self):

        default_font = font.nametofont("TkDefaultFont")
        default_font.configure(family='Liberation Sans',
                               size=20,
                               weight='bold')

        Label(self, text="RESONANCE CONTROL PANEL").grid(row=0,
                                                         column=0,
                                                         columnspan=5,
                                                         pady=20)

        Label(self,
              text="Frequency (kHz)",
              relief='raised',
              width=20,
              anchor='center').grid(row=3, column=0)
        f1 = Spinbox(self,
                     textvariable=self.freq,
                     from_=0.2,
                     to=10.01,
                     increment=0.01,
                     command=self.freq_change,
                     relief='sunken',
                     bg='#fff',
                     width=7,
                     font=default_font).grid(row=3, column=1)
        Label(self,
              text="2nd Frequency (kHz)",
              relief='raised',
              width=20,
              anchor='center').grid(row=4, column=0)
        #    f2 = Spinbox(self,textvariable = self.freq2 ,from_= 2.0, to = 3.9,increment=0.01,relief = 'sunken', bg='#fff',width=7, font = default_font).grid(row=4,column=1)
        f2 = Label(self,
                   textvariable=self.freq2,
                   relief='sunken',
                   background='#fff',
                   width=7,
                   anchor='w').grid(row=4, column=1, sticky='W')

        Button(self, text="12\N{SQUARE ROOT}2",
               command=self.shadow_default).grid(row=3, column=4)
        Label(self,
              text="Frequency ratio",
              relief='raised',
              width=20,
              anchor='center').grid(row=4, column=3)
        self.shad = Spinbox(self,
                            textvariable=self.shadow,
                            from_=0.001,
                            to=2.5,
                            increment=0.001,
                            command=self.freq_change,
                            relief='sunken',
                            bg='#fff',
                            width=7,
                            font=default_font).grid(row=4, column=4)

        Label(self, text="", width=5).grid(row=5, column=2)

        Label(self,
              text="Generator is",
              relief='raised',
              width=20,
              anchor='center').grid(row=6, column=0)
        self.gen = Spinbox(self,
                           textvariable=self.genstate,
                           values=("OFF", "ON", "CONT"),
                           relief='sunken',
                           bg='#fff',
                           width=7,
                           font=default_font).grid(row=6, column=1)
        Label(self,
              text="Generator on (s)",
              relief='raised',
              width=20,
              anchor='center').grid(row=7, column=0)
        dur = Spinbox(self,
                      textvariable=self.duration,
                      from_=0.1,
                      to=1.9,
                      increment=0.1,
                      relief='sunken',
                      bg='#fff',
                      width=7,
                      font=default_font).grid(row=7, column=1)
        Label(self,
              text="Generator off (s)",
              relief='raised',
              width=20,
              anchor='center').grid(row=8, column=0)
        guard = Spinbox(self,
                        textvariable=self.gtime,
                        from_=0.1,
                        to=1.9,
                        increment=0.1,
                        relief='sunken',
                        bg='#fff',
                        width=7,
                        font=default_font).grid(row=8, column=1)

        Label(self,
              text="Valve is",
              relief='raised',
              width=20,
              anchor='center').grid(row=6, column=3)
        self.pump = Spinbox(self,
                            textvariable=self.pumpstate,
                            values=("OFF", "ON"),
                            relief='sunken',
                            bg='#fff',
                            width=7,
                            font=default_font).grid(row=6, column=4)
        Label(self,
              text="Flush time (s)",
              relief='raised',
              width=20,
              anchor='center').grid(row=7, column=3)
        run = Spinbox(self,
                      textvariable=self.pumprun,
                      from_=0.1,
                      to=10.0,
                      increment=0.1,
                      relief='sunken',
                      bg='#fff',
                      width=7,
                      font=default_font).grid(row=7, column=4)
        Label(self,
              text="Pause time (s)",
              relief='raised',
              width=20,
              anchor='center').grid(row=8, column=3)
        stop = Spinbox(self,
                       textvariable=self.pumpstop,
                       from_=1.0,
                       to=60,
                       increment=1,
                       relief='sunken',
                       bg='#fff',
                       width=7,
                       font=default_font).grid(row=8, column=4)

        self.w = Canvas(self, width=110, height=18, relief="sunken")
        self.w.grid(row=9, column=1)
        self.r = self.w.create_rectangle(0,
                                         0,
                                         99,
                                         16,
                                         fill="silver",
                                         outline='white')

        Label(self, text="", width=5).grid(row=9, column=2)
        self.bar = Progressbar(self,
                               orient="horizontal",
                               length=400,
                               mode="determinate",
                               variable=self.progress_var,
                               maximum=100).grid(row=9, column=3, columnspan=2)

        Button(self, text="Quit", command=self.quitnot, width=7).grid(row=10,
                                                                      column=0,
                                                                      pady=20)
        Button(self, text="Stop", command=self.stopnot, width=7).grid(row=10,
                                                                      column=1,
                                                                      pady=20)
示例#49
0
catcher_height = 100
catcher_startx = canvas_width / 2 - catcher_width / 2
catcher_starty = canvas_height - catcher_height - 20
catcher_startx2 = catcher_startx + catcher_width
catcher_starty2 = catcher_starty + catcher_height

catcher = c.create_arc(catcher_startx,
                       catcher_starty,
                       catcher_startx2,
                       catcher_starty2,
                       start=200,
                       extent=140,
                       style="arc",
                       outline=catcher_color,
                       width=3)
game_font = font.nametofont("TkFixedFont")
game_font.config(size=18)

score = 0
score_text = c.create_text(10,
                           10,
                           anchor="nw",
                           font=game_font,
                           fill="darkblue",
                           text="Score: " + str(score))

lives_remaining = 3
lives_text = c.create_text(canvas_width - 10,
                           10,
                           anchor="ne",
                           font=game_font,
示例#50
0
    def __init__(self, venue_data, run_callback, save_callback):
        super().__init__()

        # Use the official University of Minnesota colors of maroon (#7a0019) and gold (#ffcc33)

        default_font = tkfont.nametofont("TkDefaultFont")
        default_font.configure(size=12)

        self.configure(background="#ffcc33")
        self.option_add("*background", "#ffcc33")
        self.option_add("*TCombobox*Listbox*background", "#ffffff")

        s = ttk.Style()
        s.configure(".", background="#ffcc33")
        s.configure("TButton", font=("calibri", 14, "bold"), foreground="#7a0019")

        # Initialize.
        self.enumerated_venue_data = {
            "City": [(venue, index) for index, venue in enumerate(venue_data["city_list"])],
            "Township": [(venue, index) for index, venue in enumerate(venue_data["township_list"])],
            "County": [(venue, index) for index, venue in enumerate(venue_data["county_list"])],
            "Watershed": [(venue, index) for index, venue in enumerate(venue_data["watershed_list"])],
            "Subregion": [(venue, index) for index, venue in enumerate(venue_data["subregion_list"])]
        }
        self.venue_codes = {
            "City": "GNIS",
            "Township": "GNIS",
            "County": "FIPS",
            "Watershed": "HUC10",
            "Subregion": "HUC8"
        }

        self.run_callback = run_callback
        self.save_callback = save_callback

        # Main window.
        self.iconphoto(False, tk.PhotoImage(file='M.png'))
        self.title("AkeyaaPy")
        self.resizable(False, False)

        # Set up the four main frames
        venue_frame = tk.LabelFrame(self,      text="Venue",      padx=10, pady=10)
        parameters_frame = tk.LabelFrame(self, text="Parameters", padx=10, pady=10)
        aquifers_frame = tk.LabelFrame(self,   text="Aquifers",   padx=10, pady=10)
        buttons_frame = tk.Frame(self,                            padx=10, pady=10)

        venue_frame.grid(     row=0, column=0, rowspan=2,    padx=5, pady=5, sticky=tk.NW)
        aquifers_frame.grid(  row=0, column=1, rowspan=2,    padx=5, pady=5, sticky=tk.NW)
        parameters_frame.grid(row=0, column=2,               padx=5, pady=5, sticky=tk.NW)
        buttons_frame.grid(   row=1, column=2, columnspan=2, padx=5, pady=5, sticky=tk.E)

        # Fill the Venue frame
        venue_types = ["City", "Township", "County", "Watershed", "Subregion", "Neighborhood", "Frame"]
        self.venue_type = tk.StringVar(value=None)

        venue_label = ttk.Label(venue_frame, text="Type ", justify=tk.LEFT)
        venue_cb = ttk.Combobox(
            venue_frame,
            state="readonly",
            textvariable=self.venue_type,
            values=venue_types
        )
        venue_cb.bind("<<ComboboxSelected>>", self.on_venue_type_select)

        venue_label.grid(row=0, column=0, sticky=tk.W)
        venue_cb.grid(row=0, column=1, sticky=tk.W)

        # Fill the Selection frame (a sub-frame in the Venue frame).
        self.selection_frame = ttk.Frame(venue_frame)

        self.selection_name = None
        self.selection_code = None
        self.selection_index = None
        self.enumerated_venue_list = None

        self.selection_text = tk.StringVar()
        self.selection_text.trace("w", self.on_change_selection_text)

        selection_label = ttk.Label(self.selection_frame, text="Name ")
        entry = ttk.Entry(self.selection_frame, textvariable=self.selection_text, width=33)
        entry.focus_set()

        # Fix for setting text colour for Tkinter 8.6.9
        # From: https://core.tcl.tk/tk/info/509cafafae
        style = ttk.Style()
        style.map(
            "Treeview",
            background=[elm for elm in style.map("Treeview", query_opt="background")
                        if elm[:2] != ('!disabled', '!selected')]
        )

        self.selection_tree = ttk.Treeview(self.selection_frame, columns=("#1"), selectmode="browse")
        self.selection_tree.heading("#0", text="Name")
        self.selection_tree.heading("#1", text="Code")
        self.selection_tree.column("#0", stretch=tk.YES)
        self.selection_tree.column("#1", width=100)

        self.selection_tree.bind("<<TreeviewSelect>>", self.on_selection)
        self.selection_tree.tag_configure("current", background="#ffcc33")

        # entry.pack(fill=tk.X, expand=0)
        # self.selection_tree.pack(fill=tk.BOTH, expand=1)

        selection_label.grid(row=0, column=0)
        entry.grid(row=0, column=1, sticky=tk.W)
        self.selection_tree.grid(row=1, column=1, sticky=tk.W)

        # Fill the Neighborhood frame (a sub-frame in the Venue frame).
        self.neighborhood_frame = ttk.Frame(venue_frame)

        self.neighborhood_easting = tk.DoubleVar(value=481738.99)               # Civil Engineering Building
        self.neighborhood_northing = tk.DoubleVar(value=4980337.72)             # Univeristy of Minnesota
        self.neighborhood_radius = tk.DoubleVar(value=10000)                    # Go Gophers!

        easting_text = ttk.Label(self.neighborhood_frame, text="Easting ")
        easting_sb = ttk.Spinbox(
            self.neighborhood_frame,
            textvariable=self.neighborhood_easting,
            from_=189783, increment=100, to=761654                              # min & max for MN
        )

        northing_text = ttk.Label(self.neighborhood_frame, text="Northing ")
        northing_sb = ttk.Spinbox(
            self.neighborhood_frame,
            textvariable=self.neighborhood_northing,
            from_=4816309, increment=100, to=5472347                            # min & max for MN
        )

        radius_text = ttk.Label(self.neighborhood_frame, text="Radius ")
        radius_sb = ttk.Spinbox(
            self.neighborhood_frame,
            textvariable=self.neighborhood_radius,
            from_=0, increment=100, to=1000000
        )

        easting_text.grid(row=0, column=0, sticky=tk.W, pady=2)
        easting_sb.grid(row=0, column=1, sticky=tk.W, pady=2)
        northing_text.grid(row=1, column=0, sticky=tk.W, pady=2)
        northing_sb.grid(row=1, column=1, sticky=tk.W, pady=2)
        radius_text.grid(row=2, column=0, sticky=tk.W, pady=2)
        radius_sb.grid(row=2, column=1, sticky=tk.W, pady=2)

        # Fill the Frame frame (a sub-frame in the Venue frame).
        self.frame_frame = ttk.Frame(venue_frame)

        self.frame_minimum_easting = tk.DoubleVar(value=481738.99 - 10000)      # Civil Engineering Building
        self.frame_maximum_easting = tk.DoubleVar(value=481738.99 + 10000)      # Univeristy of Minnesota
        self.frame_minimum_northing = tk.DoubleVar(value=4980337.72 - 10000)    # Go Gophers!
        self.frame_maximum_northing = tk.DoubleVar(value=4980337.72 + 10000)

        easting_text = tk.Label(self.frame_frame, text="Easting ")
        northing_text = tk.Label(self.frame_frame, text="Northing ")
        minimum_text = tk.Label(self.frame_frame, text="Minimum")
        maximum_text = tk.Label(self.frame_frame, text="Maximum")

        minimum_easting_sb = tk.Spinbox(
            self.frame_frame,
            textvariable=self.frame_minimum_easting,
            from_=189783, increment=100, to=761654                              # min & max for MN
        )

        maximum_easting_sb = tk.Spinbox(
            self.frame_frame,
            textvariable=self.frame_maximum_easting,
            from_=189783, increment=100, to=761654                              # min & max for MN
        )

        minimum_northing_sb = tk.Spinbox(
            self.frame_frame,
            textvariable=self.frame_minimum_northing,
            from_=4816309, increment=100, to=5472347                            # min & max for MN
        )

        maximum_northing_sb = tk.Spinbox(
            self.frame_frame,
            textvariable=self.frame_maximum_northing,
            from_=4816309, increment=100, to=5472347                            # min & max for MN
        )

        minimum_text.grid(row=0, column=1, sticky=tk.W)
        maximum_text.grid(row=0, column=2, sticky=tk.W)

        easting_text.grid(row=1, column=0, sticky=tk.W, pady=2)
        minimum_easting_sb.grid(row=1, column=1, sticky=tk.W, pady=2)
        maximum_easting_sb.grid(row=1, column=2, sticky=tk.W, pady=2)

        northing_text.grid(row=2, column=0, sticky=tk.W, pady=2)
        minimum_northing_sb.grid(row=2, column=1, sticky=tk.W, pady=2)
        maximum_northing_sb.grid(row=2, column=2, sticky=tk.W, pady=2)

        # Fill the Aquifers frame.
        self.cxxx = tk.BooleanVar(value=True)
        self.dxxx = tk.BooleanVar(value=True)
        self.ixxx = tk.BooleanVar(value=True)
        self.kxxx = tk.BooleanVar(value=True)
        self.mxxx = tk.BooleanVar(value=True)
        self.oxxx = tk.BooleanVar(value=True)
        self.pxxx = tk.BooleanVar(value=True)
        self.qxxx = tk.BooleanVar(value=True)
        self.rxxx = tk.BooleanVar(value=True)
        self.uxxx = tk.BooleanVar(value=True)

        cxxx_check = ttk.Checkbutton(aquifers_frame, text="Cxxx", variable=self.cxxx)
        dxxx_check = ttk.Checkbutton(aquifers_frame, text="Dxxx", variable=self.dxxx)
        ixxx_check = ttk.Checkbutton(aquifers_frame, text="Ixxx", variable=self.ixxx)
        kxxx_check = ttk.Checkbutton(aquifers_frame, text="Kxxx", variable=self.kxxx)
        mxxx_check = ttk.Checkbutton(aquifers_frame, text="Mxxx", variable=self.mxxx)
        oxxx_check = ttk.Checkbutton(aquifers_frame, text="Oxxx", variable=self.oxxx)
        pxxx_check = ttk.Checkbutton(aquifers_frame, text="Pxxx", variable=self.pxxx)
        qxxx_check = ttk.Checkbutton(aquifers_frame, text="Qxxx", variable=self.qxxx)
        rxxx_check = ttk.Checkbutton(aquifers_frame, text="Rxxx", variable=self.rxxx)
        uxxx_check = ttk.Checkbutton(aquifers_frame, text="Uxxx", variable=self.uxxx)

        cxxx_check.grid(row=0, column=0, sticky=tk.W)
        dxxx_check.grid(row=1, column=0, sticky=tk.W)
        ixxx_check.grid(row=2, column=0, sticky=tk.W)
        kxxx_check.grid(row=3, column=0, sticky=tk.W)
        mxxx_check.grid(row=4, column=0, sticky=tk.W)
        oxxx_check.grid(row=5, column=0, sticky=tk.W)
        pxxx_check.grid(row=6, column=0, sticky=tk.W)
        qxxx_check.grid(row=7, column=0, sticky=tk.W)
        rxxx_check.grid(row=8, column=0, sticky=tk.W)
        uxxx_check.grid(row=9, column=0, sticky=tk.W)

        # Fill the Parameters frame.
        self.radius = tk.DoubleVar(value=3000)
        self.required = tk.IntVar(value=25)
        self.spacing = tk.DoubleVar(value=1000)
        self.firstyear = tk.IntVar(value=1871)
        self.lastyear = tk.IntVar(value=datetime.datetime.now().year)

        radius_text = ttk.Label(parameters_frame, text="Radius ")
        radius_sb = ttk.Spinbox(parameters_frame, textvariable=self.radius,
                                from_=1, increment=100, to=1000000)

        required_text = ttk.Label(parameters_frame, text="Required ")
        required_sb = ttk.Spinbox(parameters_frame, textvariable=self.required,
                                  from_=6, increment=1, to=10000)

        spacing_text = ttk.Label(parameters_frame, text="Spacing ")
        spacing_sb = ttk.Spinbox(parameters_frame, textvariable=self.spacing,
                                 from_=1, increment=100, to=100000)

        firstyear_text = ttk.Label(parameters_frame, text="First year ")
        firstyear_sb = ttk.Spinbox(parameters_frame, textvariable=self.firstyear,
                                   from_=1871, increment=1, to=datetime.datetime.now().year)

        lastyear_text = ttk.Label(parameters_frame, text="Last year ")
        lastyear_sb = ttk.Spinbox(parameters_frame, textvariable=self.lastyear,
                                  from_=1871, increment=1, to=datetime.datetime.now().year)

        radius_text.grid(row=0, column=0, sticky=tk.W, pady=2)
        radius_sb.grid(row=0, column=1, sticky=tk.W, pady=2)

        required_text.grid(row=1, column=0, sticky=tk.W, pady=2)
        required_sb.grid(row=1, column=1, sticky=tk.W, pady=2)

        spacing_text.grid(row=2, column=0, sticky=tk.W, pady=2)
        spacing_sb.grid(row=2, column=1, sticky=tk.W, pady=2)

        firstyear_text.grid(row=3, column=0, sticky=tk.W, pady=2)
        firstyear_sb.grid(row=3, column=1, sticky=tk.W, pady=2)

        lastyear_text.grid(row=4, column=0, sticky=tk.W, pady=2)
        lastyear_sb.grid(row=4, column=1, sticky=tk.W, pady=2)

        # Fill the buttons frame
        self.run_button = ttk.Button(buttons_frame, text="Run", command=self.run_button_pressed, state=tk.DISABLED)
        self.save_button = ttk.Button(buttons_frame, text="Save", command=self.save_button_pressed, state=tk.DISABLED)
        self.about_button = ttk.Button(buttons_frame, text="About", command=self.about_button_pressed)
        self.exit_button = ttk.Button(buttons_frame, text="Exit", command=self.exit_button_pressed)

        self.exit_button.pack(side=tk.BOTTOM, pady=2)
        self.about_button.pack(side=tk.BOTTOM, pady=2)
        self.save_button.pack(side=tk.BOTTOM, pady=2)
        self.run_button.pack(side=tk.BOTTOM, pady=2)
示例#51
0
 def __init__(self, master, columns=1, tree=True, headings=True):
     """
     columns: int, or len(columns): Number of columns; default: 1
     iter(columns): Iterator of dict() objects; optional. Elements may
         also be strings, equivalent to the "heading" value. Keys:
             "heading": Optional
             "width": Optional"""
     
     try:
         self.nontree_columns = len(columns)
     except TypeError:
         if isinstance(columns, Iterable):
             columns = tuple(columns)
             self.nontree_columns = len(columns)
         else:
             self.nontree_columns = columns
             columns = cycle((dict(),))
     
     show = list()
     self.tree_shown = tree
     if self.tree_shown:
         show.append("tree")
         self.nontree_columns -= 1
     if headings:
         show.append("headings")
     
     self.nontree_columns = range(self.nontree_columns)
     Treeview.__init__(self, master, show=show,
         columns=tuple(self.nontree_columns))
     
     self.heading_font = nametofont("TkHeadingFont")
     self.heading_space = "\N{EN QUAD}"
     self.space_size = self.heading_font.measure(self.heading_space)
     self.text_font = nametofont("TkTextFont")
     
     self.auto_width = list()
     for (key, value) in zip(self.columns(), columns):
         if isinstance(value, str):
             value = dict(heading=value)
         
         if headings:
             try:
                 heading = value["heading"]
             except LookupError:
                 pass
             else:
                 self.heading(key, text=heading)
         
         try:
             width = value["width"]
         except LookupError:
             auto = True
             
             if headings:
                 text = self.heading(key, option="text")
                 text += self.heading_space
                 width = self.heading_font.measure(text)
         
         else:
             auto = False
             
             try:
                 (width, unit) = width
             except TypeError:
                 unit = self.FIGURE
             width *= self.text_font.measure(unit)
             width += self.space_size
         
         self.auto_width.append(auto)
         width = max(width, self.column(key, option="minwidth"))
         stretch = value.get("stretch", False)
         self.column(key, stretch=stretch, width=width)
     
     self.bind("<End>", self.end)
示例#52
0
 def __init__(self, master, columns=1, tree=True, headings=True):
     """
     columns: int, or len(columns): Number of columns; default: 1
     iter(columns): Iterator of dict() objects; optional. Elements may
         also be strings, equivalent to the "heading" value. Keys:
             "heading": Optional
             "width": Optional"""
     
     try:
         self.nontree_columns = len(columns)
     except TypeError:
         if isinstance(columns, Iterable):
             columns = tuple(columns)
             self.nontree_columns = len(columns)
         else:
             self.nontree_columns = columns
             columns = cycle((dict(),))
     
     show = list()
     self.tree_shown = tree
     if self.tree_shown:
         show.append("tree")
         self.nontree_columns -= 1
     if headings:
         show.append("headings")
     
     self.nontree_columns = range(self.nontree_columns)
     Treeview.__init__(self, master, show=show,
         columns=tuple(self.nontree_columns))
     
     self.heading_font = nametofont("TkHeadingFont")
     self.heading_space = "\N{EN QUAD}"
     self.space_size = self.heading_font.measure(self.heading_space)
     self.text_font = nametofont("TkTextFont")
     
     self.auto_width = list()
     for (key, value) in zip(self.columns(), columns):
         if isinstance(value, str):
             value = dict(heading=value)
         
         if headings:
             try:
                 heading = value["heading"]
             except LookupError:
                 pass
             else:
                 self.heading(key, text=heading)
         
         try:
             width = value["width"]
         except LookupError:
             auto = True
             
             if headings:
                 text = self.heading(key, option="text")
                 text += self.heading_space
                 width = self.heading_font.measure(text)
         
         else:
             auto = False
             
             try:
                 (width, unit) = width
             except TypeError:
                 unit = self.FIGURE
             width *= self.text_font.measure(unit)
             width += self.space_size
         
         self.auto_width.append(auto)
         width = max(width, self.column(key, option="minwidth"))
         stretch = value.get("stretch", False)
         self.column(key, stretch=stretch, width=width)
     
     self.bind("<End>", self.end)
            output_strings.append(
                "hash: %s\nresult: %s\nbase64: %s\nascii85: %s\nbase85: %s\n" %
                (name, hexdigest, b64_output, a85_output, b85_output))

        for output_string in output_strings:
            self.text.insert('end', output_string + '\n')

        self.text['state'] = 'disabled'


if __name__ == "__main__":
    root = tix.Tk()
    root.title("纸睡的密码生成器")
    root.geometry('600x400')
    root.minsize(300, 200)

    tkFont.nametofont("TkDefaultFont").config(family="Dengxian", size=11)

    style = ttk.Style()
    style.configure("basic.TFrame", foreground="black")

    mainframe = PasswordConverter(master=root, style="basic.TFrame")

    for child in mainframe.winfo_children():
        child.grid_configure(padx=5, pady=5)

    root.bind('<Return>', lambda _: mainframe.generate_password())
    root.bind('<Escape>', lambda _: root.destroy())

    root.mainloop()
示例#54
0
 def __init__(self, master, column=0):
     self.master = master
     self.column = column
     self.master.columnconfigure(column + 1, weight=1)
     en = font_size(nametofont("TkDefaultFont")["size"] / 2)
     self.master.columnconfigure(column + 0, pad=en)
示例#55
0
    def __init__(
            self,
            tk,
            lst,
            has_none=True,
            has_def=True,
            has_snd_sample=False,
            none_desc=(('line', 'Do not add anything.'),),
            none_attrs: dict=utils.EmptyMapping,
            title='BEE2',
            desc='',
            readonly_desc='',
            callback: Callable[..., None]=None,
            callback_params=(),
            attributes=(),
    ):
        """Create a window object.

        Read from .selected_id to get the currently-chosen Item name, or None
        if the <none> Item is selected.
        Args:
        - tk: Must be a Toplevel window, either the tk() root or another
        window if needed.
        - lst: A list of Item objects, defining the visible items.
        - If has_none is True, a <none> item will be added to the beginning
          of the list.
        - If has_def is True, the 'Reset to Default' button will appear,
          which resets to the suggested item.
        - If has_snd_sample is True, a '>' button will appear next to names
          to play the associated audio sample for the item.
        - none_desc holds an optional description for the <none> Item,
          which can be used to describe what it results in.
        - title is the title of the selector window.
        - callback is a function to be called whenever the selected item
         changes.
        - callback_params is a list of additional values which will be
          passed to the callback function.
          The first arguement to the callback is always the selected item ID.
        - full_context controls if the short or long names are used for the
          context menu.
        - attributes is a list of AttrDef tuples.
          Each tuple should contain an ID, display text, and default value.
          If the values are True or False a check/cross will be displayed,
          otherwise they're a string.
        - desc is descriptive text to display on the window, and in the widget
          tooltip.
        - readonly_desc will be displayed on the widget tooltip when readonly.
        """
        self.noneItem = Item(
            'NONE',
            '',
            desc=none_desc,
            attributes=dict(none_attrs),
        )
        self.noneItem.icon = img.png('BEE2/none_96')

        # The textbox on the parent window.
        self.display = None  # type: tk_tools.ReadOnlyEntry

        # Variable associated with self.display.
        self.disp_label = StringVar()

        # The '...' button to open our window.
        self.disp_btn = None  # type: ttk.Button

        # ID of the currently chosen item
        self.chosen_id = None

        # Callback function, and positional arugments to pass
        if callback is not None:
            self.callback = callback
            self.callback_params = list(callback_params)
        else:
            self.callback = None
            self.callback_params = ()

        # Item object for the currently suggested item.
        self.suggested = None

        # Should we have the 'reset to default' button?
        self.has_def = has_def
        self.description = desc
        self.readonly_description = readonly_desc

        if has_none:
            self.item_list = [self.noneItem] + lst
        else:
            self.item_list = lst
        self.selected = self.item_list[0]  # type: Item
        self.orig_selected = self.selected
        self.parent = tk
        self._readonly = False

        self.win = Toplevel(tk)
        self.win.withdraw()
        self.win.title("BEE2 - " + title)
        self.win.transient(master=tk)

        # Allow resizing in X and Y.
        self.win.resizable(True, True)

        self.win.iconbitmap('../BEE2.ico')

        # Run our quit command when the exit button is pressed, or Escape
        # on the keyboard.
        self.win.protocol("WM_DELETE_WINDOW", self.exit)
        self.win.bind("<Escape>", self.exit)

        # Allow navigating with arrow keys.
        self.win.bind("<KeyPress>", self.key_navigate)

        # A map from group name -> header widget
        self.group_widgets = {}
        # A map from folded name -> display name
        self.group_names = {}
        self.grouped_items = defaultdict(list)
        # A list of folded group names in the display order.
        self.group_order = []

        # The maximum number of items that fits per row (set in flow_items)
        self.item_width = 1

        if desc:
            self.desc_label = ttk.Label(
                self.win,
                text=desc,
                justify=LEFT,
                anchor=W,
                width=5,  # Keep a small width, so this doesn't affect the
                # initial window size.
            )
            self.desc_label.grid(row=0, column=0, sticky='EW')

        # PanedWindow allows resizing the two areas independently.
        self.pane_win = PanedWindow(
            self.win,
            orient=HORIZONTAL,
            sashpad=2,  # Padding above/below panes
            sashwidth=3,  # Width of border
            sashrelief=RAISED,  # Raise the border between panes
        )
        self.pane_win.grid(row=1, column=0, sticky="NSEW")
        self.win.columnconfigure(0, weight=1)
        self.win.rowconfigure(1, weight=1)

        self.wid = {}
        shim = ttk.Frame(self.pane_win, relief="sunken")
        shim.rowconfigure(0, weight=1)
        shim.columnconfigure(0, weight=1)

        # We need to use a canvas to allow scrolling.
        self.wid_canvas = Canvas(shim, highlightthickness=0)
        self.wid_canvas.grid(row=0, column=0, sticky="NSEW")

        # Add another frame inside to place labels on.
        self.pal_frame = ttk.Frame(self.wid_canvas)
        self.wid_canvas.create_window(1, 1, window=self.pal_frame, anchor="nw")

        self.wid_scroll = tk_tools.HidingScroll(
            shim,
            orient=VERTICAL,
            command=self.wid_canvas.yview,
        )
        self.wid_scroll.grid(row=0, column=1, sticky="NS")
        self.wid_canvas['yscrollcommand'] = self.wid_scroll.set

        utils.add_mousewheel(self.wid_canvas, self.win)

        if utils.MAC:
            # Labelframe doesn't look good here on OSX
            self.sugg_lbl = ttk.Label(
                self.pal_frame,
                # Draw lines with box drawing characters
                text="\u250E\u2500Suggested\u2500\u2512"
            )
        else:
            self.sugg_lbl = ttk.LabelFrame(
                self.pal_frame,
                text="Suggested",
                labelanchor=N,
                height=50,
            )

        # Holds all the widgets which provide info for the current item.
        self.prop_frm = ttk.Frame(self.pane_win, borderwidth=4, relief='raised')
        self.prop_frm.columnconfigure(1, weight=1)

        # Border around the selected item icon.
        self.prop_icon_frm = ttk.Frame(
            self.prop_frm,
            borderwidth=4,
            relief='raised',
            width=ICON_SIZE,
            height=ICON_SIZE,
        )
        self.prop_icon_frm.grid(row=0, column=0, columnspan=4)

        self.prop_icon = ttk.Label(self.prop_icon_frm)
        self.prop_icon.img = img.png('BEE2/blank_96')
        self.prop_icon['image'] = self.prop_icon.img
        self.prop_icon.grid(row=0, column=0)

        name_frame = ttk.Frame(self.prop_frm)

        self.prop_name = ttk.Label(
            name_frame,
            text="Item",
            justify=CENTER,
            font=("Helvetica", 12, "bold"),
        )
        name_frame.grid(row=1, column=0, columnspan=4)
        name_frame.columnconfigure(0, weight=1)
        self.prop_name.grid(row=0, column=0)

        # For music items, add a '>' button to play sound samples
        if has_snd_sample and sound.initiallised:
            self.samp_button = samp_button = ttk.Button(
                name_frame,
                text=BTN_PLAY,
                width=1,
            )
            samp_button.grid(row=0, column=1)
            add_tooltip(
                samp_button,
                "Play a sample of this item.",
            )

            def set_samp_play():
                samp_button['text'] = BTN_PLAY

            def set_samp_stop():
                samp_button['text'] = BTN_STOP

            self.sampler = sound.SamplePlayer(
                stop_callback=set_samp_play,
                start_callback=set_samp_stop,
            )
            samp_button['command'] = self.sampler.play_sample
            utils.bind_leftclick(self.prop_icon, self.sampler.play_sample)
            samp_button.state(('disabled',))
        else:
            self.sampler = None

        self.prop_author = ttk.Label(self.prop_frm, text="Author")
        self.prop_author.grid(row=2, column=0, columnspan=4)

        self.prop_desc_frm = ttk.Frame(self.prop_frm, relief="sunken")
        self.prop_desc_frm.grid(row=4, column=0, columnspan=4, sticky="NSEW")
        self.prop_desc_frm.rowconfigure(0, weight=1)
        self.prop_desc_frm.columnconfigure(0, weight=1)
        self.prop_frm.rowconfigure(4, weight=1)

        self.prop_desc = tkRichText(
            self.prop_desc_frm,
            width=40,
            height=4,
            font="TkSmallCaptionFont",
        )
        self.prop_desc.grid(
            row=0,
            column=0,
            padx=(2, 0),
            pady=2,
            sticky='NSEW',
        )

        self.prop_scroll = tk_tools.HidingScroll(
            self.prop_desc_frm,
            orient=VERTICAL,
            command=self.prop_desc.yview,
        )
        self.prop_scroll.grid(
            row=0,
            column=1,
            sticky="NS",
            padx=(0, 2),
            pady=2,
        )
        self.prop_desc['yscrollcommand'] = self.prop_scroll.set

        ttk.Button(
            self.prop_frm,
            text="OK",
            command=self.save,
        ).grid(
            row=6,
            column=0,
            padx=(8, 8),
            )

        if self.has_def:
            self.prop_reset = ttk.Button(
                self.prop_frm,
                text="Reset to Default",
                command=self.sel_suggested,
            )
            self.prop_reset.grid(
                row=6,
                column=1,
                sticky='EW',
            )

        ttk.Button(
            self.prop_frm,
            text="Cancel",
            command=self.exit,
        ).grid(
            row=6,
            column=2,
            padx=(8, 8),
        )

        self.win.option_add('*tearOff', False)
        self.context_menu = Menu(self.win)

        self.norm_font = tk_font.nametofont('TkMenuFont')

        # Make a font for showing suggested items in the context menu
        self.sugg_font = self.norm_font.copy()
        self.sugg_font['weight'] = tk_font.BOLD

        # Make a font for previewing the suggested item
        self.mouseover_font = self.norm_font.copy()
        self.mouseover_font['slant'] = tk_font.ITALIC
        self.context_var = IntVar()

        # The headers for the context menu
        self.context_menus = {}

        # Sort alphabetically, prefering a sort key if present.
        self.item_list.sort(key=lambda it: it.sort_key or it.longName)

        for ind, item in enumerate(self.item_list):  # type: int, Item
            if item == self.noneItem:
                item.button = ttk.Button(
                    self.pal_frame,
                    image=item.icon,
                )
                item.context_lbl = '<None>'
            else:
                item.button = ttk.Button(
                    self.pal_frame,
                    text=item.shortName,
                    image=item.icon,
                    compound='top',
                )

            group_key = item.group.casefold()
            self.grouped_items[group_key].append(item)

            if group_key not in self.group_names:
                # If the item is groupless, use 'Other' for the header.
                self.group_names[group_key] = item.group or 'Other'

            if not item.group:
                # Ungrouped items appear directly in the menu.
                menu = self.context_menu
            else:
                try:
                    menu = self.context_menus[group_key]
                except KeyError:
                    self.context_menus[group_key] = menu = Menu(
                        self.context_menu,
                    )

            menu.add_radiobutton(
                label=item.context_lbl,
                command=functools.partial(self.sel_item_id, item.name),
                var=self.context_var,
                value=ind,
            )

            item.win = self.win
            utils.bind_leftclick(
                item.button,
                functools.partial(self.sel_item, item),
            )
            utils.bind_leftclick_double(
                item.button,
                self.save,
            )

        # Convert to a normal dictionary, after adding all items.
        self.grouped_items = dict(self.grouped_items)

        # Figure out the order for the groups - alphabetical.
        # Note - empty string should sort to the beginning!
        self.group_order[:] = sorted(self.grouped_items.keys())

        for index, (key, menu) in enumerate(
                sorted(self.context_menus.items(), key=itemgetter(0)),
                # We start with the ungrouped items, so increase the index
                # appropriately.
                start=len(self.grouped_items.get('', ()))):
            self.context_menu.add_cascade(
                menu=menu,
                label=self.group_names[key],
            )
            # Set a custom attribute to keep track of the menu's index.
            menu.index = index

        for group_key, text in self.group_names.items():
            self.group_widgets[group_key] = GroupHeader(
                self,
                text,
            )
            self.group_widgets[group_key].should_show = True

        self.flow_items(None)
        self.wid_canvas.bind("<Configure>", self.flow_items)

        self.pane_win.add(shim)
        self.pane_win.add(self.prop_frm)

        # Force a minimum size for the two parts
        self.pane_win.paneconfigure(shim, minsize=100, stretch='always')
        self.prop_frm.update_idletasks()  # Update reqwidth()
        self.pane_win.paneconfigure(
            self.prop_frm,
            minsize=200,
            stretch='never',
        )

        if attributes:
            attr_frame = ttk.Frame(self.prop_frm)
            attr_frame.grid(
                row=5,
                column=0,
                columnspan=3,
                sticky=EW,
            )

            self.attr = {}
            # Add in all the attribute labels
            for index, attr in enumerate(attributes):
                desc_label = ttk.Label(
                    attr_frame,
                    text=attr.desc,
                )
                self.attr[attr.id] = val_label = ttk.Label(
                    attr_frame,
                )
                val_label.default = attr.default
                val_label.type = attr.type
                if attr.type is AttrTypes.BOOL:
                    # It's a tick/cross label
                    val_label['image'] = (
                        ICON_CHECK
                        if attr.default else
                        ICON_CROSS,
                    )
                elif attr.type is AttrTypes.COLOR:
                    # A small colour swatch.
                    val_label.configure(
                        relief=RAISED,
                    )
                    # Show the color value when hovered.
                    add_tooltip(val_label)

                # Position in a 2-wide grid
                desc_label.grid(
                    row=index // 2,
                    column=(index % 2) * 2,
                    sticky=E,
                )
                val_label.grid(
                    row=index // 2,
                    column=(index % 2) * 2 + 1,
                    sticky=W,
                )
        else:
            self.attr = None
示例#56
0
文件: test_font.py 项目: za/cpython
 def test_nametofont(self):
     testfont = font.nametofont(fontname, root=self.root)
     self.assertIsInstance(testfont, font.Font)
     self.assertEqual(testfont.name, fontname)
示例#57
0
    def _create_pane(self):
        label_font = font.nametofont('TkHeadingFont').copy()
        ttk.Style().configure('TLabel', borderwidth=1, relief='solid')
        style = ttk.Style()
        style.configure('Title.TLabel', borderwidth=0, anchor=tk.CENTER)
        label = ttk.Label(self,
                          style='Title.TLabel',
                          padding=(5, 5, 5, 5),
                          textvariable=self._controller._title)
        label['font'] = label_font
        label.pack(side=tk.TOP, expand=tk.NO, fill=tk.X)
        main_pane = ttk.PanedWindow(self, orient=tk.VERTICAL)
        main_pane.pack(expand=tk.YES, fill=tk.BOTH)
        top_pane = ttk.PanedWindow(main_pane, orient=tk.HORIZONTAL)
        top_pane.pack(expand=tk.YES, fill=tk.BOTH)
        main_pane.add(top_pane)

        self._controller._sectionsView = SectionsView(self._controller,
                                                      top_pane)
        self._controller._sectionsView.pack(expand=tk.YES, fill=tk.BOTH)
        top_pane.add(self._controller._sectionsView, weight=1)

        main_container = tk.Frame(top_pane)
        main_container.pack(expand=tk.YES, fill=tk.BOTH)
        style = ttk.Style()
        style.configure('PropViewTitle.TLabel',
                        borderwidth=1,
                        relief=tk.RIDGE,
                        anchor=tk.CENTER)
        label = ttk.Label(main_container,
                          style='PropViewTitle.TLabel',
                          padding=(5, 5, 5, 5),
                          textvariable=self._controller._sectionView_title)
        label['font'] = label_font

        label.pack(side=tk.TOP, expand=tk.NO, fill=tk.X)
        container = tk.Frame(main_container)
        container.pack(side=tk.BOTTOM, expand=tk.YES, fill=tk.BOTH)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)
        self._controller._emptyView = EmptyView(container)
        self._controller._emptyView.grid(row=0, column=0, sticky='nsew')

        self._controller._textView = SectionTextView(self._controller,
                                                     container)
        self._controller._textView.grid(row=0, column=0, sticky='nsew')

        self._controller._propertiesView = SectionPropertiesView(
            self._controller, container)
        self._controller._propertiesView.grid(row=0, column=0, sticky='nsew')
        self._controller._emptyView.tkraise()
        top_pane.add(main_container, weight=1)

        self._controller._outputView = ThreadSafeOutputView(main_pane)
        self._controller._outputView.pack(expand=tk.YES, fill=tk.BOTH)
        main_pane.add(self._controller._outputView)

        # redirect output
        sys.stdout = self._controller._outputView
        sys.stderr = self._controller._outputView
        # reupdate logging after redirect
        preferences = Preferences()
        config = preferences.get_logging_config()
        if config is not None:
            set_logger_config(config)

        self.update_idletasks()
        self._controller._sectionsView.show_add_button(False)
        self._controller._sectionsView.show_remove_button(False)
        self._controller._sectionsView.show_defaults_button(False)
        self._controller._emptyView.set_toolbar_size(
            self._controller._sectionsView.get_toolbar_size())
示例#58
0
def Tree(fr,outVar):
    s = Style()
    s.theme_use('default')

    s.map('Treeview', foreground=fixed_map(s,'foreground'),
            background=fixed_map(s,'background'))

    test_length = font.Font(family="Times", size=12, weight="bold").measure('Test')
    fact = int(test_length / 30 * 20.45) # 30 is the length of Test in Idle

    s.configure('Treeview', rowheight= fact)

    s.configure('font.Treeview', font='TkDefaultFont')
    # determine Heading font based on TkDefaultFont
    s.configure('font.Treeview', font='TkDefaultFont')
    def_font = font.nametofont('TkDefaultFont')
    font_family = def_font.actual()['family']
    font_size = def_font.actual()['size'] + 1
    s.configure('font.Treeview.Heading', font=(font_family,font_size,'bold'))

    # function to enable selection
    def selectItem(evt):
        curItem = tree.focus()
        lvar.set(tree.item(curItem)['values'])
        outVar.set(tree.item(curItem)['values'])

    def sortBy(tree, col, descending):
        # When a column is clicked on sort tree contents .
        # grab values to sort
        data = [(tree.set(child, col), child) for child in tree.get_children('')]

        # reorder data
        data.sort(reverse=descending)
        for indx, item in enumerate(data):
            tree.move(item[1], '', indx)

        # switch the heading so that it will sort in the opposite direction
        tree.heading(col, command=lambda col=col: sortBy(tree, col, int(not descending)))

        # reconfigure tags after ordering
        list_of_items = tree.get_children('')
        for i in range(len(list_of_items)):
            tree.tag_configure(list_of_items[i], background=backg[i%2])

    # headings and data
    treeColumns = ['Colours', 'Hash', 'RGB', 'Extra long header']

    treeData = (('red', '#FF0000', (255,0,0)),
            ('yellow', '#FFFF00', (255,255,0)),
            ('blue', '#0000FF', (0,0,255)),
            ('green', '#00FF00', (0,255,0)),
            ('magenta', '#FF00FF', (255,0,255)),
            ('cyan', '#00FFFF', (0,255,255)),
            ('foo', 'bar', 'bong', 'ding a ling ping'))

    backg = ["white",'#f0f0ff']

    # create Treeview widget
    tree = Treeview(fr, column=treeColumns, show='headings',style='font.Treeview')
    tree.grid(column=0, row=0, sticky='nsew')
    tree.bind("<<TreeviewSelect>>", selectItem)

    vsb = Scrollbar(fr,orient="vertical", command=tree.yview)
    vsb.grid(column=1, row=0, sticky='ns')
    hsb = Scrollbar(fr,orient="horizontal", command=tree.xview)
    hsb.grid(column=0, row=1,  sticky='ew')

    tree.configure(xscrollcommand=hsb.set,yscrollcommand=vsb.set)
    fr.grid_columnconfigure(0, weight=1)
    fr.grid_rowconfigure(0, weight=1)

    # insert header, data and tag configuration
    for ix,col in enumerate(treeColumns):
        tree.heading(col, text=col.title(),
            command=lambda c=col: sortBy(tree, c, 0))
        #tree.column(col,stretch=True)
        #tree.column(col,width=font.nametofont('TkHeadingFont').measure(col.title()),
                #stretch=False)
        tree.column(col,width=font.Font(family=font_family,size=font_size, weight="bold").measure(col.title()) + 10,
                stretch=False)
        #print(tree.column(col))

    # insert data row by row, then measure each items' width
    for ix, item in enumerate(treeData):
        itemID = tree.insert('', 'end', values=item)
        tree.item(itemID, tags=itemID)
        tree.tag_configure(itemID, background=backg[ix%2])

        for indx, val in enumerate(item):
            #ilen = font.Font(family="Segoe UI", size=10, weight="normal").measure(val)
            ilen = font.nametofont('TkDefaultFont').measure(val)
            if tree.column(treeColumns[indx], width=None) < ilen +10:
                tree.column(treeColumns[indx], width=ilen + 10)
            # you should see the widths adjust
            #print('col',tree.column(treeColumns[indx]),ilen)

    # display selection
    lvar = StringVar()
    lbl = Label(fr, textvariable=lvar, text="Ready")
    lbl.grid(column=0, row=2, sticky='nsew')
import tkinter.ttk as ttk
import numpy as np

###############################################
from_val = 0   # from_
to_val = 100      # to
tick_val = 10   # tickinterval
res_val = 10    # resolution
dig_val = 0     # digits
bw_val = 1      # trough border width
slider_val = 32 # sliderlength
#################################################

root = tk.Tk()

def_font = font.nametofont('TkDefaultFont')
# using numpy arange instead of range so tick intervals less than 1 can be used
data = np.arange(from_val, (to_val+1 if tick_val >=1 else to_val+tick_val), tick_val) # tick_val
data = np.round(data,1)
range_vals = tuple(data)
lspace = def_font.metrics('linespace')
len_rvs = len(range_vals)
data_size = len_rvs * lspace

space_size = len_rvs * 3
sizes = data_size + space_size
len_val = (sizes if sizes % 50 == 0 else sizes + 50 - sizes % 50)

theme_sl = {'alt': 9, 'clam': 30, 'classic': 30, 'default': 30,
                    'lime': 9, 'winnative': 9}
示例#60
0
	def __init__(self,master):

		#variables
		self.outputDir = os.path.expanduser("~/Desktop");
		self.bindUploadFiles = '';
		self.extractUploadFile='';
		self.extractUploadFileName = StringVar();
		self.pageNumList = StringVar();
		self.numPages = StringVar();
		self.combine = BooleanVar();
		self.combine.set(False);
		self.getOperator=None;
		self.NameDirectoryDict = {};
		self.files=0;
		self.blankPageCount = 0;
		self.background = "gray90"

		self.master = master
		master.configure(background=self.background)
		master.title("PDF-Surgeon® [1.0.0v]")
		master.resizable(width=False, height=False);
		default_font = font.nametofont("TkDefaultFont")
		default_font.configure(size=12,family="Candara")
		
		#mainframe
		self.mainframe = ttk.Frame(master,relief=tk.RIDGE,width=500,height=500,style="main.TFrame");
		
		# label for frame-one
		self.labelone = ttk.Label(text="Bind Files")

		# label for frame-two
		self.labeltwo = ttk.Label(text="Extract Pages")

		#labelframe - one
		self.labelframeone = ttk.LabelFrame(self.mainframe,labelwidget=self.labelone)
		
		#copy right
		self.copyright = ttk.Label(self.mainframe,text="copyrightⓒ2018 min.naung",style="i8nc.TLabel")
		self.copyright.grid(row=1,column=2,pady=3)


		#labelframe for [uploadfiles,up,down,view,remove ]
		self.newframe = ttk.Frame(self.labelframeone);
		#labelframe for [up,down]
		self.updownframe = ttk.Frame(self.newframe);
		#labelframe for [view,remove]
		self.viewremoveframe = ttk.Frame(self.newframe);


		#upload files button
		self.uploadfilesbtn = ttk.Button(self.newframe,text="Upload Files",command=self.bindUpload,style="i12n.TButton")
		# up,down,remove button
		self.upbtn = ttk.Button(self.updownframe,text="↑", command=self.up,style="r9n.TButton")
		self.downbtn =ttk.Button(self.updownframe,text="↓", command=self.down, style="r9n.TButton")
		self.viewbtn = ttk.Button(self.viewremoveframe,text="⬜",command=self.view, style="r9n.TButton")
		self.removebtn = ttk.Button(self.viewremoveframe,text="X",command=self.remove, style="r9nc.TButton")
		self.blankbtn = ttk.Button(self.viewremoveframe,text="➕",command=self.addBlank,style="r9n.TButton")

		#files info list
		self.lbframe = ttk.Frame(self.labelframeone,relief=SUNKEN)
		self.uploadfileslist = tk.Listbox(self.lbframe,exportselection=False,height=6,width=35)		
		self.scrollbar= ttk.Scrollbar(self.lbframe,orient=VERTICAL,command=self.uploadfileslist.yview) 
		self.uploadfileslist["yscrollcommand"]=self.scrollbar.set;
		

		#bind confirm button
		self.bindokbtn = ttk.Button(self.labelframeone,text="Bind PDFs",command=self.bind,style="i12b.TButton");
		

		#events [double-click open]
		self.uploadfileslist.bind("<Double-Button-1>",self.doubleClickOpen);

		#labelframe - two
		self.labelframetwo = ttk.LabelFrame(self.mainframe,labelwidget=self.labeltwo)
		#upload file button
		self.uploadframe = ttk.Frame(self.labelframetwo)	
		self.l2uploadbtn = ttk.Button(self.uploadframe,text="Upload File",command=self.extractUpload,style="i12n.TButton")
		self.l2uploadlabel = ttk.Label(self.uploadframe,textvariable=self.extractUploadFileName)
		self.l2uploadpages = ttk.Label(self.uploadframe,textvariable=self.numPages);
		#numbers of page
		self.numlbframe = ttk.Frame(self.labelframetwo)
		self.pagenumlb = ttk.Label(self.numlbframe,text="Page Number:")
		self.pagenumbers = ttk.Entry(self.numlbframe,width=15,textvariable=self.pageNumList,style="i10n.TEntry")
		self.pagenumbers.insert(0,"eg: 1,3-5,9,11-17");
		self.pagenumbers.bind("<FocusIn>",self.hideText)
		self.combinepage = ttk.Checkbutton(self.labelframetwo,text="Combine",variable=self.combine,
			onvalue=True,offvalue=False)		
		#extract confirm button
		self.l2extractok = ttk.Button(self.labelframetwo,text="Extract PDFs",command=self.extract,style="i12b.TButton");

		#tooltips
		tooltip(self.uploadfilesbtn,"Upload PDFs to merge");
		tooltip(self.upbtn,"Up");
		tooltip(self.downbtn,"Down");
		tooltip(self.viewbtn,"Open");
		tooltip(self.removebtn,"Remove");
		tooltip(self.blankbtn,"add blank page")
		tooltip(self.bindokbtn,"Files merge to single PDF")
		tooltip(self.l2uploadbtn,"Upload PDF to extract");
		tooltip(self.l2extractok,"Extract files from uploaded PDF")


		#grids
		self.mainframe.grid(row=0,column=0)

		#labelframeone -grids
		self.labelframeone.grid(row=0,column=0,padx=10,pady=10,sticky=(N))
		self.newframe.grid(row=0,column=0,pady=5)
		self.updownframe.grid(row=0,column=0,sticky=(W,N,S),pady=5)
		self.viewremoveframe.grid(row=0,column=2,sticky=(E,N,S),pady=5)
		self.uploadfilesbtn.grid(row=0,column=1,ipadx=8,padx=40)
		self.upbtn.grid(row=0,column=0,sticky=(N,E))
		self.downbtn.grid(row=0,column=1,sticky=(N,W,E))
		self.viewbtn.grid(row=0,column=2,sticky=(N,W,E))	
		self.removebtn.grid(row=0,column=3,sticky=(N,W,E))
		self.blankbtn.grid(row=0,column=4,sticky=(N,E))

		self.lbframe.grid(row=1,column=0,padx=10)
		self.uploadfileslist.grid(row=0,column=0,sticky=(N,W,E,S))
		self.scrollbar.grid(row=0,column=1,sticky=(N,S))
		self.bindokbtn.grid(row=3,column=0,pady=6,ipadx=10);

		#labelframetwo -grids
		self.labelframetwo.grid(row=0,column=2,padx=10,pady=10,sticky=(N))
		self.uploadframe.grid(row=0,column=0,padx=35,pady=7)
		self.l2uploadbtn.grid(row=0,column=0,ipadx=10)
		self.l2uploadlabel.grid(row=1,column=0,sticky=(N))
		self.l2uploadpages.grid(row=2,column=0,sticky=(N))
		self.numlbframe.grid(row=2,column=0,sticky=(N))
		self.pagenumlb.grid(row=0,column=0)
		self.pagenumbers.grid(row=1,column=0)
		self.combinepage.grid(row=4,column=0,pady=3)
		self.l2extractok.grid(row=5,column=0,ipadx=10,pady=8);

		# styles
		self.style = ttk.Style();
		self.style.configure("main.TFrame",background=self.background)
		self.style.configure("label.TLabel",background="AntiqueWhite1")
		self.style.configure("lframe.TLabelframe.Label",background="AntiqueWhite1")
		self.style.configure("r9n.TButton",font=("Candara",9,"normal","bold"),height=4,width=3)
		self.style.configure("r9nc.TButton",font=("Candara",9,"normal","bold"),height=4,width=3,foreground="red")
		self.style.configure("i8nc.TLabel",font=("Candara",9,"italic","bold"),foreground="gray33",background=self.background)
		self.style.configure("i12b.TButton",font = ("Candara",12,"italic","bold"))
		self.style.configure("i12n.TButton",font = ("Candara",12,"italic","normal"),relief=RAISED)
		self.style.configure("i10n.TEntry",font = ("Candara",10,"italic","normal"))
		self.style.configure("i12.TFrame",font=("Candara",12))

		# display window
		master.mainloop()