Exemplo n.º 1
10
class Scratchpad:

    def __init__(self):
        self.window = Tk()
        self.window.title("Onager Scratchpad")
        self.create_frame()
        self.create_editing_window()
        self.window.bind('<F7>', self.save_file)
        self.window.bind('<F5>', self.open_file)

    def create_frame(self):
        frame_style = Style()
        frame_style.theme_use('alt')
        frame_style.configure("TFrame",
                              relief='raised')
        self.frame = Frame(self.window, style="frame_style.TFrame")
        self.frame.rowconfigure(1)
        self.frame.columnconfigure(1)
        self.frame.grid(row=0, column=0)

    def create_editing_window(self):
        self.editing_window = ScrolledText(self.frame)
        self.editing_window.configure(fg='gold',
                                      bg='blue',
                                      font='serif 12',
                                      padx='15',
                                      pady='15',
                                      wrap='word',
                                      borderwidth='10',
                                      relief='sunken',
                                      tabs='48',
                                      insertbackground='cyan')
        self.editing_window.grid(row=0, column=0)

    def save_file(self, event=None):
        name = asksaveasfilename()
        outfile = open(name, 'w')
        contents = self.editing_window.get(0.0, END)
        outfile.write(contents)
        outfile.close()

    def open_file(self, event=None):
        name = askopenfilename()
        infile = open(name, 'r')
        contents = infile.read()
        self.editing_window.insert(INSERT, contents)
        infile.close()
Exemplo n.º 2
0
class TwoCells:
    ANYTHING = 0
    INTEGERS = 1
    NON_NEGATIVE_INTEGERS = 2
    STATIC = 3

    def __init__(self, parent, validation_type=ANYTHING, **kwargs):
        self.validation_type = validation_type
        self.frame = Frame(parent)
        self.frame.grid(columnspan=2, sticky=E + N + S + W, **kwargs)
        self.frame.columnconfigure(0, weight=1)
        self.frame.rowconfigure(0, weight=1)
        self.validate_command = (self.frame.register(self._on_validate), "%P")

    def _on_validate(self, new_value):
        try:
            if self.validation_type == self.INTEGERS:
                if new_value not in ["", "-"]:
                    int(new_value)
            elif self.validation_type == self.NON_NEGATIVE_INTEGERS:
                if new_value != "":
                    value = int(new_value)
                    if value < 0:
                        return False
            elif self.validation_type == self.STATIC:
                return False
            return True
        except Exception:
            return False
    def create_widgets(self):
        ''' Creates appropriate widgets on this frame.
        '''
        self.columnconfigure(0, weight=1)
        self.rowconfigure(3, weight=1)
        frame_for_save_btn = Frame(self)
        frame_for_save_btn.columnconfigure(1, weight=1)
        self.status_lbl = Label(frame_for_save_btn, text='')
        self.status_lbl.grid(row=0, column=1, sticky=N+W)
        save_solution_btn = Button(frame_for_save_btn, text='Save solution',
                                   command=self.on_save_solution)
        save_solution_btn.grid(row=1, column=0, sticky=W+N, padx=5, pady=5)
        self.progress_bar = Progressbar(frame_for_save_btn,
                                        mode='determinate', maximum=100)
        self.progress_bar.grid(row=1, column=1, sticky=W+E, padx=10, pady=5)

        frame_for_save_btn.grid(sticky=W+N+E+S, padx=5, pady=5)

        frame_for_btns = Frame(self)
        self._create_file_format_btn('*.xlsx', 1, frame_for_btns, 0)
        self._create_file_format_btn('*.xls', 2, frame_for_btns, 1)
        self._create_file_format_btn('*.csv', 3, frame_for_btns, 2)
        self.solution_format_var.set(1)

        frame_for_btns.grid(row=1, column=0, sticky=W+N+E+S, padx=5, pady=5)
        self.data_from_file_lbl = Label(self, text=TEXT_FOR_FILE_LBL, anchor=W,
                                        justify=LEFT,
                                        wraplength=MAX_FILE_PARAMS_LBL_LENGTH)
        self.data_from_file_lbl.grid(row=2, column=0, padx=5, pady=5,
                                     sticky=W+N)

        self.solution_tab = SolutionFrameWithText(self)
        self.solution_tab.grid(row=3, column=0, sticky=W+E+S+N, padx=5, pady=5)
Exemplo n.º 4
0
def create_input_form_fields(body_frame: ttk.Frame, names: Sequence[str],
                             entry_fields: Mapping[str, EntryField]):
    """Create the labels and fields for an entry form.
    
    Args:
        body_frame: The outer frame for the labels and fields.
        names: A sequence of names of the fields.
        entry_fields: A mapping of the field names to an instance of EntryField.
    """

    # Create a column for the labels.
    body_frame.columnconfigure(0, weight=1, minsize=30)
    # Create a column for the fields.
    body_frame.columnconfigure(1, weight=1)

    for row_ix, internal_name in enumerate(names):
        entry_field = entry_fields[internal_name]
        label = ttk.Label(body_frame, text=entry_field.label_text)
        label.grid(column=0, row=row_ix, sticky='e', padx=5)
        entry = ttk.Entry(body_frame,
                          textvariable=entry_field.textvariable,
                          width=36)
        entry.grid(column=1, row=row_ix)
        entry_field.widget = entry
        entry_field.textvariable.set(entry_field.original_value)
Exemplo n.º 5
0
    def _createStammdatenTab(self, stammdatenPage:ttk.Frame):
        stv = StammdatenView(stammdatenPage)
        stv.grid(column=0, row=0, sticky='nwe', padx=50, pady=50)
        self._stammdatenView = stv

        stammdatenPage.rowconfigure(0, weight=1)
        stammdatenPage.columnconfigure(0, weight=1)
Exemplo n.º 6
0
 def __init__(self, parent, title, imageFile, body):
     super(DialogAbout, self).__init__(parent)
     self.parent = parent
     parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
     dialogX = int(parentGeometry.group(3))
     dialogY = int(parentGeometry.group(4))
     self.transient(self.parent)
     self.title(title)
     
     frame = Frame(self)
     image = PhotoImage(file=imageFile)
     aboutImage = Label(frame, image=image)
     aboutBody = Label(frame, text=body, wraplength=500)
     okButton = Button(frame, text=_("OK"), command=self.ok)
     okButton.focus_set()
     aboutImage.grid(row=0, column=0, sticky=NW, pady=20, padx=16)
     aboutBody.grid(row=0, column=1, columnspan=2, sticky=EW, pady=3, padx=0)
     okButton.grid(row=1, column=2, sticky=EW, pady=3)
     
     frame.grid(row=0, column=0, sticky=(N,S,E,W))
     frame.columnconfigure(1, weight=1)
     window = self.winfo_toplevel()
     window.columnconfigure(0, weight=1)
     self.geometry("+{0}+{1}".format(dialogX+200,dialogY+200))
     
     self.bind("<Alt-u>", lambda *ignore: okButton.focus_set())
     self.bind("<Return>", self.ok)
     self.bind("<Escape>", self.close)
     
     self.protocol("WM_DELETE_WINDOW", self.close)
     self.grab_set()
     self.wait_window(self)
Exemplo n.º 7
0
    def _createWohnungDetailsTab(self, wohnungDetailsPage:ttk.Frame):
        wghview = WohnungDetailsView(wohnungDetailsPage)
        wghview.grid(column=0, row=0, sticky='nwe', padx=10, pady=10)
        self._wohnungDetailsView = wghview

        wohnungDetailsPage.rowconfigure(0, weight=1)
        wohnungDetailsPage.columnconfigure(0, weight=1)
Exemplo n.º 8
0
    def _create_widgets(self):
        main_frame = Frame(self)
        self.textbox = Text(main_frame, relief=FLAT, undo=False, takefocus=0,
                            bg=OSCONST.TEXT_BG, height=4)
        self.hyperlink = HyperlinkManager(self.textbox)
        info_text = ("Biscuit created by Matt Sanderson for Macquarie "
                     "University.\n"
                     "To find out more head to the ")
        link_text = "Biscuit GitHub Repository"
        self.textbox.insert(END, info_text)
        self.textbox.insert(END, link_text,
                            self.hyperlink.add(self._open_link))
        self.textbox.grid(column=0, row=0, columnspan=3)
        self.textbox.config(state=DISABLED)
        Button(main_frame, text="Close",
               command=self._exit).grid(column=0, row=1, sticky='w')
        update_btn = Button(main_frame, text="Check for Updates",
                            command=self._check_for_updates)
        update_btn.grid(column=1, row=1, sticky='w', padx=2)
        version_lbl = Label(
            main_frame, text="Current version: {0}".format(OSCONST.VERSION))
        version_lbl.grid(column=2, row=1, sticky='w', padx=2)

        main_frame.columnconfigure(0, weight=1)
        main_frame.columnconfigure(1, weight=0)
        main_frame.columnconfigure(2, weight=0)

        main_frame.grid(sticky='nsew')

        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)
Exemplo n.º 9
0
    def creation2(self):
        # frame = self.gui_frame

        # добавляем новый фрейм для группирования
        frame = Frame(
            master=self.base_frame, # указываем родителем базовый фрейм
            relief=RAISED, # стиль рамки FLAT SUNKEN RAISED GROOVE RIDGE
            borderwidth=2 # ширина рамки в пикселях
        )
        frame.pack(fill=BOTH)
        print('111', self.base_frame.winfo_height())
        print('222', frame.winfo_screenmmheight())
        print('333', frame.winfo_height())
        # print(dir(self.parent))

        frame.columnconfigure(0)  # формируем столбцы
        frame.columnconfigure(1)
        frame.rowconfigure(0, minsize=30)  # и строки
        # wdt = self.frame.winfo_screenmmheight() - self.options['height']
        frame.rowconfigure(1, minsize=frame.winfo_screenmmheight())
        frame.rowconfigure(2, minsize=30)

        # for i in dir(frame):
        #     if i.startswith('winfo_'): print(i)

        lbl_title = Label(master=frame, text="Данные")  # текст над выводом
        lbl_title.grid(row=2, column=1)
Exemplo n.º 10
0
    def creation1(self):
        frame = Frame(
            master=self.base_frame,  # указываем родителем базовый фрейм
            relief=RAISED,  # стиль рамки FLAT SUNKEN RAISED GROOVE RIDGE
            borderwidth=2  # ширина рамки в пикселях
        )
        frame.pack()
        frame.columnconfigure(1, weight=1) # формируем столбцы
        frame.columnconfigure(3, pad=7)
        frame.rowconfigure(3, weight=1) # и строки
        frame.rowconfigure(5, pad=7)

        lbl = Label(frame, text="Данные")  # текст над выводом
        lbl.grid(sticky=W, pady=4, padx=5)

        # для вывода создаём scrolled поле вместо обычного text
        area = scrolledtext.ScrolledText(frame)
        self.area = area  # передаём в класс созданный объект
        area.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E + W + S + N)

        abtn = Button(frame, text="Тест", command=self.load_image)  # тестируем загрузку картинки
        abtn.grid(row=1, column=3)

        # cbtn = Button(frame, text="Закрыть", command=self.quit)
        # cbtn.grid(row=2, column=3, pady=4)

        hbtn = Button(frame, text="Запрос", command=self.btn_request)
        hbtn.grid(row=5, column=0, padx=5)

        obtn = Button(frame, text="Готово", command=self.btn_quit)
        obtn.grid(row=5, column=3)
Exemplo n.º 11
0
 def __init__(self, parent, title, imageFile, body):
     super(DialogAbout, self).__init__(parent)
     self.parent = parent
     parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
     dialogX = int(parentGeometry.group(3))
     dialogY = int(parentGeometry.group(4))
     self.transient(self.parent)
     self.title(title)
     
     frame = Frame(self)
     image = PhotoImage(file=imageFile)
     aboutImage = Label(frame, image=image)
     aboutBody = Label(frame, text=body, wraplength=500)
     okButton = Button(frame, text=_("OK"), command=self.ok)
     okButton.focus_set()
     aboutImage.grid(row=0, column=0, sticky=NW, pady=20, padx=16)
     aboutBody.grid(row=0, column=1, columnspan=2, sticky=EW, pady=3, padx=0)
     okButton.grid(row=1, column=2, sticky=EW, pady=3)
     
     frame.grid(row=0, column=0, sticky=(N,S,E,W))
     frame.columnconfigure(1, weight=1)
     window = self.winfo_toplevel()
     window.columnconfigure(0, weight=1)
     self.geometry("+{0}+{1}".format(dialogX+200,dialogY+200))
     
     self.bind("<Alt-u>", lambda *ignore: okButton.focus_set())
     self.bind("<Return>", self.ok)
     self.bind("<Escape>", self.close)
     
     self.protocol("WM_DELETE_WINDOW", self.close)
     self.grab_set()
     self.wait_window(self)
Exemplo n.º 12
0
def mainWindow():
    # Глобализируем переменные --------------------------------------------
    global loginwindow
    global mail
    global password
    # Основное ------------------------------------------------------------
    loginwindow = Tk()
    loginwindow.title('Вход')
    loginwindow.geometry('296x160') #Измените размеры, если у вас НЕ Windows
    loginwindow.resizable(height = False, width = False)
    # Переменные ----------------------------------------------------------
    mail = StringVar()
    password = StringVar()
    # Геометрия окна ------------------------------------------------------
    mainframe = Frame(loginwindow, padding = '3 3 12 12')
    mainframe.grid(column = 0, row = 0, sticky = (N, W, E, S))
    mainframe.columnconfigure(0, weight = 1)
    mainframe.rowconfigure(0, weight = 1)
    # Текст ---------------------------------------------------------------
    ttk.Label(mainframe, text = 'Почта:').grid(column = 0, row = 0, sticky = W)
    ttk.Label(mainframe, text = 'Пароль:').grid(column = 0, row = 1, sticky = W)
    ttk.Label(mainframe, text = '').grid(column = 0, row = 2, sticky = W)
    ttk.Label(mainframe, text = '').grid(column = 0, row = 3, sticky = E)
    # Текстовые формы -----------------------------------------------------
    mail_form = ttk.Entry(mainframe, width = 30, textvariable = mail).grid(column = 1, row = 0, sticky = (W, E))
    password_form = ttk.Entry(mainframe, width = 30, show = '*', textvariable = password).grid(column = 1, row = 1, sticky = (W, E))
    # Кнопки --------------------------------------------------------------
    login_button = ttk.Button(mainframe, text = 'Войти', command = secondWindow).grid(column = 1,row = 4, sticky = E)
    website = ttk.Button(mainframe, text = 'Сайт проекта', command = open_site).grid(column = 0,row = 4, sticky = W)
    # Отрисовка -----------------------------------------------------------
    for child in mainframe.winfo_children():
        child.grid_configure(padx = 5, pady = 5)
    loginwindow.mainloop()
Exemplo n.º 13
0
class FrontEnd(Frame):
    def __init__(self, master, version):
        Frame.__init__(self, master)
        master.title(version[:-5])
        # MAKE IT LOOK GOOD
        style = Style()
        style.configure("atitle.TLabel", font="tkDefaultFont 12 bold italic")

        # CREATE AND SET VARIABLES
        self.version = version
        self.description = None
        self.logo = None
        self.status_lbl = StringVar()  # TO HOLD STATUS VARIABLE IN STATUSBAR

        # CREATE ROOT MENUBAR
        menubar = Menu(self.master)
        self.master["menu"] = menubar
        self.master.option_add("*tearOff", False)
        # CREATE FILE MENU
        self.menu_file = Menu(menubar, name="file")
        self.menu_file.add_separator()
        self.menu_file.add_command(label="Exit", accelerator="Alt-F4", command=self.master.destroy)
        menubar.add_cascade(menu=self.menu_file, label="File", underline=0)
        # CREATE HELP MENU
        menu_help = Menu(menubar, name="help")
        menu_help.add_command(label="About", command=self.show_about)
        menubar.add_cascade(menu=menu_help, label="Help", underline=0)

        # CREATE BUTTON BAR
        self.button_bar = Frame(self.master, relief="groove", padding="0 1 0 2")
        self.button_bar.grid(sticky="ew")

        # SETUP PRIMARY FRAME FOR WIDGETS
        self.frame = Frame(self.master, padding="25")
        self.frame.grid(sticky="nsew")

        # CREATE STATUS BAR
        Separator(self.master).grid(row=8, sticky="ew")
        self.status_bar = Frame(self.master, padding="8 0 0 1")
        self.status_bar.grid(row=9, sticky="ews")
        Label(self.status_bar, textvariable=self.status_lbl).grid(row=0, column=0, padx="0 7")
        Label(self.status_bar, text=self.version[-5:]).grid(row=0, column=8)
        Sizegrip(self.status_bar).grid(row=0, column=9, sticky="e")

        # CONFIGURE AUTO-RESIZING
        self.master.columnconfigure(0, weight=1)
        self.master.rowconfigure(1, weight=1)
        self.frame.columnconfigure(0, weight=1)
        # self.frame.rowconfigure(0, weight=1)
        self.status_bar.columnconfigure(1, weight=1)

    def show_about(self):
        about = About(self.master, "About {}".format(self.version[:-5]), self.logo)
        Label(about.frame, text=self.version, style="atitle.TLabel").grid(sticky="w")
        Label(about.frame, text="Developer:  Joel W. Dafoe").grid(pady="6", sticky="w")
        link = Link(about.frame, text="http://cyberdatx.com", foreground="blue", cursor="hand2")
        link.grid(sticky="w")
        link.bind("<Button-1>", lambda e: webbrowser.open("http://cyberdatx.com"))
        Label(about.frame, text=self.description, wraplength=292).grid(columnspan=2, pady=6, sticky=W)
Exemplo n.º 14
0
    def __init__(self, mainWin, options):
        self.mainWin = mainWin
        parent = mainWin.parent
        super(DialogNewFactItemOptions, self).__init__(parent)
        self.parent = parent
        self.options = options
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False

        self.transient(self.parent)
        self.title(_("New Fact Item Options"))
        
        frame = Frame(self)

        label(frame, 1, 1, "Entity scheme:")
        self.cellEntityIdentScheme = gridCell(frame, 2, 1, getattr(options,"entityIdentScheme",""), width=50)
        ToolTip(self.cellEntityIdentScheme, text=_("Enter the scheme for the context entity identifier"), wraplength=240)
        label(frame, 1, 2, "Entity identifier:")
        self.cellEntityIdentValue = gridCell(frame, 2, 2, getattr(options,"entityIdentValue",""))
        ToolTip(self.cellEntityIdentValue, text=_("Enter the entity identifier value (e.g., stock ticker)"), wraplength=240)
        label(frame, 1, 3, "Start date:")
        startDate = getattr(options,"startDate",None)
        self.cellStartDate = gridCell(frame, 2, 3, XmlUtil.dateunionValue(startDate) if startDate else "")
        ToolTip(self.cellStartDate, text=_("Enter the start date for the report period (e.g., 2010-01-01)"), wraplength=240)
        label(frame, 1, 4, "End date:")
        endDate = getattr(options,"endDate",None)
        self.cellEndDate = gridCell(frame, 2, 4, XmlUtil.dateunionValue(endDate, subtractOneDay=True) if endDate else "")
        ToolTip(self.cellEndDate, text=_("Enter the end date for the report period (e.g., 2010-12-31)"), wraplength=240)
        label(frame, 1, 5, "Monetary unit:")
        self.cellMonetaryUnit = gridCombobox(frame, 2, 5, getattr(options,"monetaryUnit",""), values=monetaryUnits)
        ToolTip(self.cellMonetaryUnit, text=_("Select a monetary unit (e.g., EUR)"), wraplength=240)
        label(frame, 1, 6, "Monetary decimals:")
        self.cellMonetaryDecimals = gridCell(frame, 2, 6, getattr(options,"monetaryDecimals","2"))
        ToolTip(self.cellMonetaryDecimals, text=_("Enter decimals for monetary items"), wraplength=240)
        label(frame, 1, 7, "Non-monetary decimals:")
        self.cellNonMonetaryDecimals = gridCell(frame, 2, 7, getattr(options,"nonMonetaryDecimals","0"))
        ToolTip(self.cellNonMonetaryDecimals, text=_("Enter decimals for non-monetary items (e.g., stock shares)"), wraplength=240)

        cancelButton = Button(frame, text=_("Cancel"), width=8, command=self.close)
        ToolTip(cancelButton, text=_("Cancel operation, discarding changes and entries"))
        okButton = Button(frame, text=_("OK"), width=8, command=self.ok)
        ToolTip(okButton, text=_("Accept the options as entered above"))
        cancelButton.grid(row=8, column=1, columnspan=3, sticky=E, pady=3, padx=3)
        okButton.grid(row=8, column=1, columnspan=3, sticky=E, pady=3, padx=86)
        
        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(2, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        
        #self.bind("<Return>", self.ok)
        #self.bind("<Escape>", self.close)
        
        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
Exemplo n.º 15
0
Arquivo: ui.py Projeto: hayj/Annotator
 def initUI(self):
     self.master.title("Annotator")
     # self.grid(row=0, column=0, sticky='news')
     # self.rowconfigure(0, weight=1)
     # self.columnconfigure(0, weight=1)
     self.pack(fill=BOTH, expand=True)
     self.columnconfigure(0, weight=1)
     self.columnconfigure(11, pad=10)
     for i in range(10):
         self.rowconfigure(i, weight=1)
     # for i in range(20):
     # 	self.columnconfigure(i, weight=1)
     # Title:
     row = 0
     titleMessage = Message(self,
                            text="Annotator",
                            **self.headMessagesOption)
     titleMessage.grid(row=row, column=11, sticky='ewn')
     row += 1
     # Description:
     w1 = Message(self,
                  text=self.toolDescription,
                  width=200,
                  font='Arial 8')
     w1.grid(sticky="n", row=row, column=11, pady=4)
     row += 1
     # Task description:
     if self.taskDescription is not None:
         titleMessage = Message(self,
                                text="Task description",
                                **self.headMessagesOption)
         titleMessage.grid(row=row, column=11, sticky='ewn')
         row += 1
         w1 = Message(self,
                      text=self.taskDescription,
                      width=200,
                      font='Arial 8')
         w1.grid(sticky="n", row=row, column=11, pady=4)
         row += 1
     # Labels:
     self.labelFrameRow = row
     row += 1
     # Control head:
     browsingMessage = Message(self,
                               text="Browsing",
                               **self.headMessagesOption)
     browsingMessage.grid(row=row, column=11, sticky='ewn')
     row += 1
     # We make buttons:
     subFrame = Frame(self)
     subFrame.columnconfigure(0, weight=1)
     subFrame.columnconfigure(1, weight=1)
     subFrame.rowconfigure(0, weight=1)
     subFrame.grid(row=row, column=11, sticky="new")
     previousButton = Button(subFrame, text="<<", command=self.left)
     previousButton.grid(row=0, column=0, sticky="new")
     nextButton = Button(subFrame, text=">>", command=self.right)
     nextButton.grid(row=0, column=1, sticky="new")
     row += 1
Exemplo n.º 16
0
    def _createMonatlicheTab(self, mietePage:ttk.Frame):
        #Miete-Tabelle
        et = GenericEditableTable(mietePage)
        et.grid(column=0, row=0, sticky='nswe')
        self._monatlicheTableView = et

        mietePage.rowconfigure(0, weight=1)
        mietePage.columnconfigure(0, weight=1)
Exemplo n.º 17
0
    def _createRechnungenTab(self, rechnungPage:ttk.Frame):
        #Rechnung-Tabelle
        et = GenericEditableTable(rechnungPage)
        et.grid(column=0, row=0, sticky='nswe')
        self._rechnungTableView = et

        rechnungPage.rowconfigure(0, weight=1)
        rechnungPage.columnconfigure(0, weight=1)
Exemplo n.º 18
0
Arquivo: dialog.py Projeto: gokai/tim
class ListDialog(object):
    def __init__ (self, master, items, message, accept_func):
        self.accept_func = accept_func

        self.top = Toplevel(master)
        self.top.transient(master)
        self.top.rowconfigure(0, weight=1)
        self.top.rowconfigure(1, weight=3)
        self.top.rowconfigure(2, weight=0)
        self.top.columnconfigure(0, weight=1)
        self.top.columnconfigure(1, weight=1)
        self.top.resizable(width=True, height=True)

        self.frame = Frame(self.top)
        self.frame.rowconfigure(0, weight=1)
        self.frame.rowconfigure(1, weight=0)
        self.frame.columnconfigure(0, weight=1)
        self.frame.columnconfigure(1, weight=0)
        self.frame.grid(row=0, column=0, sticky=(N, S, W, E), columnspan=2)
        self.canvas = Canvas(self.frame)
        self.canvas.create_text(0, 0, text=message, anchor=NW)
        self.canvas.grid(row=0, column=0, sticky=(N, W, S, E))

        self.vscroll = Scrollbar(self.frame, command=self.canvas.yview)
        self.vscroll.grid(row=0, column=1, sticky=(N, S))
        self.canvas['yscrollcommand'] = self.vscroll.set

        self.hscroll = Scrollbar(self.frame, command=self.canvas.xview, orient=HORIZONTAL)
        self.hscroll.grid(row=1, column=0, sticky=(W, E), columnspan=2)
        self.canvas['xscrollcommand'] = self.hscroll.set

        self.canvas['scrollregion'] = self.canvas.bbox('all')
        self.canvas.bind('<Button-4>', self.scroll)
        self.canvas.bind('<Button-5>', self.scroll)
        self.canvas.bind('<MouseWheel>', self.scroll)

        self.view = NameView(self.top, sorted(items))
        self.view.widget.grid(row=1, column=0, columnspan=2, sticky=(N, W, E, S))

        self.delbutton = Button(self.top, text='Ok', command=self.accept )
        self.cancelbutton = Button(self.top, text='Cancel', command=self.cancel)
        self.delbutton.grid(row=2, column=0)
        self.cancelbutton.grid(row=2, column=1)
        self.view.widget.focus_set()

    def accept(self):
        self.accept_func(self.view.selection())
        self.top.destroy()

    def cancel(self):
        self.result = None
        self.top.destroy()

    def scroll(self, event):
        if event.num == 4 or event.delta > 0:
            self.canvas.yview(SCROLL, -1, UNITS)
        elif event.num == 5 or event.delta < 0:
            self.canvas.yview(SCROLL, 1, UNITS)
Exemplo n.º 19
0
    def init(self, root):
        padded = {'padding': 5}
        sticky = {'sticky': NSEW}

        # Configure grid
        frame = Frame(root, **padded)  # type: ignore
        frame.rowconfigure(0, weight=1)
        frame.rowconfigure(1, weight=1)
        frame.columnconfigure(0, weight=1)

        def frame_inputs(root):
            frame = Frame(root, **padded)  # type: ignore

            # Configure grid
            frame.rowconfigure(0, weight=1)
            frame.rowconfigure(1, weight=1)
            frame.columnconfigure(0, weight=1)
            frame.columnconfigure(1, weight=1)
            frame.columnconfigure(2, weight=1)

            # Place widgets
            entry = Entry(frame, width=7, textvariable=self.feet)
            entry.grid(column=1, row=0)
            entry.focus()
            label = Label(frame, text="feet")
            label.grid(column=2, row=0)
            label = Label(frame, text="is equivalent to")
            label.grid(column=0, row=1)
            label = Label(frame, text="meters")
            label.grid(column=2, row=1)
            label = Label(frame, textvariable=self.meters)
            label.grid(column=1, row=1)

            return frame

        def frame_commands(root):
            frame = Frame(root, **padded)  # type: ignore

            # Configure grid
            frame.rowconfigure(0, weight=1)
            frame.columnconfigure(0, weight=1)

            # Place widgets
            button = Button(frame, text="Calculate", command=self.calculate)
            button.grid(column=0, row=0)
            self.root.bind('<Return>', self.calculate)

            return frame

        def separator(root):
            return Separator(root)

        # Place widgets
        frame_inputs(frame).grid(row=0, **sticky)
        separator(frame).grid(row=1, padx=10, pady=5, **sticky)
        frame_commands(frame).grid(row=2, **sticky)

        return frame
Exemplo n.º 20
0
class App(Tk):
    """The application window."""

    def __init__(self):
        super().__init__()
        self.title('Smart RFID')
        self.container = Frame(self)
        self.container.grid(column=0, row=0, sticky=(N, W, E, S))
        self.container.columnconfigure(0, weight=1)
        self.container.rowconfigure(0, weight=1)

        self.frames = {}
        # Instantiate the frames.
        for frame in (StartPage, MoveMode, AddPalletsMode, DeleteTagsMode,
                      AddPlacesMode):
            frame_instance = frame(self.container, self)
            frame_instance.grid(column=0, row=0, sticky=(N, W, E, S))
            self.frames[frame] = frame_instance
            self.add_padding(frame_instance)
        self.container.pack()
        self.show_frame(StartPage)

        self.protocol('WM_DELETE_WINDOW', self.exit_handler)

    def exit_handler(self):
        """Clean shutdown of the frames."""
        for frame in self.frames.values():
            try:
                frame.stop()
            except AttributeError:
                # The frame doesn't have a stop method
                pass
        self.quit()

    def show_frame(self, frame_class):
        """Switch the currently shown frame.

        Args:
            frame_class: The class of the frame that should be shown in the
                application.
        """
        frame = self.frames[frame_class]
        frame.tkraise()
        try:
            frame.enter()
        except AttributeError:
            # If the frame doesn't have an enter method
            pass

    @staticmethod
    def add_padding(frame):
        """Add padding to the widgets inside a frame.

        Args:
            frame: An instance of a Frame.
        """
        for child in frame.winfo_children():
            child.grid_configure(padx=5, pady=5)
Exemplo n.º 21
0
Arquivo: ui.py Projeto: hayj/Annotator
 def initTextFrame(self, texts):
     # We init the frame:
     if self.textFrame is not None:
         self.textFrame.destroy()
     self.textFrame = Frame(self)
     self.textFrame.grid(row=0,
                         column=0,
                         columnspan=10,
                         rowspan=10,
                         padx=5,
                         pady=0,
                         sticky="news")
     self.textFrame.rowconfigure(0, weight=0)
     self.textFrame.rowconfigure(1, weight=1)
     # For each text:
     if not isinstance(texts, list):
         texts = [texts]
     nbColumns = len(texts)
     for i in range(nbColumns):
         self.textFrame.columnconfigure(i, weight=1)
         current = texts[i]
         try:
             # We add the head message:
             if dictContains(current, "title"):
                 headMessage = Message(self.textFrame,
                                       text=tkStripExtra(current["title"]),
                                       **self.headMessagesOption)
                 headMessage.grid(row=0,
                                  column=i,
                                  sticky='nwe',
                                  padx=2,
                                  pady=0)
             # We create the area for the text:
             textAreaFrame = Frame(self.textFrame)
             textAreaFrame.columnconfigure(0, weight=1)
             textAreaFrame.rowconfigure(0, weight=1)
             textAreaRow = 1
             textAreaRowspan = 1
             if not dictContains(current, "title"):
                 textAreaRow = 0
                 textAreaRowspan = 2
             textAreaFrame.grid(row=textAreaRow,
                                rowspan=textAreaRowspan,
                                column=i,
                                sticky="news",
                                padx=0)
             # We create the Text widget in:
             textWidget = Text(textAreaFrame)
             textWidget.grid(row=0, column=0, sticky="news")
             textWidget.insert(INSERT, tkStripExtra(current["text"]))
             textWidget.config(state=DISABLED)
             # We make the scroll bar:
             scrollBar = Scrollbar(textAreaFrame, command=textWidget.yview)
             scrollBar.grid(row=0, column=1, sticky="nse")
             textWidget['yscrollcommand'] = scrollBar.set
         except Exception as e:
             logException(e, self)
Exemplo n.º 22
0
    def __init__(self, master):
        Toplevel.__init__(self, master)
        self.protocol("WM_DELETE_WINDOW", self.quitter)
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=1)
        self.rowconfigure(0, weight=1)
        self.title("Exclusions")
        self.transient(master)
        self.grab_set()
        self.img_supp = PhotoImage(file=IM_SUPP)
        self.img_add = PhotoImage(file=IM_ADD)

        style = Style(self)
        style.configure("list.TFrame", background="white", relief="sunken")

        frame = Frame(self)
        frame.columnconfigure(0, weight=1)
        frame.rowconfigure(0, weight=1)
        frame.grid(row=0, columnspan=2, sticky="eswn", padx=10, pady=(10, 4))

        listbox_frame = Frame(frame, borderwidth=1, style="list.TFrame")
        listbox_frame.columnconfigure(0, weight=1)
        listbox_frame.rowconfigure(0, weight=1)
        listbox_frame.grid(row=0, column=0, sticky="eswn")

        self.listvar = StringVar(self,
                                 value=CONFIG.get("Defaults", "exclude_copie"))
        self.exclude_list = split(r'(?<!\\) ',
                                  CONFIG.get("Defaults", "exclude_copie"))

        self.listbox = Listbox(listbox_frame,
                               highlightthickness=0,
                               listvariable=self.listvar)
        self.listbox.grid(sticky="eswn")

        scroll_x = Scrollbar(frame,
                             orient="horizontal",
                             command=self.listbox.xview)
        scroll_x.grid(row=1, column=0, sticky="ew")
        scroll_y = Scrollbar(frame,
                             orient="vertical",
                             command=self.listbox.yview)
        scroll_y.grid(row=0, column=1, sticky="ns")
        self.listbox.configure(xscrollcommand=scroll_x.set,
                               yscrollcommand=scroll_y.set)

        Button(self, image=self.img_add, command=self.add).grid(row=1,
                                                                column=0,
                                                                sticky="e",
                                                                padx=(10, 4),
                                                                pady=(4, 10))
        Button(self, image=self.img_supp, command=self.rem).grid(row=1,
                                                                 column=1,
                                                                 sticky="w",
                                                                 padx=(4, 10),
                                                                 pady=(4, 10))
        self.geometry("200x300")
Exemplo n.º 23
0
    def _createVeranlagungTab(self, veranlPage: ttk.Frame):
        vv = VeranlagungView(veranlPage)
        vv.grid(column=1, row=1, sticky='nswe', padx=5, pady=5)
        self._veranlagungView = vv

        # veranlPage.rowconfigure(0, weight=1)
        # veranlPage.rowconfigure(2, weight=3)
        veranlPage.columnconfigure(0, weight=1)
        veranlPage.columnconfigure(2, weight=1)
Exemplo n.º 24
0
 def __init__(self, parent, url=None, buttonSEC=False, buttonRSS=False):
     super(DialogURL, self).__init__(parent)
     self.parent = parent
     parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
     dialogX = int(parentGeometry.group(3))
     dialogY = int(parentGeometry.group(4))
     self.accepted = False
     self.url = None
     self.transient(self.parent)
     self.title("Enter URL")
     self.urlVar = StringVar()
     self.urlVar.set(url if url is not None else "http://")
     
     frame = Frame(self)
     urlLabel = Label(frame, text=_("URL:"), underline=0)
     urlEntry = Entry(frame, textvariable=self.urlVar, width=60)
     urlEntry.focus_set()
     okButton = Button(frame, text=_("OK"), command=self.ok)
     cancelButton = Button(frame, text=_("Cancel"), command=self.close)
     if buttonSEC:
         usSecButton = Button(frame, text=_("SEC search"), command=self.usSec)
         usSecButton.grid(row=1, column=1, sticky=W, pady=3)
         ToolTip(usSecButton, text=_("Opens US SEC Edgar Company Search (in web browser)\n\n"
                                  "(1) Find the company in web browser,\n"
                                  "(2) Click 'documents' button for desired filing,\n"
                                  "(3) Find 'data files' panel, instance document row, 'document' column,\n"
                                  "(4) On instance document file name, right-click browser menu: 'copy shortcut',\n"
                                  "(5) Come back to this dialog window,\n"
                                  "(6) Ctrl-v (paste) shortcut into above URL text box,\n"
                                  "(7) Click ok button to load instance document"),
                                  wraplength=480)
     if buttonRSS:
         rssButton = Button(frame, text=_("SEC RSS"), command=self.rssFeed)
         rssButton.grid(row=1, column=1, pady=3)
         ToolTip(rssButton, text=_("Opens current US SEC Edgar RSS feed"),
                                  wraplength=480)
     urlLabel.grid(row=0, column=0, sticky=W, pady=3, padx=3)
     urlEntry.grid(row=0, column=1, columnspan=3, sticky=EW, pady=3, padx=3)
     okButton.grid(row=1, column=2, sticky=E, pady=3)
     ToolTip(okButton, text=_("Opens above URL from web cache, downloading to cache if necessary"), wraplength=240)
     cancelButton.grid(row=1, column=3, sticky=EW, pady=3, padx=3)
     ToolTip(cancelButton, text=_("Cancel operation"))
                 
     frame.grid(row=0, column=0, sticky=(N,S,E,W))
     frame.columnconfigure(1, weight=1)
     window = self.winfo_toplevel()
     window.columnconfigure(0, weight=1)
     self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
     
     self.bind("<Alt-u>", lambda *ignore: urlEntry.focus_set())
     self.bind("<Return>", self.ok)
     self.bind("<Escape>", self.close)
     
     self.protocol("WM_DELETE_WINDOW", self.close)
     self.grab_set()
     self.wait_window(self)
Exemplo n.º 25
0
 def __init__(self, parent, url=None, buttonSEC=False, buttonRSS=False):
     super(DialogURL, self).__init__(parent)
     self.parent = parent
     parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
     dialogX = int(parentGeometry.group(3))
     dialogY = int(parentGeometry.group(4))
     self.accepted = False
     self.url = None
     self.transient(self.parent)
     self.title("Enter URL")
     self.urlVar = StringVar()
     self.urlVar.set(url if url is not None else "http://")
     
     frame = Frame(self)
     urlLabel = Label(frame, text=_("URL:"), underline=0)
     urlEntry = Entry(frame, textvariable=self.urlVar, width=60)
     urlEntry.focus_set()
     okButton = Button(frame, text=_("OK"), command=self.ok)
     cancelButton = Button(frame, text=_("Cancel"), command=self.close)
     if buttonSEC:
         usSecButton = Button(frame, text=_("SEC search"), command=self.usSec)
         usSecButton.grid(row=1, column=1, sticky=W, pady=3)
         ToolTip(usSecButton, text=_("Opens US SEC Edgar Company Search (in web browser)\n\n"
                                  "(1) Find the company in web browser,\n"
                                  "(2) Click 'documents' button for desired filing,\n"
                                  "(3) Find 'data files' panel, instance document row, 'document' column,\n"
                                  "(4) On instance document file name, right-click browser menu: 'copy shortcut',\n"
                                  "(5) Come back to this dialog window,\n"
                                  "(6) Ctrl-v (paste) shortcut into above URL text box,\n"
                                  "(7) Click ok button to load instance document"),
                                  wraplength=480)
     if buttonRSS:
         rssButton = Button(frame, text=_("SEC RSS"), command=self.rssFeed)
         rssButton.grid(row=1, column=1, pady=3)
         ToolTip(rssButton, text=_("Opens current US SEC Edgar RSS feed"),
                                  wraplength=480)
     urlLabel.grid(row=0, column=0, sticky=W, pady=3, padx=3)
     urlEntry.grid(row=0, column=1, columnspan=3, sticky=EW, pady=3, padx=3)
     okButton.grid(row=1, column=2, sticky=E, pady=3)
     ToolTip(okButton, text=_("Opens above URL from web cache, downloading to cache if necessary"), wraplength=240)
     cancelButton.grid(row=1, column=3, sticky=EW, pady=3, padx=3)
     ToolTip(cancelButton, text=_("Cancel operation"))
                 
     frame.grid(row=0, column=0, sticky=(N,S,E,W))
     frame.columnconfigure(1, weight=1)
     window = self.winfo_toplevel()
     window.columnconfigure(0, weight=1)
     self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
     
     self.bind("<Alt-u>", lambda *ignore: urlEntry.focus_set())
     self.bind("<Return>", self.ok)
     self.bind("<Escape>", self.close)
     
     self.protocol("WM_DELETE_WINDOW", self.close)
     self.grab_set()
     self.wait_window(self)
Exemplo n.º 26
0
 def __init__(self, master:Notebook, text, *args, **kw):
     super(TextPage, self).__init__(master, *args, **kw)
     f = Frame(master)
     self.grid(in_=f, row=0, column=0, sticky=NSEW)
     self.lift(f)
     sb = Scrollbar(f, orient='vertical', command=self.yview)
     sb.grid(row=0, column=1, sticky=NS)
     self.configure(yscrollcommand=sb.set) 
     f.columnconfigure(0, weight=1)
     f.rowconfigure(0, weight=1)        
     master.add(f, text=text)
Exemplo n.º 27
0
    def __init__(self, cntlr):

        super(SaveViewerDialog, self).__init__(cntlr.parent)

        self.cntlr = cntlr
        self.parent = cntlr.parent
        self.accepted = False

        self.title("Save iXBRL Viewer")

        frame = Frame(self)
        self._scriptUrl = StringVar()
        self._scriptUrl.set(self.cntlr.config.setdefault('iXBRLViewerScriptURL', 'dist/js'))
        self._filename = StringVar()
        self._filename.set(self.cntlr.config.setdefault("iXBRLViewerOutputFile",""))

        y = 1

        scriptUrlLabel = Label(frame, text = "Script URL");
        scriptUrlEntry = Entry(frame, textvariable = self._scriptUrl, width=80);

        scriptUrlLabel.grid(row=y, column=0, sticky=W, pady=3, padx=3)
        scriptUrlEntry.grid(row=y, column=1, columnspan=2, sticky=EW, pady=3, padx=3)

        y += 1

        filenameLabel = Label(frame, text = "iXBRL file")
        filenameEntry = Entry(frame, textvariable = self._filename, width=80)
        filenameBrowse = Button(frame, text=_("Browse..."), command=self.browseForFile)

        filenameLabel.grid(row=y, column=0, sticky=W, pady=3, padx=3)
        filenameEntry.grid(row=y, column=1, sticky=EW, pady=3, padx=3)
        filenameBrowse.grid(row=y, column=2, sticky=EW, pady=3, padx=3)

        y += 1

        okButton = Button(frame, text=_("OK"), command=self.ok)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        okButton.grid(row=y, column=1, sticky=E, pady=3)
        cancelButton.grid(row=y, column=2, columnspan=1, sticky=E, pady=3, padx=3)

        frame.grid(row=0, column=0, sticky=(N,E,S,W))
        frame.columnconfigure(1, weight=1)

        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        #self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))

        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)

        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
Exemplo n.º 28
0
    def __init__(self, parent=None, title="", message="", button=_("Ok"), image=None):
        """
        Create a message box with one button.

        Arguments:
            parent: parent of the toplevel window
            title: message box title
            message: message box text (that can be selected)
            button: message displayed on the button
            image: image displayed at the left of the message, either a PhotoImage or a string
        """
        Toplevel.__init__(self, parent, class_='Scheduler')
        self.transient(parent)
        self.resizable(False, False)
        self.title(title)
        self.result = ""
        self.button = button
        if isinstance(image, str):
            data = ICONS.get(image)
            if data:
                self.img = PhotoImage(master=self, data=data)
            else:
                self.img = PhotoImage(master=self, file=image)
            image = self.img
        frame = Frame(self)
        frame.rowconfigure(0, weight=1)
        frame.columnconfigure(1, weight=1)
        l = len(message)
        w = max(1, min(l, 50))
        h = 0
        for line in message.splitlines():
            h += 1 + len(line) // w
        if h < 3:
            w = min(l, 35)
            h = 0
            for line in message.splitlines():
                h += 1 + len(line) // w
        display = Text(frame, relief='flat', highlightthickness=0,
                       font="TkDefaultFont 10 bold", bg=self.cget('bg'),
                       height=h, width=w, wrap="word")
        display.configure(inactiveselectbackground=display.cget("selectbackground"))
        display.insert("1.0", message)
        display.configure(state="disabled")
        display.grid(row=0, column=1, pady=(10, 4), padx=4, sticky="ewns")
        display.bind("<Button-1>", lambda event: display.focus_set())
        if image:
            Label(frame, image=image).grid(row=0, column=0, padx=4, pady=(10, 4))
        b = Button(self, text=button, command=self.validate)
        frame.pack()
        b.pack(padx=10, pady=10)
        self.grab_set()
        b.focus_set()
Exemplo n.º 29
0
        def frame_commands(root):
            frame = Frame(root, **padded)  # type: ignore

            # Configure grid
            frame.rowconfigure(0, weight=1)
            frame.columnconfigure(0, weight=1)

            # Place widgets
            button = Button(frame, text="Calculate", command=self.calculate)
            button.grid(column=0, row=0)
            self.root.bind('<Return>', self.calculate)

            return frame
Exemplo n.º 30
0
 def create_status_bar(self, master):
     statbar = Frame(master, padding = '3 3 3 3')
     statbar.grid(column=0, row=2, sticky=(EW, S))
     Label(statbar, text='RDFS File:', padding='0 3 0 3').grid(row=0, column=0, sticky=SE)
     rdfsFileNameLbl = Label(statbar, textvariable=self.rdfsFileName,
                             background='#bbb', relief=SUNKEN, padding='3 3 3 3')
     rdfsFileNameLbl.grid(column=1, row=0, sticky=(EW))
     Label(statbar, text='Template file:', padding='0 3 0 3').grid(row=1, column=0, sticky=SE)        
     templateFileNameLbl = Label(statbar, textvariable=self.templateFileName,
                                 background='#bbb', relief=SUNKEN, padding='3 3 3 3')
     templateFileNameLbl.grid(column=1, row=1, sticky=(EW))
     statbar.columnconfigure(1, weight=1)
     for child in statbar.winfo_children():
         child.grid_configure(padx=3, pady=3)
Exemplo n.º 31
0
def secondWindow():
    if validate_email(mail.get()) == False:
        messagebox.showerror('Ошибка', 'Проверьте написание почты')
    else:
        # Закрытие окна входа -----------------------------------------------------
        loginwindow.destroy()
        # Глобализируем переменные ------------------------------------------------
        global mail_to
        global subject
        global message_form
        global delay
        global app
        # Основное ----------------------------------------------------------------
        app = Tk()
        app.title('Email Sender, v1.5.4')
        app.geometry('425x340') #Измените размеры, если у вас НЕ Windows
        app.resizable(height = False, width = False)
        # Переменные -------------------------------------------------------------- 
        mail_to = StringVar()
        subject = StringVar()
        message_form = StringVar()
        delay = IntVar()
        # Геометрия окна ----------------------------------------------------------
        mainframe = Frame(app, padding = '3 3 12 12')
        mainframe.grid(column = 0, row = 0, sticky = (N, W, E, S))
        mainframe.columnconfigure(0, weight = 1)
        mainframe.rowconfigure(0, weight = 1)
        # Текст -------------------------------------------------------------------
        ttk.Label(mainframe, text = 'Почта получателя: ').grid(column = 0, row = 0, sticky = W)
        ttk.Label(mainframe, text = 'Тема сообщения: ').grid(column = 0, row = 1, sticky = W)
        ttk.Label(mainframe, text = 'Текст сообщения: ').grid(column = 0, row = 2, sticky = W)
        ttk.Label(mainframe, text = 'Таймер (сек): ').grid(column = 2, row = 3, sticky = E)
        # Текстовые формы ---------------------------------------------------------
        mail_to_form = ttk.Entry(mainframe, width = 30, textvariable = mail_to).grid(column = 2, row = 0, sticky = (W, E))
        subject_form = ttk.Entry(mainframe, width = 30, textvariable = subject).grid(column = 2, row = 1, sticky = (W, E))
        message_form = Text(mainframe, width = 35, height = 10)
        message_form.grid(column = 2, row = 2, sticky = (W, E))
        # -------------------------------------------------------------------------
        timer = ttk.Entry(mainframe, width = 15, textvariable = delay).grid(column = 2, row = 4, sticky = E)
        # Кнопки ------------------------------------------------------------------
        send_button = ttk.Button(mainframe, text = 'Отправить', command = send)
        send_button.grid(column = 2, row = 5, sticky = E)
        # -------------------------------------------------------------------------
        add_file_button = ttk.Button(mainframe, text = 'Прикрепить', command = add_files)
        add_file_button.grid(column = 0, row = 5, sticky = W) 
        # Отрисовка ---------------------------------------------------------------
        for child in mainframe.winfo_children():
            child.grid_configure(padx = 5, pady = 5)
        app.mainloop()
Exemplo n.º 32
0
    def create_widgets(self):
        ''' Creates appropriate widgets on this frame.
        '''
        self.columnconfigure(0, weight=1)
        self.rowconfigure(3, weight=1)
        frame_for_save_btn = Frame(self)
        frame_for_save_btn.columnconfigure(1, weight=1)
        self.status_lbl = Label(frame_for_save_btn, text='')
        self.status_lbl.grid(row=0, column=1, sticky=N + W)
        save_solution_btn = Button(frame_for_save_btn,
                                   text='Save solution',
                                   command=self.on_save_solution)
        save_solution_btn.grid(row=1, column=0, sticky=W + N, padx=5, pady=5)
        self.progress_bar = Progressbar(frame_for_save_btn,
                                        mode='determinate',
                                        maximum=100)
        self.progress_bar.grid(row=1, column=1, sticky=W + E, padx=10, pady=5)

        frame_for_save_btn.grid(sticky=W + N + E + S, padx=5, pady=5)

        frame_for_btns = Frame(self)
        self._create_file_format_btn('*.xlsx', 1, frame_for_btns, 0)
        self._create_file_format_btn('*.xls', 2, frame_for_btns, 1)
        self._create_file_format_btn('*.csv', 3, frame_for_btns, 2)
        self.solution_format_var.set(1)

        frame_for_btns.grid(row=1,
                            column=0,
                            sticky=W + N + E + S,
                            padx=5,
                            pady=5)
        self.data_from_file_lbl = Label(self,
                                        text=TEXT_FOR_FILE_LBL,
                                        anchor=W,
                                        justify=LEFT,
                                        wraplength=MAX_FILE_PARAMS_LBL_LENGTH)
        self.data_from_file_lbl.grid(row=2,
                                     column=0,
                                     padx=5,
                                     pady=5,
                                     sticky=W + N)

        self.solution_tab = SolutionFrameWithText(self)
        self.solution_tab.grid(row=3,
                               column=0,
                               sticky=W + E + S + N,
                               padx=5,
                               pady=5)
Exemplo n.º 33
0
class ScrolledCanvas:
    def __init__(self, master, **opts):
        if 'yscrollincrement' not in opts:
            opts['yscrollincrement'] = 17
        self.master = master
        self.frame = Frame(master)
        self.frame.rowconfigure(0, weight=1)
        self.frame.columnconfigure(0, weight=1)
        self.canvas = Canvas(self.frame, **opts)
        self.canvas.grid(row=0, column=0, sticky="nsew")
        self.vbar = Scrollbar(self.frame, name="vbar")
        self.vbar.grid(row=0, column=1, sticky="nse")
        self.hbar = Scrollbar(self.frame, name="hbar", orient="horizontal")
        self.hbar.grid(row=1, column=0, sticky="ews")
        self.canvas['yscrollcommand'] = self.vbar.set
        self.vbar['command'] = self.canvas.yview
        self.canvas['xscrollcommand'] = self.hbar.set
        self.hbar['command'] = self.canvas.xview
        self.canvas.bind("<Key-Prior>", self.page_up)
        self.canvas.bind("<Key-Next>", self.page_down)
        self.canvas.bind("<Key-Up>", self.unit_up)
        self.canvas.bind("<Key-Down>", self.unit_down)
        self.canvas.bind("<MouseWheel>", wheel_event)
        self.canvas.bind("<Button-4>", wheel_event)
        self.canvas.bind("<Button-5>", wheel_event)
        #if isinstance(master, Toplevel) or isinstance(master, Tk):
        self.canvas.bind("<Alt-Key-2>", self.zoom_height)
        self.canvas.focus_set()

    def page_up(self, event):
        self.canvas.yview_scroll(-1, "page")
        return "break"

    def page_down(self, event):
        self.canvas.yview_scroll(1, "page")
        return "break"

    def unit_up(self, event):
        self.canvas.yview_scroll(-1, "unit")
        return "break"

    def unit_down(self, event):
        self.canvas.yview_scroll(1, "unit")
        return "break"

    def zoom_height(self, event):
        zoomheight.zoom_height(self.master)
        return "break"
Exemplo n.º 34
0
    def create_rdfs_frame(self, master:Notebook):
        rdfsframe = Frame(master, padding = '3 3 3 3', width=600, height=400)
        Label(rdfsframe, text='RDFS Name:', padding='3 3 3 3').grid(row=0, column=0, padx=3, pady=3)
        rdfsNameLbl = Label(rdfsframe, textvariable=self.rdfsName,
                            background='#bbb', relief=SUNKEN, padding='3 0 3 3')
        rdfsNameLbl.grid(row=0, column=1, columnspan=3, sticky=EW, padx=3, pady=6)
        self.classtree.heading(column='#0', text='ClassTree')
        ysb = Scrollbar(rdfsframe, orient='vertical', command=self.classtree.yview)
        xsb = Scrollbar(rdfsframe, orient='horizontal', command=self.classtree.xview)
        self.classtree.configure(yscrollcommand=ysb.set)
        self.classtree.configure(xscrollcommand=xsb.set)
        self.classtree.bind('<<TreeviewSelect>>', self.update_classinfo)
        self.classtree.grid(row=1, column=0, columnspan=2, in_=rdfsframe, sticky=NSEW)
        self.classtree.lift(rdfsframe)
        self.classtree.tag_configure('include', foreground='black')
        self.classtree.tag_configure('notinclude', foreground='gray')
        ysb.grid(row=1, column=2, sticky=(NS))
        xsb.grid(row=2, column=0, columnspan=2, sticky=(EW))
        classinfoframe = Frame(rdfsframe, width=300, height=400)
        classinfoframe.grid(row=1, column=3, padx=3, pady=3, sticky=(NSEW))
        Label(classinfoframe, text='Class Name:',
              font='bold', padding='3 3 3 3').grid(row=1, column=0, sticky=NW)
        classNameLbl = Label(classinfoframe, textvariable=self.className,
                            background='#bbb', relief=SUNKEN, padding='3 3 3 3',
                             font='bold', width=25)
        classNameLbl.grid(row=1, column=1, sticky=EW)
        Label(classinfoframe, text='Description:',
              font='bold', padding='3 3 3 3').grid(row=2, column=0, sticky=NW)
        self.classDescrTxt.grid(row=2, column=1, in_=classinfoframe, sticky=EW)
        self.classDescrTxt.lift(classinfoframe)
        include_chk = Checkbutton(classinfoframe,
                                  text='include this class',
                                  variable=self.includeclass,
                                  command=self.include_class)
        include_chk.grid(row=3, column=1, sticky=E)
        Label(classinfoframe, text='Properties:',
              font='bold', padding='3 3 3 3').grid(row=5, column=0, sticky=NW)
        self.propertiesframe.grid(in_ = classinfoframe, row=5, column=1, sticky=(N+E+S+W))
        self.propertiesframe.lift(classinfoframe)

        classinfoframe.rowconfigure(5, weight=1)
        classinfoframe.columnconfigure(1, weight=1)
        rdfsframe.columnconfigure(1, weight=1)
        rdfsframe.columnconfigure(3, weight=3)
        rdfsframe.rowconfigure(1, weight=1)        
        master.add(rdfsframe, text='RDFS')
Exemplo n.º 35
0
    def __create_frame_grid(
            self,
            frame_position: FrameGridPositionEnum,
            width: int = None,
            height: int = None,
            column_weight: int = 0,
            row_weight: int = 0,
            padx: int = None,
            pady: int = None,
            row: int = None,
            column: int = None,
            sticky: GridPositionEnum = GridPositionEnum.NONE) -> Frame:
        if frame_position == FrameGridPositionEnum.CUSTOM_POSITION \
                and (row is None or column is None):
            raise ApplicationException(
                'Bug: row and column parameters must have values'
                ' when frame_position is CUSTOM_POSITION')

        frame = Frame(self.__frame_and_name.frame)
        self.update_row_and_column(frame_position)

        if frame_position != FrameGridPositionEnum.CUSTOM_POSITION:
            row = self.__row
            column = self.__column

        logger().debug(
            f'Create new frame_and_name. Parent [{self.__frame_and_name.name}]'
            f' Row [{row}] Column [{column}]'
            f' Sticky [{sticky.value}]')

        frame.rowconfigure(row, weight=row_weight)
        frame.columnconfigure(column, weight=column_weight)

        frame.grid(row=row,
                   column=column,
                   padx=padx,
                   pady=pady,
                   sticky=sticky.value)

        if width:
            frame.config(width=width)

        if height:
            frame.config(height=height)

        return frame
Exemplo n.º 36
0
class Scratchpad:
    def __init__(self):
        self.window = Tk()
        self.window.title("Onager Scratchpad")
        self.create_frame()
        self.create_editing_window()
        self.window.bind('<F7>', self.save_file)
        self.window.bind('<F5>', self.open_file)

    def create_frame(self):
        frame_style = Style()
        frame_style.theme_use('alt')
        frame_style.configure("TFrame", relief='raised')
        self.frame = Frame(self.window, style="frame_style.TFrame")
        self.frame.rowconfigure(1)
        self.frame.columnconfigure(1)
        self.frame.grid(row=0, column=0)

    def create_editing_window(self):
        self.editing_window = ScrolledText(self.frame)
        self.editing_window.configure(fg='gold',
                                      bg='blue',
                                      font='serif 12',
                                      padx='15',
                                      pady='15',
                                      wrap='word',
                                      borderwidth='10',
                                      relief='sunken',
                                      tabs='48',
                                      insertbackground='cyan')
        self.editing_window.grid(row=0, column=0)

    def save_file(self, event=None):
        name = asksaveasfilename()
        outfile = open(name, 'w')
        contents = self.editing_window.get(0.0, END)
        outfile.write(contents)
        outfile.close()

    def open_file(self, event=None):
        name = askopenfilename()
        infile = open(name, 'r')
        contents = infile.read()
        self.editing_window.insert(INSERT, contents)
        infile.close()
Exemplo n.º 37
0
    def __init__(self):
        super().__init__()
        # __________ ROOT WINDOW MENU BAR __________
        self.geometry("500x600")
        self.title("Magic Session Mixer")
        # set icon:
        dirname = os.path.dirname(__file__)
        icon_path = os.path.join(dirname, 'magic_session_mixer.ico')
        self.iconbitmap(icon_path)

        # ________________ STYLING ________________
        s = Style()

        s.configure("Active.TFrame", background='#007AD9')
        # s.configure("Inactive.TFrame", background='#A2A2A2')
        s.configure("Inactive.TFrame", background='#AF3118')

        s.configure("Unmuted.TButton", foreground='#007AD9')
        # s.configure("Muted.TButton", foreground='#C33C54')
        s.configure("Muted.TButton", foreground='#AF3118')

        # _________________ HEADER _________________
        header = Frame(self)
        title = Label(header,
                      text="Magic Session Mixer",
                      font=("Calibri", 20, "bold"))

        # ________________ SEPARATE ________________
        separate = Separator(header, orient=HORIZONTAL)

        # ____________ ARRANGE ELEMENTS ____________
        header.columnconfigure(0, weight=1)
        title.grid(row=0, column=0, pady=10, sticky="W")
        separate.grid(row=1, column=0, sticky="EW", pady=10)

        # _______________ PACK FRAME _______________
        header.pack(fill='x', padx=15)

        # ____________ BUILD WITH PYCAW ____________
        turbo_anonym = Label(self,
                             text="created by TurboAnonym with pycaw",
                             font=("Consolas", 8, "italic"))
        turbo_anonym.pack(side=BOTTOM, fill="x", pady=6, padx=6)
Exemplo n.º 38
0
    def _create_tab(self,
                    window_name: str,
                    tab_name: str,
                    tab_frame_name: str,
                    row_weight_index: int = None,
                    row_weight: int = 0,
                    column_weight_index: int = None,
                    column_weight: int = 0,
                    sticky: GridPositionEnum = None) -> FramesOrganizer:
        """
        Create tab.

        :param window_name:
        :param tab_name: Tab name which will appear in the top of the tab.
        :param tab_frame_name: Tab frame_and_name name
                               which will be used as tab index.
        :param row_weight_index:
        :param row_weight:
        :param column_weight_index:
        :param column_weight:
        :param sticky:
        :return:
        """
        tab = Frame(self.get_tab_control(window_name))

        if row_weight_index is not None:
            tab.rowconfigure(row_weight_index, weight=row_weight)

        if column_weight_index is not None:
            tab.columnconfigure(column_weight_index, weight=column_weight)

        self._tab = tab
        if sticky:
            self.get_tab_control(window_name).add(tab,
                                                  text=tab_name,
                                                  sticky=sticky.value)
        else:
            self.get_tab_control(window_name).add(tab, text=tab_name)

        self._add_to_parent_frames_dict(tab, tab_frame_name)

        return self._parent_frames_dict[tab_frame_name]
Exemplo n.º 39
0
class MinutiaeFrameBase(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)

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

        self.open_fingerprint_image_button = Frame(self,
                                                   relief=RAISED,
                                                   borderwidth=1)
        self.open_fingerprint_image_button.grid(row=0, column=0, sticky=NSEW)

        self.open_fingerprint_image_button.columnconfigure(0, weight=1)

        self.minutiae_file_label = Label(self.open_fingerprint_image_button,
                                         text="test")
        self.minutiae_file_label.grid(row=0, column=0)

        self.minutiae_file_label = ScrolledText(self)
        self.minutiae_file_label.grid(row=1, column=0, sticky=NSEW)
Exemplo n.º 40
0
class ScrolledCanvas:
    def __init__(self, master, **opts):
        if 'yscrollincrement' not in opts:
            opts['yscrollincrement'] = 17
        self.master = master
        self.frame = Frame(master)
        self.frame.rowconfigure(0, weight=1)
        self.frame.columnconfigure(0, weight=1)
        self.canvas = Canvas(self.frame, **opts)
        self.canvas.grid(row=0, column=0, sticky="nsew")
        self.vbar = Scrollbar(self.frame, name="vbar")
        self.vbar.grid(row=0, column=1, sticky="nse")
        self.hbar = Scrollbar(self.frame, name="hbar", orient="horizontal")
        self.hbar.grid(row=1, column=0, sticky="ews")
        self.canvas['yscrollcommand'] = self.vbar.set
        self.vbar['command'] = self.canvas.yview
        self.canvas['xscrollcommand'] = self.hbar.set
        self.hbar['command'] = self.canvas.xview
        self.canvas.bind("<Key-Prior>", self.page_up)
        self.canvas.bind("<Key-Next>", self.page_down)
        self.canvas.bind("<Key-Up>", self.unit_up)
        self.canvas.bind("<Key-Down>", self.unit_down)
        #if isinstance(master, Toplevel) or isinstance(master, Tk):
        self.canvas.bind("<Alt-Key-2>", self.zoom_height)
        self.canvas.focus_set()
    def page_up(self, event):
        self.canvas.yview_scroll(-1, "page")
        return "break"
    def page_down(self, event):
        self.canvas.yview_scroll(1, "page")
        return "break"
    def unit_up(self, event):
        self.canvas.yview_scroll(-1, "unit")
        return "break"
    def unit_down(self, event):
        self.canvas.yview_scroll(1, "unit")
        return "break"
    def zoom_height(self, event):
        zoomheight.zoom_height(self.master)
        return "break"
Exemplo n.º 41
0
class qbtConvertor(Tk):
    """ GUI Application for migration from uTorrent to qBittorrent """
    def __init__(self):
        Tk.__init__(self)
        self.title("uT to qBt convertor")

        #main frame
        self.main_frame = Frame(self, padding="3 3 12 12")
        self.main_frame.grid(column=0, row=0, sticky=(N, W, E, S))
        self.main_frame.columnconfigure(0, weight=1)
        self.main_frame.rowconfigure(0, weight=1)

        #uT part
        self.ut_data = StringVar()
        self.ut_label = Label(self.main_frame, text="uT data")
        self.ut_label.grid(column=0, row=1, sticky=(W))
        self.ut_entry = Entry(self.main_frame, width=100, textvariable=self.ut_data)
        self.ut_entry.grid(column=1, row=1, sticky=(W))
        self.ut_button = Button(self.main_frame, text="Browse", command=self.load_file)
        self.ut_button.grid(column=2, row=1)

        #qBt part
        self.qbt_folder = StringVar()
        self.qbt_label = Label(self.main_frame, text="qBt folder")
        self.qbt_label.grid(column=0, row=4, sticky=(W))
        self.qbt_entry = Entry(self.main_frame, width=100, textvariable=self.qbt_folder)
        self.qbt_entry.grid(column=1, row=4, sticky=(W))
        self.qbt_button = Button(self.main_frame, text="Browse", command=self.open_dir)
        self.qbt_button.grid(column=2, row=4, sticky=(W, E))


        #convertor
        self.convertor_button = Button(self.main_frame, text="Convert", command=self.convert,
                                       width=50)
        self.convertor_button.grid(column=1, columnspan=2, row=5)

        self.progress_bar = Progressbar(self.main_frame, orient=HORIZONTAL, length=300, mode="indeterminate")
        self.progress_bar.grid(column=1, columnspan=3, row=6)

        #set padding for each element
        for child in self.main_frame.winfo_children():
            child.grid_configure(padx=5, pady=5)

    def convert(self):
        message = messagebox
        if not self.qbt_folder.get() or not self.ut_data.get():
            message.showerror("ERROR", "Specify paths!")
            return
        self.progress_bar.start()
        convertor(self.ut_data.get(), self.qbt_folder.get())
        self.progress_bar.stop()

    def load_file(self):
        file_name = filedialog.askopenfilename(filetypes=(("UT resume file", "*.dat"),
                                                          ("All", "*")))
        if file_name:
            self.ut_data.set(file_name)

    def open_dir(self):
        dir_name = filedialog.askdirectory()

        if dir_name:
            self.qbt_folder.set(dir_name)
Exemplo n.º 42
0
class Sudoku(Tk):
    def __init__(self, file=None):
        Tk.__init__(self, className="Sudoku-Tk")
        self.title("Sudoku-Tk")
        self.resizable(0, 0)
        self.protocol("WM_DELETE_WINDOW", self.quitter)
        cst.set_icon(self)
        self.columnconfigure(3, weight=1)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        menu_nouveau = Menu(menu, tearoff=0)

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

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

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

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

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

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

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

        self.configure(menu=menu)

        # --- clavier popup
        self.clavier = None

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

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

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

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

    @property
    def level(self):
        return self._level

    @level.setter
    def level(self, level):
        self._level = level
        self.label_level.configure(text=_(level.capitalize()))

    def update_nbs(self, nb, delta):
        self.progression[nb - 1].nb += delta

    def reset_nbs(self):
        for p in self.progression:
            p.nb = 0

    def evaluate_level(self):
        grille = Grille()
        for i in range(9):
            for j in range(9):
                val = self.blocs[i, j].get_val()
                if val:
                    grille.ajoute_init(i, j, val)
        self.level = difficulte_grille(grille)

    def show_stat(self):
        """ show best times """
        def reset():
            """ reset best times """
            for level in ["easy", "medium", "difficult"]:
                CONFIG.set("Statistics", level, "")
            top.destroy()

        if self.chrono_on:
            self.play_pause()
        top = Toplevel(self)
        top.transient(self)
        top.columnconfigure(1, weight=1)
        top.resizable(0, 0)

        top.title(_("Statistics"))
        top.grab_set()

        Label(top, text=_("Best times"), font="Sans 12 bold").grid(row=0, columnspan=2,
                                                                   padx=30, pady=10)

        for i, level in enumerate(["easy", "medium", "difficult"]):
            Label(top, text=_(level.capitalize()),
                  font="Sans 10 bold").grid(row=i + 1, column=0, padx=(20, 4),
                                            pady=4, sticky="e")
            tps = CONFIG.get("Statistics", level)
            if tps:
                tps = int(tps)
                m = tps // 60
                s = tps % 60
                Label(top, text=" %i min %i s" % (m, s),
                      font="Sans 10").grid(row=i + 1, column=1,
                                           sticky="w", pady=4,
                                           padx=(4, 20))
        Button(top, text=_("Close"), command=top.destroy).grid(row=4, column=0, padx=(10, 4), pady=10)
        Button(top, text=_("Clear"), command=reset).grid(row=4, column=1, padx=(4, 10), pady=10)

    def new_easy(self):
        nb = np.random.randint(1, 101)
        fichier = join(cst.PUZZLES_LOCATION, "easy", "puzzle_easy_%i.txt" % nb)
        self.import_grille(fichier)
        self.level = "easy"

    def new_medium(self):
        nb = np.random.randint(1, 101)
        fichier = join(cst.PUZZLES_LOCATION, "medium", "puzzle_medium_%i.txt" % nb)
        self.import_grille(fichier)
        self.level = "medium"

    def new_difficult(self):
        nb = np.random.randint(1, 101)
        fichier = join(cst.PUZZLES_LOCATION, "difficult", "puzzle_difficult_%i.txt" % nb)
        self.import_grille(fichier)
        self.level = "difficult"

    def translate(self):
        """ changement de la langue de l'interface """
        one_button_box(self, _("Information"),
                       _("The language setting will take effect after restarting the application"),
                       image=self.im_info)
        CONFIG.set("General", "language", self.langue.get())

    def focus_out(self, event):
        """ met en pause si la fenêtre n'est plus au premier plan """
        try:
            if not self.focus_get() and self.chrono_on:
                self.play_pause()
        except KeyError:
            # erreur déclenchée par la présence d'une tkMessagebox
            if self.chrono_on:
                self.play_pause()

    def stacks_reinit(self):
        """efface l'historique des actions"""
        self._undo_stack.clear()
        self._redo_stack.clear()
        self.b_undo.configure(state="disabled")
        self.b_redo.configure(state="disabled")

    def stacks_modif(self, action):
        """Record action and clear redo stack."""
        self._undo_stack.append(action)
        self.b_undo.configure(state="normal")
        self.b_redo.configure(state="disabled")
        self._redo_stack.clear()

    def about(self):
        if self.chrono_on:
            self.play_pause()
        About(self)

    def aide(self, event=None):
        if self.chrono_on:
            self.play_pause()
        Aide(self)

    def quitter(self):
        rep = _("Yes")
        if self.debut:
            rep = two_button_box(self, _("Confirmation"),
                                 _("Do you want to interrupt the current puzzle?"),
                                 _("Yes"), _("No"), image=self.im_question)
        if rep == _("Yes"):
            if self.debut:
                self.save(cst.PATH_SAVE)
            self.destroy()

    def undo(self):
        if self._undo_stack and self.chrono_on:
            self.b_redo.configure(state="normal")
            i, j, val_prec, pos_prec, modifs, val, pos = self._undo_stack.pop(-1)
            self._redo_stack.append((i, j, val_prec, pos_prec, modifs, val, pos))
            if not self._undo_stack:
                self.b_undo.configure(state="disabled")

            if self.blocs[i, j].get_val():
                self.modifie_nb_cases_remplies(-1)
                self.update_nbs(self.blocs[i, j].get_val(), -1)
            self.blocs[i, j].efface_case()
            if val_prec:
                self.modifie_nb_cases_remplies(self.blocs[i, j].edit_chiffre(val_prec))
                if not self.test_case(i, j, val):
                    self.update_grille(i, j, val)
            else:
                for nb in pos_prec:
                    v = int(nb)
                    self.modifie_nb_cases_remplies(self.blocs[i, j].edit_possibilite(v))
                    self.test_possibilite(i, j, v)
            for k, l in modifs:
                self.blocs[k, l].edit_possibilite(val)

    def redo(self):
        if self._redo_stack and self.chrono_on:
            self.b_undo.configure(state="normal")
            i, j, val_prec, pos_prec, modifs, val, pos = self._redo_stack.pop(-1)
            self._undo_stack.append((i, j, val_prec, pos_prec, modifs, val, pos))
            if not self._redo_stack:
                self.b_redo.configure(state="disabled")
            val_prec = self.blocs[i, j].get_val()
            if val_prec:
                self.modifie_nb_cases_remplies(-1)
                self.update_nbs(val_prec, -1)
            self.blocs[i, j].efface_case()
            if val:
                self.modifie_nb_cases_remplies(self.blocs[i, j].edit_chiffre(val))
                if not self.test_case(i, j, val_prec):
                    self.update_grille(i, j, val_prec)
            else:
                for nb in pos:
                    v = int(nb)
                    self.modifie_nb_cases_remplies(self.blocs[i, j].edit_possibilite(v))
                    self.test_possibilite(i, j, v)

    def restart(self, m=0, s=0):
        """ réinitialise le chrono et les boutons """
        self.chrono = [m, s]
        self.chrono_on = False
        self.debut = False
        self.tps.configure(text=" %02i:%02i" % tuple(self.chrono))
        self.b_undo.configure(state="disabled")
        self.b_pause.configure(state="disabled", image=self.im_pause)
        self.b_redo.configure(state="disabled")
        self.b_restart.configure(state="disabled")
        self.stacks_reinit()
        self.frame_pause.place_forget()

    def play_pause(self):
        """ Démarre le chrono s'il était arrêté, le met en pause sinon """
        if self.debut:
            if self.chrono_on:
                self.chrono_on = False
                self.b_pause.configure(image=self.im_play)
                self.b_redo.configure(state="disabled")
                self.b_undo.configure(state="disabled")
                self.tooltip_wrapper.set_tooltip_text(self.b_pause, _("Resume game"))
                self.frame_pause.place(in_=self.frame_puzzle, x=0, y=0, anchor='nw',
                                       relwidth=1, relheight=1)
            elif self.nb_cases_remplies != 81:
                self.chrono_on = True
                self.b_pause.configure(image=self.im_pause)
                self.tps.after(1000, self.affiche_chrono)
                if self._undo_stack:
                    self.b_undo.configure(state="normal")
                if self._redo_stack:
                    self.b_redo.configure(state="normal")
                self.tooltip_wrapper.set_tooltip_text(self.b_pause, _("Pause game"))
                self.frame_pause.place_forget()

    def affiche_chrono(self):
        """ Met à jour l'affichage du temps """
        if self.chrono_on:
            self.chrono[1] += 1
            if self.chrono[1] == 60:
                self.chrono[0] += 1
                self.chrono[1] = 0
            self.tps.configure(text=" %02i:%02i" % tuple(self.chrono))
            self.tps.after(1000, self.affiche_chrono)

    def modifie_nb_cases_remplies(self, nb):
        self.nb_cases_remplies += nb

    def edit_case(self, event):
        if event.num in [1, 3]:
            if not self.debut and self.nb_cases_remplies != 81:
                self.debut = True
                self.b_pause.configure(state="normal")
                self.b_restart.configure(state="normal")
                self.play_pause()
            if str(event.widget) != "." and self.chrono_on:
                if self.clavier:
                    self.clavier.quitter()
                ref = self.blocs[0, 0].winfo_parent()
                case = event.widget.grid_info().get("in", None)
                if str(case) == ref:
                    case = event.widget
                try:
                    if case.is_modifiable():
                        if event.num == 1:
                            self.clavier = Clavier(self, case, "val")
                        elif event.num == 3:
                            self.clavier = Clavier(self, case, "possibilite")
                        self.clavier.display("+%i+%i" % (case.winfo_rootx() - 25, case.winfo_rooty() + 50))
                except AttributeError:
                    if self.clavier:
                        self.clavier.quitter()

            elif self.clavier:
                self.clavier.quitter()

    def test_case(self, i, j, val_prec=0):
        """ Teste si la valeur de la case est en contradiction avec celles des
            autres cases de la ligne / colonne / bloc et renvoie True s'il y a une erreur."""
        val = self.blocs[i, j].get_val()
        a, b = i // 3, j // 3
        error = False
        if val:
            if ((self.blocs[i, :] == val).sum() > 1 or (self.blocs[:, j] == val).sum() > 1 or
               (self.blocs[3 * a: 3 * (a + 1), 3 * b: 3 * (b + 1)] == val).sum() > 1):
                # erreur !
                self.blocs[i, j].affiche_erreur()
                error = True
        if val_prec:
            # a number was removed, remove obsolete errors
            line = self.blocs[i, :] == val_prec
            column = self.blocs[:, j] == val_prec
            bloc = self.blocs[3 * a: 3 * (a + 1), 3 * b: 3 * (b + 1)] == val_prec
            if line.sum() == 1:
                self.blocs[i, line.argmax()].no_error()
                self.test_case(i, line.argmax())
            if column.sum() == 1:
                self.blocs[column.argmax(), j].no_error()
                self.test_case(column.argmax(), j)
            if bloc.sum() == 1:
                x, y = divmod(bloc.argmax(), 3)
                self.blocs[3 * a + x, 3 * b + y].no_error()
                self.test_case(3 * a + x, 3 * b + y)
        return error

    def test_possibilite(self, i, j, val):
        """ Teste si la possibilité val de la case est en contradiction avec les valeurs des
            autres cases de la ligne / colonne / bloc """
        a, b = i // 3, j // 3
        if ((self.blocs[i, :] == val).sum() > 0 or (self.blocs[:, j] == val).sum() > 0 or
           (self.blocs[3 * a: 3 * (a + 1), 3 * b: 3 * (b + 1)] == val).sum() > 0):
            # erreur !
            self.blocs[i, j].affiche_erreur_possibilite(val)

    def test_remplie(self):
        """ Test si la grille est remplie """
        if self.nb_cases_remplies == 81:
            grille = Grille()
            for i in range(9):
                for j in range(9):
                    val = self.blocs[i, j].get_val()
                    if val:
                        grille.ajoute_init(i, j, val)
            sol = grille.solve()
            if type(sol) == np.ndarray:
                self.play_pause()
                self.frame_pause.place_forget()
                one_button_box(self, _("Information"),
                               _("You solved the puzzle in %(min)i minutes and %(sec)i secondes.") % {"min": self.chrono[0], "sec": self.chrono[1]},
                               image=self.im_info)
                if self.level != "unknown":
                    best = CONFIG.get("Statistics", self.level)
                    current = self.chrono[0] * 60 + self.chrono[1]
                    if best:
                        best = int(best)
                        if current < best:
                            CONFIG.set("Statistics", self.level, str(current))
                    else:
                        CONFIG.set("Statistics", self.level, str(current))
                self.b_pause.configure(state="disabled")
                self.debut = False

            else:
                i, j = sol[1]
                if self.blocs[i, j].get_val():
                    self.blocs[i, j].affiche_erreur()
                one_button_box(self, _("Information"), _("There is a mistake."),
                               image=self.im_info)

    def update_grille(self, i, j, val_prec=0):
        """ Enlève les possibilités devenues impossibles suite à l'ajout d'une
            valeur dans la case (i, j) """
        val = self.blocs[i, j].get_val()
        modif = []
        a, b = i // 3, j // 3
        if val_prec:
            x, y = divmod(val_prec - 1, 3)
        for k, (line, column, bloc) in enumerate(zip(self.blocs[i, :], self.blocs[:, j], self.blocs[3 * a: 3 * (a + 1), 3 * b: 3 * (b + 1)].flatten())):
            # works because if line is bloc then pos1 is pos3 and both are edited at once
            pos1 = line.get_possibilites()
            pos2 = column.get_possibilites()
            pos3 = bloc.get_possibilites()
            if val in pos1:
                self.blocs[i, k].edit_possibilite(val)
                modif.append((i, k))
            if val in pos2:
                self.blocs[k, j].edit_possibilite(val)
                modif.append((k, j))
            if val in pos3:
                m, n = divmod(k, 3)
                self.blocs[3 * a + m, 3 * b + n].edit_possibilite(val)
                modif.append((3 * a + m, 3 * b + n))
            if val_prec:
                if val_prec in pos1:
                    self.blocs[i, k].pas_erreur(x, y)
                    self.test_possibilite(i, k, val_prec)
                if val_prec in pos2:
                    self.blocs[k, j].pas_erreur(x, y)
                    self.test_possibilite(k, j, val_prec)
                if val_prec in pos3:
                    m, n = divmod(k, 3)
                    m, n = 3 * a + m, 3 * b + n
                    if m != i and n != j:
                        self.blocs[m, n].pas_erreur(x, y)
                        self.test_possibilite(m, n, val_prec)
        return modif

    def set_clavier(self, c):
        self.clavier = c

    def grille_vide(self):
        rep = _("Yes")
        if self.debut:
            rep = two_button_box(self, _("Confirmation"),
                                 _("Do you want to abandon the current puzzle?"),
                                 _("Yes"), _("No"), self.im_question)
        if rep == _("Yes"):
            self.nb_cases_remplies = 0
            self.restart()
            self.level = "unknown"
            self.reset_nbs()
            for i in range(9):
                for j in range(9):
                    self.blocs[i, j].set_modifiable(True)
                    self.blocs[i, j].efface_case()

    def genere_grille(self):
        """ Génère une nouvelle grille """
        if self.chrono_on:
            self.play_pause()
        rep = _("Yes")
        if self.debut:
            rep = two_button_box(self, _("Confirmation"),
                                 _("Do you want to abandon the current puzzle?"),
                                 _("Yes"), _("No"), self.im_question)

        if rep == _("Yes"):
            self.configure(cursor="watch")
            self.update()
            rep2 = _("Retry")
            while rep2 == _("Retry"):
                grille = genere_grille()
                diff = difficulte_grille(grille)
                nb = grille.nb_cases_remplies()
                self.configure(cursor="")
                rep2 = two_button_box(self, _("Information"),
                                      _("The generated puzzle contains %(nb)i numbers and its level is %(difficulty)s.") % ({"nb": nb, "difficulty": _(diff.capitalize())}),
                                      _("Play"), _("Retry"), image=self.im_info)
            if rep2 == _("Play"):
                self.level = diff
                self.affiche_grille(grille.get_sudoku())

    def recommence(self):
        if self.chrono_on:
            self.play_pause()
        rep = _("Yes")
        if self.debut:
            rep = two_button_box(self, _("Confirmation"),
                                 _("Do you really want to start again?"),
                                 _("Yes"), _("No"), self.im_question)
        if rep == _("Yes"):
            self.reset_nbs()
            for i in range(9):
                for j in range(9):
                    if self.blocs[i, j].is_modifiable():
                        if self.blocs[i, j].get_val():
                            self.nb_cases_remplies -= 1
                        self.blocs[i, j].efface_case()
                    else:
                        self.update_nbs(self.blocs[i, j].get_val(), 1)
            self.restart()
        elif self.debut:
            self.play_pause()

    def save(self, path):
        grille = np.zeros((9, 9), dtype=int)
        modif = np.zeros((9, 9), dtype=bool)
        possibilites = []
        for i in range(9):
            possibilites.append([])
            for j in range(9):
                grille[i, j] = self.blocs[i, j].get_val()
                modif[i, j] = self.blocs[i, j].is_modifiable()
                possibilites[i].append(self.blocs[i, j].get_possibilites())
        with open(path, "wb") as fich:
            p = Pickler(fich)
            p.dump(grille)
            p.dump(modif)
            p.dump(possibilites)
            p.dump(self.chrono)
            p.dump(self.level)

    def sauvegarde(self):
        if self.chrono_on:
            self.play_pause()
        fichier = asksaveasfilename(initialdir=cst.INITIALDIR,
                                    defaultextension='.sudoku',
                                    filetypes=[('Sudoku', '*.sudoku')])
        if fichier:
            self.save(fichier)

    def affiche_grille(self, grille):
        """ Affiche la grille """
        self.nb_cases_remplies = 0
        self.restart()
        self.reset_nbs()
        for i in range(9):
            for j in range(9):
                nb = grille[i, j]
                self.blocs[i, j].efface_case()
                if nb:
                    self.blocs[i, j].set_modifiable(False)
                    self.nb_cases_remplies += 1
                    self.blocs[i, j].edit_chiffre(nb)
                else:
                    self.blocs[i, j].set_modifiable(True)

    def load_sudoku(self, file):
        with open(file, "rb") as fich:
            dp = Unpickler(fich)
            grille = dp.load()
            modif = dp.load()
            possibilites = dp.load()
            chrono = dp.load()
            self.level = dp.load()
        self.nb_cases_remplies = 0
        self.reset_nbs()
        self.restart(*chrono)
        for i in range(9):
            for j in range(9):
                self.blocs[i, j].efface_case()
                if grille[i, j]:
                    self.nb_cases_remplies += 1
                    self.blocs[i, j].edit_chiffre(grille[i, j])
                else:
                    for pos in possibilites[i][j]:
                        self.blocs[i, j].edit_possibilite(pos)
                self.blocs[i, j].set_modifiable(modif[i, j])

    def import_partie(self):
        """ importe une partie stockée dans un fichier .sudoku """
        if self.chrono_on:
            self.play_pause()
        rep = _("Yes")
        if self.debut:
            rep = two_button_box(self, _("Confirmation"),
                                 _("Do you want to abandon the current puzzle?"),
                                 _("Yes"), _("No"), self.im_question)
        if rep == _("Yes"):
            fichier = askopenfilename(initialdir=cst.INITIALDIR,
                                      defaultextension='.sudoku',
                                      filetypes=[('Sudoku', '*.sudoku')])
            if fichier:
                try:
                    self.load_sudoku(fichier)
                except FileNotFoundError:
                    one_button_box(self, _("Error"),
                                   _("The file %(file)r does not exist.") % fichier,
                                   image=self.im_erreur)
                except (KeyError, EOFError, UnpicklingError):
                    one_button_box(self, _("Error"),
                                   _("This file is not a valid sudoku file."),
                                   image=self.im_erreur)
        elif self.debut:
            self.play_pause()

    def resolution_init(self):
        """ Résolution de la grille initiale (sans tenir compte des valeurs rentrées par l'utilisateur. """
        grille = Grille()
        for i in range(9):
            for j in range(9):
                if not self.blocs[i, j].is_modifiable():
                    val = self.blocs[i, j].get_val()
                    grille.ajoute_init(i, j, val)
        self.configure(cursor="watch")
        self.update()
        sol = grille.solve()
        self.configure(cursor="")
        if type(sol) == np.ndarray:
            for i in range(9):
                for j in range(9):
                    val = self.blocs[i, j].get_val()
                    if not val:
                        self.blocs[i, j].edit_chiffre(sol[i, j])
                        self.blocs[i, j].affiche_solution()
                    elif self.blocs[i, j].is_modifiable():
                        if val != sol[i, j]:
                            self.blocs[i, j].edit_chiffre(sol[i, j])
                            self.blocs[i, j].affiche_erreur()
            self.restart()
            self.nb_cases_remplies = 81

        elif sol[1]:
            i, j = sol[1]
            if self.blocs[i, j].get_val():
                self.blocs[i, j].affiche_erreur()
            one_button_box(self, _("Error"), _("The grid is wrong. It cannot be solved."),
                           image=self.im_erreur)
        else:
            one_button_box(self, _("Error"), _("Resolution failed."),
                           image=self.im_erreur)

    def resolution(self):
        if self.chrono_on:
            self.play_pause()
        rep = two_button_box(self, _("Confirmation"),
                             _("Do you really want to get the solution?"),
                             _("Yes"), _("No"), image=self.im_question)
        if rep == _("Yes"):
            self.frame_pause.place_forget()
            grille = Grille()
            for i in range(9):
                for j in range(9):
                    val = self.blocs[i, j].get_val()
                    if val:
                        grille.ajoute_init(i, j, val)
            self.configure(cursor="watch")
            self.update()
            sol = grille.solve()
            self.configure(cursor="")
            if type(sol) == np.ndarray:
                for i in range(9):
                    for j in range(9):
                        val = self.blocs[i, j].get_val()
                        if not val:
                            self.blocs[i, j].edit_chiffre(sol[i, j])
                            self.blocs[i, j].affiche_solution()
                self.restart()
                self.b_restart.configure(state="normal")
                self.nb_cases_remplies = 81
            elif sol[1]:
                i, j = sol[1]
                if self.blocs[i, j].get_val():
                    self.blocs[i, j].affiche_erreur()
                i, j = 0, 0
                while i < 9 and self.blocs[i, j].is_modifiable():
                    j += 1
                    if j == 9:
                        i += 1
                        j = 0
                if i < 9:
                    # il y a au moins une case de type "initial"
                    rep = two_button_box(self, _("Error"),
                                         _("The grid is wrong. It cannot be solved. Do you want the solution of the initial grid?"),
                                         _("Yes"), _("No"), image=self.im_erreur)
                    if rep == _("Yes"):
                        self.resolution_init()
                else:
                    one_button_box(self, _("Error"), _("The grid is wrong. It cannot be solved."),
                                   image=self.im_erreur)
            else:
                one_button_box(self, _("Error"), _("Resolution failed."),
                               image=self.im_erreur)

    def load_grille(self, file):
        gr = np.loadtxt(file, dtype=int)
        if gr.shape == (9, 9):
            self.affiche_grille(gr)
            self.level = "unknown"
        else:
            one_button_box(self, _("Error"), _("This is not a 9x9 sudoku grid."),
                           image=self.im_erreur)

    def import_grille(self, fichier=None):
        """ importe une grille stockée dans un fichier txt sous forme de
            chiffres séparés par des espaces (0 = case vide) """
        if self.chrono_on:
            self.play_pause()
        rep = _("Yes")
        if self.debut:
            rep = two_button_box(self, _("Confirmation"),
                                 _("Do you want to abandon the current puzzle?"),
                                 _("Yes"), _("No"), self.im_question)
        if rep == _("Yes"):
            if not fichier:
                fichier = askopenfilename(initialdir=cst.INITIALDIR,
                                          defaultextension='.txt',
                                          filetypes=[('Text', '*.txt'), ('Tous les fichiers', "*")])
            if fichier:
                try:
                    self.load_grille(fichier)
                except (ValueError, UnicodeDecodeError):
                    one_button_box(self, _("Error"),
                                   _("The file does not have the right format. It should be a .txt file with cell values separated by one space. 0 means empty cell."),
                                   image=self.im_erreur)
                except FileNotFoundError:
                    one_button_box(self, _("Error"),
                                   _("The file %(file)r does not exist.") % fichier,
                                   image=self.im_erreur)
        elif self.debut:
            self.play_pause()

    def export_impression(self):
        """ exporte la grille en image (pour pouvoir l'imprimer) """
        if self.chrono_on:
            self.play_pause()
        fichier = asksaveasfilename(title=_("Export"),
                                    initialdir=cst.INITIALDIR,
                                    defaultextension='.png',
                                    filetypes=[('PNG', '*.png'),
                                               ('JPEG', 'jpg')])
        if fichier:
            grille = np.zeros((9, 9), dtype=int)
            for i in range(9):
                for j in range(9):
                    grille[i, j] = self.blocs[i, j].get_val()
            font = ImageFont.truetype("arial.ttf", 64)
            im = Image.new("RGB", (748, 748), "white")
            draw = ImageDraw.Draw(im)
            i = 0
            l = 1
            while i < 10:
                if i % 3 == 0:
                    w = 4
                else:
                    w = 2
                draw.line((l, 1, l, 748), width=w, fill="black")
                draw.line((1, l, 748, l), width=w, fill="black")
                l += 80 + w
                i += 1

            for i in range(9):
                for j in range(9):
                    if grille[i, j]:
                        draw.text((26 + j * 82 + 2 * (j // 3),
                                   10 + i * 82 + 2 * (i // 3)),
                                  " %i" % grille[i, j], fill="black", font=font)

            del draw
            im.save(fichier)
Exemplo n.º 43
0
    def __init__(self, mainWin, options, reportType, endDate):
        self.reportType = reportType
        self.mainWin = mainWin
        self.endDate = endDate
        parent = mainWin
        super(DialogCssfSaveOptions, self).__init__(parent)
        self.parent = parent
        self.options = options
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False
        self.accountingVersionValues = ACCOUNTING_VERSION_VALUES
        if reportType == SCOREP_REPORT:
            self.accountingVersionValues = self.accountingVersionValues + ACCOUNTING_SUBSIDIARY

        self.transient(self.parent)
        self.title(_("Save As CSSF Options"))
        
        frame = Frame(self)

        label(frame, 1, 1, _("Entity type:"))
        self.cellEntityType = gridCombobox(frame, 2, 1, getattr(options,"entityType",""), values=COMPANY_TYPE_VALUES)
        ToolTip(self.cellEntityType, text=_("Select an entity type"), wraplength=240)
        label(frame, 1, 2, _("CSSF entity code:"))
        self.cellCssfCode = gridCell(frame, 2, 2, getattr(options,"cssfCode",""))
        ToolTip(self.cellCssfCode, text=_("Enter a CSSF entity code (up to {0} digits)").format(CSSF_CODE_LENGTH), wraplength=240)
        currentRow = 3
        if reportType.endswith(COREP_REPORT_SUFFIX):
            label(frame, 1, currentRow, _("Ratio type:"))
            defaultValue = getattr(options, "ratioType","")
            if defaultValue not in RATIO_TYPE_VALUES:
                defaultValue = RATIO_TYPE_VALUES[0]
            self.cellRatioType = gridCombobox(frame, 2, currentRow, defaultValue, values=RATIO_TYPE_VALUES)
            ToolTip(self.cellRatioType, text=_("Select how the ratios are computed"), wraplength=240)
            currentRow += 1
        if reportType[0] != CONSOLIDATED_REPORT_PREFIX:
            label(frame, 1, currentRow, _("Accounting version:"))
            defaultValue = getattr(options, "accountingVersion", "")
            if defaultValue not in self.accountingVersionValues:
                defaultValue = ACCOUNTING_VERSION_DEFAULT
            self.cellAccountingVersion = gridCombobox(frame, 2, currentRow, defaultValue, values=self.accountingVersionValues)
            ToolTip(self.cellAccountingVersion, text=_("Select the accounting version"), wraplength=240)
            currentRow += 1
        if reportType == FINREP_REPORT:
            label(frame, 1, currentRow, _("Figures type:"))
            self.cellFiguresType = gridCombobox(frame, 2, currentRow, getattr(options,"figuresType",""), values=FIGURES_TYPE_VALUES)
            ToolTip(self.cellFiguresType, text=_("Select a figures type"), wraplength=240)
            currentRow += 1

        cancelButton = Button(frame, text=_("Cancel"), width=8, command=self.close)
        ToolTip(cancelButton, text=_("Cancel operation, discarding changes and entries"))
        okButton = Button(frame, text=_("OK"), width=8, command=self.ok)
        ToolTip(okButton, text=_("Accept the options as entered above"))
        cancelButton.grid(row=currentRow, column=1, columnspan=3, sticky=E, pady=3, padx=3)
        okButton.grid(row=currentRow, column=1, columnspan=3, sticky=E, pady=3, padx=86)
        
        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(2, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
Exemplo n.º 44
0
    def __init__(self, mainWin):
        self.mainWin = mainWin
        parent = mainWin
        super(DialogNewFileOptions, self).__init__(parent)
        self.parent = parent
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False
        
        self.ebaTaxonomyVersion = EBA_TAXONOMY_DEFAULT_VERSION
        self.ebaReportingType = EBA_REPORTING_TYPE_DEFAULT
        self.setEntryPoints()
        self.ebaEntryPointKey = self.ebaEntryPointValues[0]
        self.options = EbaNewFileOptions(self.ebaTaxonomyVersion, self.ebaReportingType,
                                         self.ebaEntryPointValues[0])
        
        options = self.options

        self.transient(self.parent)
        self.title(_("New EBA File"))
        
        frame = Frame(self)
        frame.focus_set()
        
        label(frame, 1, 1, _("Taxonomy version:"))
        self.cellTaxonomyVersion = gridCombobox(frame, 2, 1, getattr(options,"ebaTaxonomyVersion", ""),
                                           values=EBA_TAXONOMY_VERSIONS_VALUES,
                                           comboboxselected = self.onTaxonomyVersionChanged,
                                           width=40)
        ToolTip(self.cellTaxonomyVersion, text=_("Select a taxonomy version"), wraplength=240)

        label(frame, 1, 2, _("EBA reporting type:"))
        self.cellReportType = gridCombobox(frame, 2, 2, getattr(options,"ebaReportingType", ""),
                                           values=EBA_REPORTING_TYPES_VALUES,
                                           comboboxselected = self.onReportTypeChanged,
                                           width=40)
        ToolTip(self.cellReportType, text=_("Select a report type"), wraplength=240)
        label(frame, 1, 3, _("Entry point:"))
        self.cellEntryPoint = gridCombobox(frame, 2, 3, getattr(options,"ebaEntryPointKey", ""),
                                           values=self.ebaEntryPointValues,
                                           comboboxselected = self.onEntryPointChanged,
                                           width=40)
        ToolTip(self.cellEntryPoint, text=_("Select an EBA entry point"), wraplength=240)
        currentRow = 4
        
        self.setEntryPointsCombo()


        cancelButton = Button(frame, text=_("Cancel"), width=8, command=self.close)
        ToolTip(cancelButton, text=_("Cancel operation"))
        okButton = Button(frame, text=_("New"), width=8, command=self.ok)
        ToolTip(okButton, text=_("Create a new file"))
        cancelButton.grid(row=currentRow, column=1, columnspan=3, sticky=E, pady=3, padx=3)
        okButton.grid(row=currentRow, column=1, columnspan=3, sticky=E, pady=3, padx=86)
        
        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(2, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
Exemplo n.º 45
0
    def initui(self):

        self.parent.title("Light pollution map")
        self.style = Style()
        self.style.theme_use("alt")

        self.grid(row=0, column=0)

        padding = {'padx':'5', 'pady':'5'}
        big_heading_font = ("Arial", 14, 'bold')
        small_heading_font = ("Arial", 10, 'bold')

        # Create frames.
        # There are three frames for settings - preprocessing, convolve, and contour.
        # Each also has an image frame underneath it.
        # Layout is as follows:
        #
        #             --------------------------------------------------------------------------
        #             |                 |                 |                 |                  |
        #             |                 |                 |                 |                  |
        #             |   import_body   |   process_body  |   contour_body  |   export_body    |
        #             |                 |                 |                 |                  |
        #             |                 |                 |                 |                  |
        #             --------------------------------------------------------------------------

        # Settings frames

        top = self.winfo_toplevel()
        top.rowconfigure(0, weight=1)
        top.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=1)
        self.columnconfigure(2, weight=1)
        self.columnconfigure(3, weight=1)

        import_body = Frame(self, relief=RAISED, borderwidth=1)
        import_body.grid(row=0, column=0, sticky=N+S+E+W)

        process_body = Frame(self, relief=RAISED, borderwidth=1)
        process_body.grid(row=0, column=1, sticky=N+S+E+W)

        contour_body = Frame(self, relief=RAISED, borderwidth=1)
        contour_body.grid(row=0, column=2, sticky=N+S+E+W)

        export_body = Frame(self, relief=RAISED, borderwidth=1)
        export_body.grid(row=0, column=3, sticky=N+S+E+W)

         # =============================================================================================================
        #
        # Contents of load_image_frame
        #
        # =============================================================================================================

        # Heading

        processing_frame_header = Label(import_body, text="Import", font=big_heading_font)
        processing_frame_header.grid(row=0, column=0, sticky=N, **padding)

        filename_variable = StringVar()

        # Import image

        import_canvas = Canvas(import_body, width=canvas_size, height=canvas_size, background='black')
        import_canvas.grid(row=1, column=0, sticky=N, **padding)

        # Load file method

        def choosefile():
            filename_variable.set(filedialog.askopenfilename(parent=import_body))
            image = Image.open(filename_variable.get())
            thumbnail = create_thumbnail(image, canvas_size)
            import_canvas.create_image(0, 0, image=thumbnail, anchor=NW)

        load_image_button = Button(import_body, text="Import image", command=choosefile)
        load_image_button.grid(row=2, column=0, columnspan=2, sticky=E+W+S, **padding)
        import_body.rowconfigure(2, weight=1)

        # =============================================================================================================
        #
        # Contents of processing_frame
        #
        # =============================================================================================================

        processing_frame_header = Label(process_body, text="Process", font=big_heading_font)
        processing_frame_header.grid(row=0, column=0, columnspan=2, sticky=N, **padding)

        clipping_variable = IntVar()

        constants_label = Label(process_body, text="Clipping",
                                font=("Arial", 10, 'bold'))
        constants_label.grid(row=1, column=0, sticky=E, **padding)

        clipping_label = Label(process_body, text="Remove pixels with \n brightness under")
        clipping_label.grid(row=2, column=0, sticky=E, **padding)

        clipping_entry = Entry(process_body, textvariable=clipping_variable, width=4)
        clipping_entry.grid(row=2, column=1, sticky=W, **padding)

        clipping_variable.set(value=default_clipping_value)

        convolve_header = Label(process_body, text="Kernel", font=small_heading_font)
        convolve_header.grid(row=4, column=0, sticky=E, **padding)

        kernel_size_variable = IntVar()

        kernel_size_label = Label(process_body, text="Convolve kernel size", justify=RIGHT)
        kernel_size_label.grid(row=5, column=0, sticky=E, **padding)

        kernel_size_entry = Entry(process_body, textvariable=kernel_size_variable, width=4)
        kernel_size_entry.grid(row=5, column=1, sticky=W, **padding)
        kernel_size_variable.set(value=default_kernel_size)

        # Constants for convolve equation

        constants_label = Label(process_body, text="Falloff",
                                font=("Arial", 10, 'bold'))
        constants_label.grid(row=6, column=0, sticky=E, **padding)

        constant_a_label = Label(process_body, text="Constant A:")
        constant_b_label = Label(process_body, text="Constant B:")
        constant_c_label = Label(process_body, text="Constant C:")

        constant_a_label.grid(row=7, column=0, sticky=E, **padding)
        constant_b_label.grid(row=8, column=0, sticky=E, **padding)
        constant_c_label.grid(row=9, column=0, sticky=E, **padding)

        constant_a_variable = DoubleVar()
        constant_b_variable = DoubleVar()
        constant_c_variable = DoubleVar()

        constant_a_entry = Entry(process_body, textvariable=constant_a_variable, width=4)
        constant_b_entry = Entry(process_body, textvariable=constant_b_variable, width=4)
        constant_c_entry = Entry(process_body, textvariable=constant_c_variable, width=4)

        constant_a_variable.set(default_constant_a)
        constant_b_variable.set(default_constant_b)
        constant_c_variable.set(default_constant_c)

        constant_a_entry.grid(row=7, column=1, **padding)
        constant_b_entry.grid(row=8, column=1, **padding)
        constant_c_entry.grid(row=9, column=1, **padding)

        constants_note = Label(process_body, text="Falloff equation is (Ax^B)-C", font=("Arial", 9))
        constants_note.grid(row=10, column=0, columnspan=2, sticky=E, **padding)

        # Start button!

        def process():
            print("Filename was " + filename_variable.get())
            image_data =  process_image(filename=filename_variable.get(),
                                        kernel_size=kernel_size_variable.get(),
                                        clipping_value=clipping_variable.get(),
                                        constant_a=constant_a_variable.get(),
                                        constant_b=constant_b_variable.get(),
                                        constant_c=constant_c_variable.get()
                                        )

            image_data = Image.open("processed_image.png")
            thumbnail = create_thumbnail(image_data, canvas_size)
            export_canvas.create_image(0, 0, image=thumbnail, anchor=NW)

        start_button = Button(process_body, text="Process image", command=process)
        start_button.grid(row=11, column=0, columnspan=3, sticky=E+W+S, **padding)
        process_body.rowconfigure(11, weight=1)

        # =============================================================================================================
        #
        # Contents of contour_frame
        #
        # =============================================================================================================

        contour_header = Label(contour_body, text="Contour", font=big_heading_font)
        contour_header.grid(row=0, column=0, sticky=S, columnspan=2, **padding)

        contour_note = Label(contour_body, text="(optional)")
        contour_note.grid(row=1, column=0, sticky=S, columnspan=2)

        scale_options = {"width":"5", "length":"150"}
        slider_padding = {"padx":"2", "pady":"0"}

        scale_list = []
        scale_values_list = []

        default_scale_values = [5, 7, 10, 20, 30, 40, 60, 100, 200]

        for i in range(9):
            scale = Scale(contour_body, from_=0, to_=255, orient=HORIZONTAL, **scale_options)
            scale.grid(row=i+2, column=0, columnspan=2, sticky=S, **slider_padding)
            scale.set(default_scale_values[i])
            scale_list.append(scale)

        for scale in scale_list:
            print(scale)
            print(type(scale))
            #print(scale.get())

        def contour():

            scale_values_list.clear()

            for scale in scale_list:
                scale_values_list.append(scale.get())

            contour_image(scale_values_list)

            image_data = Image.open("Contoured_image.png")
            thumbnail = create_thumbnail(image_data, canvas_size)
            export_canvas.create_image(0, 0, image=thumbnail, anchor=NW)

        contour_button = Button(contour_body, text="Contour image", command=contour)
        contour_button.grid(row=11, column=0, columnspan=2, sticky=E+S+W, **padding)
        contour_body.rowconfigure(11, weight=1)
        contour_body.columnconfigure(1, weight=1)

        # =============================================================================================================
        #
        # Contents of export_body
        #
        # =============================================================================================================

        filename_export_variable = StringVar()

        def export_file():
            filename_options = {}
            filename_options['filetypes'] = [('PNG', '.png')]
            filename_options['initialfile'] = 'output.png'
            filename_options['parent'] = self
            filename_export_variable.set(filedialog.asksaveasfilename(**filename_options))
            image_data = Image.open("Contoured_image.png")
            image_data.save(filename_export_variable.get())

        export_header = Label(export_body, text="Export", font=big_heading_font)
        export_header.grid(row=0, column=0, sticky=N, **padding)

        export_canvas = Canvas(export_body, width=canvas_size, height=canvas_size, background='black')
        export_canvas.grid(row=1, column=0, **padding)

        export_button = Button(export_body, text="Export image", command=export_file)
        export_button.grid(row=2, column=0, columnspan=2, sticky=E+W+S, **padding)
        export_body.rowconfigure(2, weight=1)
Exemplo n.º 46
0
    def __init__(self, mainWin, options):
        self.mainWin = mainWin
        parent = mainWin.parent
        super(DialogRssWatch, self).__init__(parent)
        self.parent = parent
        self.options = options
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False

        self.transient(self.parent)
        self.title(_("RSS Feed Processing Control"))
        
        frame = Frame(self)

        # checkbox entries
        label(frame, 1, 1, "RSS Feed:")
        feedSources = sorted(rssFeeds.keys())
        self.cellFeed = gridCombobox(frame, 2, 1, options.get("feedSource",""), values=feedSources)
        self.cellFeed.grid(pady=2)
        ToolTip(self.cellFeed, text=_("Select an RSS feed to process for item matching, formulas, and validations as selected below"), wraplength=240)
        label(frame, 1, 2, "Match fact text:")
        self.cellMatchText = gridCell(frame, 2, 2, options.get("matchTextExpr",""))
        ToolTip(self.cellMatchText, text=_("Enter a regular expression to be matched to the text of each filing instance fact item. "
                                           "Regular expressions may contain patterns to detect, such as ab.?c, for any single character between b and c, or ab.*c for any number of characters between b and c."), wraplength=240)
        label(frame, 1, 3, "Formula file:")
        self.cellFormulaFile = gridCell(frame,2, 3, options.get("formulaFileUri",""))
        ToolTip(self.cellFormulaFile, text=_("Select a formula linkbase to to evaluate each filing.  "
                                             "The formula linkbase may contain one or more assertions, the results of which is recorded in the log file.  "
                                             "If unsuccessful assertion alerts are selected and an e-mail address provided, the recipient will be notified of filings with assertions that do not pass."), wraplength=240)
        openFileImage = PhotoImage(file=os.path.join(mainWin.imagesDir, "toolbarOpenFile.gif"))
        chooseFormulaFileButton = Button(frame, image=openFileImage, width=12, command=self.chooseFormulaFile)
        chooseFormulaFileButton.grid(row=3, column=3, sticky=W)
        label(frame, 1, 4, "Log file:")
        self.cellLogFile = gridCell(frame,2, 4, options.get("logFileUri",""))
        ToolTip(self.cellLogFile, text=_("Select a log file in which to save an activity log, including validation results, matched item text, and formula results.\n\n "
                                         "Two files are produced, (1) .txt with the log messages, and (2) .csv with the RSS feed items and status.  "), wraplength=240)
        chooseLogFileButton = Button(frame, image=openFileImage, width=12, command=self.chooseLogFile)
        chooseLogFileButton.grid(row=4, column=3, sticky=W)
        label(frame, 1, 5, "E-mail alerts to:")
        self.cellEmailAddress = gridCell(frame,2, 5, options.get("emailAddress",""))
        ToolTip(self.cellEmailAddress, text=_("Specify e-mail recipient(s) for alerts per below."), wraplength=240)
        label(frame, 1, 6, "Latest pub date:")
        pubdate = getattr(options,"latestPubDate",None)
        self.cellLatestPubDate = gridCell(frame,2, 6, str(pubdate) if pubdate else "")
        ToolTip(self.cellLatestPubDate, text=_("Specify pub dateTime of last processed submission.  Next item to examine will be after this dateTime."), wraplength=240)
        clearImage = PhotoImage(file=os.path.join(mainWin.imagesDir, "toolbarDelete.gif"))
        clearPubDateButton = Button(frame, image=clearImage, width=12, command=self.clearPubDate)
        clearPubDateButton.grid(row=6, column=3, sticky=W)
        ToolTip(clearPubDateButton, text=_("Clear pub dateTime so that next cycle processes all entries in RSS feed."), wraplength=240)
        label(frame, 2, 7, "Validate:")
        label(frame, 2, 12, "Alert on:")
        self.checkboxes = (
           checkbox(frame, 2, 8, 
                    "XBRL 2.1 and Dimensions rules", 
                    "validateXbrlRules"),
           checkbox(frame, 2, 9, 
                    "Selected disclosure system rules", 
                    "validateDisclosureSystemRules"),
           checkbox(frame, 2, 10,
                    "Calculation linkbase roll-up", 
                    "validateCalcLinkbase"),
           checkbox(frame, 2, 11,
                    "Formula assertions", 
                    "validateFormulaAssertions"),
           checkbox(frame, 2, 13, 
                    "Facts with matching text", 
                    "alertMatchedFactText"),
           checkbox(frame, 2, 14,
                    "Unsuccessful formula assertions", 
                    "alertAssertionUnsuccessful"),
           checkbox(frame, 2, 15, 
                    "Validation errors", 
                    "alertValiditionError"),

        
           # Note: if adding to this list keep ModelFormulaObject.FormulaOptions in sync
        
           )
        
        mainWin.showStatus(None)

        cancelButton = Button(frame, text=_("Cancel"), width=8, command=self.close)
        ToolTip(cancelButton, text=_("Cancel operation, discarding changes and entries"))
        okButton = Button(frame, text=_("OK"), width=8, command=self.ok)
        ToolTip(okButton, text=_("Accept the options as entered above"))
        cancelButton.grid(row=16, column=1, columnspan=3, sticky=E, pady=3, padx=3)
        okButton.grid(row=16, column=1, columnspan=3, sticky=E, pady=3, padx=86)
        
        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(2, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        
        #self.bind("<Return>", self.ok)
        #self.bind("<Escape>", self.close)
        
        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
Exemplo n.º 47
0
class Vidget(object):
    """
    Vidget contains a widget, instead of being a widget itself using
    inheritance. The benefit is that `An editor has a GUI` is more natural than
    `An editor is a GUI`.

    Vidget delegates widget-related methods, e.g. `grid`, `pack`, and `place`,
    to the widget contained, so that the Vidget object can be used just like a
    widget.
    """

    def __init__(
        self,
        master=None,
        widget=None,
        config_target=None,
    ):
        """
        Initialize object.

        @param master: Master widget.

        @param widget: Main widget. If not given, will create a Frame widget.

        @param config_target: The widget to call `config` method on. Default is
        the main widget.

        @return: None.
        """
        # Master widget
        self._vidget_master = master

        # Config target widget
        self._vidget_config_target = config_target

        # If main widget is given
        if widget is not None:
            # Set main widget
            self._vidget_widget = widget

        # If main widget is not given
        else:
            # Create default main Frame widget
            self._vidget_widget = Frame(master=master)

            # Configure children layout weights
            self._vidget_widget.rowconfigure(0, weight=1)

            self._vidget_widget.columnconfigure(0, weight=1)

    def master(self):
        """
        Get the master widget.

        @return: Master widget.
        """
        # Return the master widget
        return self._vidget_master

    def widget(self):
        """
        Get the main widget.

        @return: Main widget.
        """
        # Return the main widget
        return self._vidget_widget

    def config(self, *args, **kwargs):
        """
        Call `config` method on the config target widget.

        @param args: Positional arguments.

        @param kwargs: Keyword arguments.

        @return: Calls result.
        """
        # Call `config` method on the config target widget
        return self.config_target().config(*args, **kwargs)

    def config_target(self):
        """
        Get the config target widget.

        @return: Config target widget. Default is the main widget.
        """
        # If the config target widget is given
        if self._vidget_config_target is not None:
            # Return the config target widget
            return self._vidget_config_target

        # If the config target widget is not given
        else:
            # Return the main widget
            return self.widget()

    def config_target_set(self, target):
        """
        Set the config target widget.

        @param target: Config target widget. `None` means the main widget.

        @return: None.
        """
        # Set the config target widget
        self._vidget_config_target = target

    def state(self, *args, **kwargs):
        """
        Call `state` method on the config target widget.

        @param args: Positional arguments.

        @param kwargs: Keyword arguments.

        @return: Call result.
        """
        # Call `state` method on the config target widget
        return self.config_target().state(*args, **kwargs)

    def instate(self, *args, **kwargs):
        """
        Call `instate` method on the config target widget.

        @param args: Positional arguments.

        @param kwargs: Keyword arguments.

        @return: Call result.
        """
        # Call `instate` method on the config target widget
        return self.config_target().instate(*args, **kwargs)

    def bind(self, *args, **kwargs):
        """
        Call `bind` method on the config target widget.

        @param args: Positional arguments.

        @param kwargs: Keyword arguments.

        @return: Call result.
        """
        # Call `bind` method on the config target widget
        return self.config_target().bind(*args, **kwargs)

    def tkraise(self, *args, **kwargs):
        """
        Call `tkraise` method on the main widget.

        @param args: Positional arguments.

        @param kwargs: Keyword arguments.

        @return: Call result.
        """
        # Call `tkraise` method on the main widget
        return self.widget().tkraise(*args, **kwargs)

    def lower(self, *args, **kwargs):
        """
        Call `lower` method on the main widget.

        @param args: Positional arguments.

        @param kwargs: Keyword arguments.

        @return: Call result.
        """
        # Call `lower` method on the main widget
        return self.widget().lower(*args, **kwargs)

    def grid(self, *args, **kwargs):
        """
        Call `grid` method on the main widget.

        @param args: Positional arguments.

        @param kwargs: Keyword arguments.

        @return: Call result.
        """
        # Call `grid` method on the main widget
        return self.widget().grid(*args, **kwargs)

    def pack(self, *args, **kwargs):
        """
        Call `pack` method on the main widget.

        @param args: Positional arguments.

        @param kwargs: Keyword arguments.

        @return: Call result.
        """
        # Call `pack` method on the main widget
        return self.widget().pack(*args, **kwargs)

    def place(self, *args, **kwargs):
        """
        Call `place` method on the main widget.

        @param args: Positional arguments.

        @param kwargs: Keyword arguments.

        @return: Call result.
        """
        # Call `place` method on the main widget
        return self.widget().place(*args, **kwargs)

    def grid_forget(self):
        """
        Call `grid_forget` method on the main widget.

        @return: Call result.
        """
        # Call `grid_forget` method on the main widget
        return self.widget().grid_forget()

    def grid_propagate(self, value):
        """
        Call `grid_propagate` method on the main widget.

        @param value: Whether propagate.

        @return: Call result.
        """
        # Call `grid_propagate` method on the main widget
        return self.widget().grid_propagate(value)

    def pack_forget(self):
        """
        Call `pack_forget` method on the main widget.

        @return: Call result.
        """
        # Call `pack_forget` method on the main widget
        return self.widget().pack_forget()

    def pack_propagate(self, value):
        """
        Call `pack_propagate` method on the main widget.

        @param value: Whether propagate.

        @return: Call result.
        """
        # Call `pack_propagate` method on the main widget
        return self.widget().pack_propagate(value)

    def place_forget(self):
        """
        Call `place_forget` method on the main widget.

        @return: Call result.
        """
        # Call `place_forget` method on the main widget
        return self.widget().place_forget()

    def destroy(self):
        """
        Call `destroy` method on the main widget.

        @return: Call result.
        """
        # Call `destroy` method on the main widget
        return self.widget().destroy()

    def after(self, *args, **kwargs):
        """
        Call `after` method on the main widget.

        @param args: Positional arguments.

        @param kwargs: Keyword arguments.

        @return: Call result.
        """
        # Call `after` method on the main widget
        return self.widget().after(*args, **kwargs)
Exemplo n.º 48
0
 def __init__(self, mainWin):
     super(DialogLanguage, self).__init__(mainWin.parent)
     self.mainWin = mainWin
     self.parent = mainWin.parent
     parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", self.parent.geometry())
     dialogX = int(parentGeometry.group(3))
     dialogY = int(parentGeometry.group(4))
     self.transient(self.parent)
     self.title(_("arelle - User Interface and Labels language code settings"))
     self.languageCodes = languageCodes()
     langs = (["System default language ({0})".format(mainWin.modelManager.defaultLang)] +
              sorted(self.languageCodes.keys() if self.mainWin.isMSW else
                     [k 
                      for avail in [availableLocales()] # unix/Mac locale -a supported locale codes
                      for k, v in self.languageCodes.items()
                      if v.partition(" ")[0] in avail]
                     ))
     self.uiLang = mainWin.config.get("userInterfaceLangOverride", "")
     if self.uiLang == "" or self.uiLang == mainWin.modelManager.defaultLang:
         self.uiLangIndex = 0
     else:
         self.uiLangIndex = None
         for i, langName in enumerate(langs):
             if i > 0 and self.uiLang in self.languageCodes[langName]:
                 self.uiLangIndex = i
                 break
     self.labelLang = mainWin.config.get("labelLangOverride", "")
     if self.labelLang == "" or self.labelLang == mainWin.modelManager.defaultLang:
         self.labelLangIndex = 0
     else:
         self.labelLangIndex = None
         for i, langName in enumerate(langs):
             if i > 0 and self.labelLang in self.languageCodes[langName]:
                 self.labelLangIndex = i
                 break
     
     frame = Frame(self)
     
     defaultLanguage = mainWin.modelManager.defaultLang
     for langName, langCodes in self.languageCodes.items():
         if mainWin.modelManager.defaultLang in langCodes:
             defaultLanguage += ", " + langName
             break
     gridHdr(frame, 0, 0, _(
              "The system default language is: {0} \n\n"
              "You may override with a different language for user interface language and locale settings, and for language of taxonomy linkbase labels to display. \n\n").format(
             defaultLanguage),
           columnspan=5, wraplength=400)
     label(frame, 0, 1, _("User Interface:"))
     self.cbUiLang = gridCombobox(frame, 1, 1, values=langs, selectindex=self.uiLangIndex, columnspan=4)
     label(frame, 0, 2, _("Labels:"))
     self.cbLabelLang = gridCombobox(frame, 1, 2, values=langs, selectindex=self.labelLangIndex, columnspan=4)
     self.cbUiLang.focus_set()
     okButton = Button(frame, text=_("OK"), command=self.ok)
     cancelButton = Button(frame, text=_("Cancel"), command=self.close)
     okButton.grid(row=3, column=2, sticky=E, pady=3)
     cancelButton.grid(row=3, column=3, columnspan=2, sticky=EW, pady=3, padx=3)
     frame.grid(row=0, column=0, sticky=(N,S,E,W))
     frame.columnconfigure(1, weight=1)
     window = self.winfo_toplevel()
     window.columnconfigure(0, weight=1)
     self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
     
     self.bind("<Return>", self.ok)
     self.bind("<Escape>", self.close)
     
     self.protocol("WM_DELETE_WINDOW", self.close)
     self.grab_set()
     self.wait_window(self)
Exemplo n.º 49
0
    def __init__(self, mainWin, options):
        parent = mainWin.parent
        self.modelManager = mainWin.modelManager
        super(DialogFormulaParameters, self).__init__(parent)
        self.parent = parent
        self.options = options
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False

        self.transient(self.parent)
        self.title(_("Formula Parameters and Trace Options"))
        
        frame = Frame(self)

        '''
        dialogFrame = Frame(frame, width=500)
        dialogFrame.columnconfigure(0, weight=1)
        dialogFrame.rowconfigure(0, weight=1)
        dialogFrame.grid(row=0, column=0, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        '''
        
        # mainWin.showStatus(_("loading formula options and parameters"))
        
        # load grid
        gridHdr(frame, 1, 0, "Parameters", columnspan=3)
        gridHdr(frame, 1, 1, "QName")
        gridHdr(frame, 2, 1, "Type")
        gridHdr(frame, 3, 1, "Value")
        
        self.gridCells = []
        y = 2
        dataTypes = ("xs:string", "xs:integer", "xs:decimal", "xs:boolean", "xs:date", "xs:datetime", "xs:QName")
        for parameter in options["parameterValues"].items():
            paramQname, paramTypeValue = parameter
            if isinstance(paramTypeValue, (tuple,list)):
                paramType, paramValue = paramTypeValue  # similar to modelTestcaseObject, where values() are (type,value)
            else:
                paramType = None
                paramValue = paramTypeValue
            self.gridCells.append( (
                gridCell(frame, 1, y, paramQname),
                gridCombobox(frame, 2, y, paramType, values=dataTypes),
                gridCell(frame, 3, y, paramValue)) )
            y += 1
        # extra entry for new cells
        for i in range(5):
            self.gridCells.append( (
                gridCell(frame, 1, y),
                gridCombobox(frame, 2, y, values=dataTypes),
                gridCell(frame, 3, y)) )
            y += 1
        y += 1
        
        # checkbox entries
        label(frame, 1, y, "Parameter Trace:")
        label(frame, 1, y + 3, "API Calls Trace:")
        label(frame, 1, y + 8, "Testcase Results:")
        label(frame, 2, y, "Variable Set Trace:")
        label(frame, 3, y, "Variables Trace:")
        self.checkboxes = (
           checkbox(frame, 1, y + 1, 
                    "Expression Result", 
                    "traceParameterExpressionResult"),
           checkbox(frame, 1, y + 2,
                    "Input Value", 
                    "traceParameterInputValue"),
           checkbox(frame, 1, y + 4, 
                    "Expression Source", 
                    "traceCallExpressionSource"),
           checkbox(frame, 1, y + 5, 
                    "Expression Code", 
                    "traceCallExpressionCode"),
           checkbox(frame, 1, y + 6, 
                    "Expression Evaluation", 
                    "traceCallExpressionEvaluation"),
           checkbox(frame, 1, y + 7,
                    "Expression Result", 
                    "traceCallExpressionResult"),
           checkbox(frame, 1, y + 9,
                    "Capture Warnings", 
                    "testcaseResultsCaptureWarnings"),

           checkbox(frame, 2, y + 1, 
                    "Expression Source", 
                    "traceVariableSetExpressionSource"),
           checkbox(frame, 2, y + 2, 
                    "Expression Code", 
                    "traceVariableSetExpressionCode"),
           checkbox(frame, 2, y + 3, 
                    "Expression Evaluation", 
                    "traceVariableSetExpressionEvaluation"),
           checkbox(frame, 2, y + 4,
                    "Expression Result", 
                    "traceVariableSetExpressionResult"),
           checkbox(frame, 2, y + 5,
                    "Assertion Result Counts", 
                    "traceAssertionResultCounts"),
           checkbox(frame, 2, y + 6,
                    "Assertion Satisfied [info]", 
                    "traceSatisfiedAssertions"),
           checkbox(frame, 2, y + 7,
                    "Assertion Unsatisfied [error]", 
                    "errorUnsatisfiedAssertions"),
           checkbox(frame, 2, y + 8,
                    "Assertion Unsatisfied [info]", 
                    "traceUnsatisfiedAssertions"),
           checkbox(frame, 2, y + 9,
                    "Formula Rules", 
                    "traceFormulaRules"),
           checkbox(frame, 2, y + 10,
                    "Evaluation Timing", 
                    "timeVariableSetEvaluation"),
           checkbox(frame, 3, y + 1, 
                    "Variable Dependencies", 
                    "traceVariablesDependencies"),
           checkbox(frame, 3, y + 2, 
                    "Variables Order", 
                    "traceVariablesOrder"),
           checkbox(frame, 3, y + 3, 
                    "Expression Source", 
                    "traceVariableExpressionSource"),
           checkbox(frame, 3, y + 4, 
                    "Expression Code", 
                    "traceVariableExpressionCode"),
           checkbox(frame, 3, y + 5, 
                    "Expression Evaluation", 
                    "traceVariableExpressionEvaluation"),
           checkbox(frame, 3, y + 6, 
                    "Expression Result", 
                    "traceVariableExpressionResult"),
           checkbox(frame, 3, y + 7, 
                    "Filter Winnowing", 
                    "traceVariableFilterWinnowing"),
           checkbox(frame, 3, y + 8, 
                    "Filters Result", 
                    "traceVariableFiltersResult")
        
           # Note: if adding to this list keep ModelFormulaObject.FormulaOptions in sync
        
           )
        y += 11
        
        mainWin.showStatus(None)

        label(frame, 1, y, "IDs:")
        self.idsEntry = gridCell(frame, 1, y, options.get("runIDs"))
        self.idsEntry.grid(columnspan=2, padx=30)
        _w = 8 if self.modelManager.cntlr.isMac else 12
        okButton = Button(frame, text=_("OK"), width=_w, command=self.ok)
        cancelButton = Button(frame, text=_("Cancel"), width=_w, command=self.close)
        okButton.grid(row=y, column=3, sticky=W, pady=3)
        cancelButton.grid(row=y, column=3, sticky=E, pady=3, padx=3)
        
        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(1, weight=3)
        frame.columnconfigure(2, weight=1)
        frame.columnconfigure(3, weight=3)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        
        #self.bind("<Return>", self.ok)
        #self.bind("<Escape>", self.close)
        
        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
Exemplo n.º 50
0
Arquivo: tagview.py Projeto: gokai/tim
class NameView(object):
    """Shows a treeview of unique names."""

    def __init__(self, master, names):
        self.widget = Frame(master)
        self._tree = Treeview(self.widget, columns='name')
        self._tree.grid(row=0,column=0, sticky=(N,S,W,E))
        self._tree.view = self
        self.widget.columnconfigure(0, weight=1)
        self.widget.rowconfigure(0,weight=1)
        self._tree.column('name', width=50)
        self._tree['show'] = 'tree'
        actions = {'edit': lambda e: self.edit(),
                'search': lambda e: self.search(),
                'focus_next': lambda e: self.focus_next(),
                'focus_prev': lambda e: self.focus_prev(),
                'select': lambda e: self._tree.selection_toggle(self._tree.focus()),
                'clear_selection': lambda e: self._tree.selection_set([])
                }
        kb.make_bindings(kb.tagview, actions, self._tree.bind)
        self._iids = dict()
        self._names = dict()
        logger.debug('Names: %s', names)
        self.widget.focus_set = self._tree.focus_set
        for name in sorted(names):
            iid = self._tree.insert('', 'end', text=name)
            self._names[iid] = name
            self._iids[name] = iid
        self._scroll = Scrollbar(self.widget, command=self._tree.yview)
        self._tree['yscrollcommand'] = self._scroll.set
        self._scroll.grid(row=0, column=1, sticky=(N, S))
        self.widget.columnconfigure(1, weight=0)


    def selection(self):
        logger.debug('Selection: %s', self._tree.selection())
        return [self._names[iid] for iid in self._tree.selection()]

    def edit(self):
        self._tree.event_generate('<<NameViewEdit>>')

    def search(self):
        if len(self._tree.selection()) == 0:
            self._tree.selection_add(self._tree.focus())
        self._tree.event_generate('<<NameViewSearch>>')

    def append(self, names):
        logger.debug('Append names: %s', names)
        for name in names:
            if name not in self._names.values():
                iid = self._tree.insert('', 'end', text=name)
                self._names[iid] = name
                self._iids[name] = iid

    def delete(self, name):
        self._tree.delete(self._iids[name])
        del self._names[self._iids[name]]
        del self._iids[name]

    def _focus(self, iid):
        self._tree.focus(iid)
        self._tree.see(iid)

    def focus_next(self):
        cur_iid = self._tree.focus()
        next_iid = self._tree.next(cur_iid)
        if next_iid == '':
            iids = self._tree.get_children()
            next_iid = iids[0]
        self._focus(next_iid)

    def focus_prev(self):
        cur_iid = self._tree.focus()
        prev_iid = self._tree.prev(cur_iid)
        if prev_iid == '':
            iids = self._tree.get_children()
            prev_iid = iids[-1]
        self._focus(prev_iid)

    def jump_to(self, name):
        try:
            iid = self._iids[name]
            self._focus(iid)
        except KeyError:
            pass

    def get_names(self):
        return tuple(self._names.values())

    def set(self, names):
        self._tree.delete(*self._iids.values())
        self._iids.clear()
        self._names.clear()
        for name in sorted(names):
            iid = self._tree.insert('', 'end', text=name)
            self._names[iid] = name
            self._iids[name] = iid
Exemplo n.º 51
0
    def __init__(self, parent, title, host=None, realm=None, useOsProxy=None, urlAddr=None, urlPort=None, user=None, password=None, database=None, timeout=None, dbType=None, showUrl=False, showUser=False, showHost=True, showRealm=True, showDatabase=False):
        super(DialogUserPassword, self).__init__(parent)
        self.parent = parent
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False
        self.transient(self.parent)
        self.title(title)
        self.urlAddrVar = StringVar()
        self.urlAddrVar.set(urlAddr if urlAddr else "")
        self.urlPortVar = StringVar()
        self.urlPortVar.set(urlPort if urlPort else "")
        self.userVar = StringVar()
        self.userVar.set(user if user else "")
        self.passwordVar = StringVar()
        self.passwordVar.set(password if password else "")
        self.databaseVar = StringVar()
        self.databaseVar.set(database if database else "")
        self.timeoutVar = StringVar()
        self.timeoutVar.set(timeout if timeout else "")
        
        frame = Frame(self)
        y = 0
        if showHost:
            hostLabel = Label(frame, text=_("Host:"), underline=0)
            hostDisplay = Label(frame, text=host, width=30)
            if host and len(host) > 30:
                ToolTip(hostDisplay, text=host, wraplength=240)
            hostLabel.grid(row=y, column=0, sticky=W, pady=3, padx=3)
            hostDisplay.grid(row=y, column=1, columnspan=4, sticky=EW, pady=3, padx=3)
            y += 1
        if showRealm:
            realmLabel = Label(frame, text=_("Realm:"), underline=0)
            realmDisplay = Label(frame, text=realm, width=25)
            if realm and len(realm) > 30:
                ToolTip(realmDisplay, text=realm, wraplength=240)
            realmLabel.grid(row=y, column=0, sticky=W, pady=3, padx=3)
            realmDisplay.grid(row=y, column=1, columnspan=4, sticky=EW, pady=3, padx=3)
            y += 1
        self.enabledWidgets = []
        if useOsProxy is not None:
            if sys.platform.startswith("win"):
                hostProxy = _('Microsoft Windows Internet Settings')
            elif sys.platform in ("darwin", "macos"):
                hostProxy = _('Mac OS X System Configuration')
            else: # linux/unix
                hostProxy = _('environment variables')
            useOsProxyCb = checkbox(frame, 0, y, text=_("Use proxy server of {0}").format(hostProxy))
            useOsProxyCb.grid(columnspan=5)
            useOsProxyCb.valueVar.set(useOsProxy)
            ToolTip(useOsProxyCb, text=_("Check to use {0} \n"
                                         "Uncheck to specify: \n"
                                         "   No proxy if URL address is left blank, \n"
                                         "   Proxy via URL address if it is not blank, \n"
                                         "       with user and password (if provided)"
                                         ).format(hostProxy), wraplength=360)
            self.useOsProxyCb = useOsProxyCb
            useOsProxyCb.valueVar.trace("w", self.setEnabledState)

            y += 1
        if showUrl:
            urlAddrLabel = Label(frame, text=_("Address:"), underline=0)
            urlAddrEntry = Entry(frame, textvariable=self.urlAddrVar, width=16)
            urlPortLabel = Label(frame, text=_("Port:"), underline=0)
            urlPortEntry = Entry(frame, textvariable=self.urlPortVar, width=5)
            urlAddrEntry.focus_set()
            urlAddrLabel.grid(row=y, column=0, sticky=W, pady=3, padx=3)
            urlAddrEntry.grid(row=y, column=1, columnspan=2, sticky=EW, pady=3, padx=3)
            urlPortLabel.grid(row=y, column=3, sticky=W, pady=3, padx=3)
            urlPortEntry.grid(row=y, column=4, sticky=EW, pady=3, padx=3)
            ToolTip(urlAddrEntry, text=_("Enter URL address and port number \n"
                                         "  e.g., address: 168.1.2.3 port: 8080 \n"
                                         "  or address: proxy.myCompany.com port: 8080 \n"
                                         "  or leave blank to specify no proxy server"), wraplength=360)
            self.enabledWidgets.append(urlAddrEntry)
            self.enabledWidgets.append(urlPortEntry)
            y += 1
        userLabel = Label(frame, text=_("User:"******"Password:"******"*")
        passwordLabel.grid(row=y, column=0, sticky=W, pady=3, padx=3)
        passwordEntry.grid(row=y, column=1, columnspan=4, sticky=EW, pady=3, padx=3)
        self.enabledWidgets.append(passwordEntry)
        y += 1
        if showDatabase:
            urlDatabaseLabel = Label(frame, text=_("Database:"), underline=0)
            urlDatabaseEntry = Entry(frame, textvariable=self.databaseVar, width=25)
            urlDatabaseLabel.grid(row=y, column=0, sticky=W, pady=3, padx=3)
            urlDatabaseEntry.grid(row=y, column=1, columnspan=4, sticky=EW, pady=3, padx=3)
            ToolTip(urlAddrEntry, text=_("Enter database name (optional) or leave blank"), wraplength=360)
            self.enabledWidgets.append(urlDatabaseEntry)
            y += 1
            urlTimeoutLabel = Label(frame, text=_("Timeout:"), underline=0)
            urlTimeoutEntry = Entry(frame, textvariable=self.timeoutVar, width=25)
            urlTimeoutLabel.grid(row=y, column=0, sticky=W, pady=3, padx=3)
            urlTimeoutEntry.grid(row=y, column=1, columnspan=4, sticky=EW, pady=3, padx=3)
            ToolTip(urlAddrEntry, text=_("Enter timeout seconds (optional) or leave blank for default (60 secs.)"), wraplength=360)
            self.enabledWidgets.append(urlTimeoutEntry)
            y += 1
            dbTypeLabel = Label(frame, text=_("DB type:"), underline=0)
            dbTypeLabel.grid(row=y, column=0, sticky=W, pady=3, padx=3)
            self.cbDbType = gridCombobox(frame, 1, y, values=DBDescriptions, 
                                         selectindex=DBTypes.index(dbType) if dbType in DBTypes else None)
            self.cbDbType.grid(columnspan=4, pady=3, padx=3)
            y += 1
        okButton = Button(frame, text=_("OK"), command=self.ok)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        okButton.grid(row=y, column=2, sticky=E, pady=3)
        cancelButton.grid(row=y, column=3, columnspan=2, sticky=EW, pady=3, padx=3)
        y += 1
                
        if useOsProxy is not None:
            self.setEnabledState()

        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(1, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        
        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)
        
        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
Exemplo n.º 52
0
    def __init__(self, mainWin, openType, filesource, filenames, title, colHeader, showAltViewButton=False):
        parent = mainWin.parent
        super(DialogOpenArchive, self).__init__(parent)
        self.parent = parent
        self.showAltViewButton = showAltViewButton
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False

        self.transient(self.parent)
        
        frame = Frame(self)

        treeFrame = Frame(frame, width=500)
        vScrollbar = Scrollbar(treeFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(treeFrame, orient=HORIZONTAL)
        self.treeView = Treeview(treeFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set)
        self.treeView.grid(row=0, column=0, sticky=(N, S, E, W))
        hScrollbar["command"] = self.treeView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.treeView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        treeFrame.columnconfigure(0, weight=1)
        treeFrame.rowconfigure(0, weight=1)
        treeFrame.grid(row=0, column=0, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        self.treeView.focus_set()
        
        mainWin.showStatus(_("loading archive {0}").format(filesource.url))
        self.filesource = filesource
        self.filenames = filenames
        self.selection = filesource.selection
        self.hasToolTip = False
        selectedNode = None

        if openType == ENTRY_POINTS:
            try:
                metadataFiles = filesource.taxonomyPackageMetadataFiles
                if len(metadataFiles) > 1:
                    raise IOError(_("Taxonomy package contained more than one metadata file: {0}.")
                                  .format(', '.join(metadataFiles)))
                metadataFile = metadataFiles[0]
                metadata = filesource.file(filesource.url + os.sep + metadataFile)[0]
                self.metadataFilePrefix = os.sep.join(os.path.split(metadataFile)[:-1])
                if self.metadataFilePrefix:
                    self.metadataFilePrefix += os.sep
        
                self.nameToUrls, self.remappings = parseTxmyPkg(mainWin, metadata)
            except Exception as e:
                self.close()
                err = _("Failed to parse metadata; the underlying error was: {0}").format(e)
                messagebox.showerror(_("Malformed taxonomy package"), err)
                mainWin.addToLog(err)
                return
    
        mainWin.showStatus(None)
        
        if openType == DISCLOSURE_SYSTEM:
            y = 3
        else:
            y = 1

        okButton = Button(frame, text=_("OK"), command=self.ok)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        okButton.grid(row=y, column=2, sticky=(S,E,W), pady=3)
        cancelButton.grid(row=y, column=3, sticky=(S,E,W), pady=3, padx=3)
        
        if showAltViewButton:
            self.altViewButton = Button(frame, command=self.showAltView)
            self.altViewButton.grid(row=y, column=0, sticky=(S,W), pady=3, padx=3)
        
        self.loadTreeView(openType, colHeader, title)

        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(0, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        
        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)
        
        self.toolTipText = StringVar()
        if self.hasToolTip:
            self.treeView.bind("<Motion>", self.motion, '+')
            self.treeView.bind("<Leave>", self.leave, '+')
            self.toolTipText = StringVar()
            self.toolTip = ToolTip(self.treeView, 
                                   textvariable=self.toolTipText, 
                                   wraplength=640, 
                                   follow_mouse=True,
                                   state="disabled")
            self.toolTipRowId = None

        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
Exemplo n.º 53
0
    def __init__(self, mainWin, options):
        parent = mainWin.parent
        super(DialogFind, self).__init__(parent)
        self.parent = parent
        self.modelManager = mainWin.modelManager
        self.modelXbrl = None   # set when Find pressed, this blocks next prematurely
        if options is None: options = newFindOptions
        self.options = options
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
        dialogW = int(parentGeometry.group(1))
        dialogH = int(parentGeometry.group(2))
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False

        self.transient(self.parent)
        self.title(_("Find"))
        
        self.objsList = [] # next may be tried before anything is found
        
        frame = Frame(self)

        # load grid
        findLabel = gridHdr(frame, 1, 0, "Find:", anchor="w")
        findLabel.grid(padx=8)
        self.cbExpr = gridCombobox(frame, 1, 1, values=options["priorExpressions"])
        self.cbExpr.grid(columnspan=3, padx=8)
        ToolTip(self.cbExpr, text=_("Enter expression to find, or select from combo box drop down history list."), wraplength=240)

        y = 2
        
        # checkbox entries
        label(frame, 1, y, "Direction:")
        label(frame, 1, y + 3, "Match:")
        scopeLabel = label(frame, 2, y, "Scope:")
        ToolTip(scopeLabel, text=_("Scope for an XBRL document (instance or DTS).  "
                                   "For an RSS Feed, all properties are matched.  "), wraplength=240)
        rbUp = radiobutton(frame, 1, y+1, "Up", "up", "direction")
        ToolTip(rbUp, text=_("Find/Next up (on screen) from last to first match."), wraplength=240)
        rbDn = radiobutton(frame, 1, y+2, "Down", "down", "direction", rbUp.valueVar)
        ToolTip(rbDn, text=_("Find/Next down (on screen) from first to last match."), wraplength=240)
        rbText = radiobutton(frame, 1, y+4, "Text (ignore case)", "text", "exprType")
        ToolTip(rbText, text=_("Expression is a set of characters to match, ignoring case.  "
                               "The match may occur anywhere within the scope. "), wraplength=360)
        rbRegex = radiobutton(frame, 1, y+5, "Regular expression", "regex", "exprType", rbText.valueVar)
        ToolTip(rbRegex, text=_('A regular expression to match, anywhere in the scope, ignoring case.  '
                                'For example, "cash" would match cash anywhere in a string (like cash on hand), '
                                'whereas "^cash$" would match a full string to only contain cash. ' 
                                'Use regular expression metacharacters, e.g., "." for any single character, '
                                '".*" for any number of wild characters, .{3} for exactly 3 wild characters. '), wraplength=360)
        rbXPath = radiobutton(frame, 1, y+6, "XPath 2 expression", "xpath", "exprType", rbText.valueVar)
        ToolTip(rbXPath, text=_('An XPath 2 expression, where the context element, ".", is a candidate concept QName, if any concept scope is checked, '
                                'and a candidate fact item, if any fact scope is checked.  The XPath 2 functions do not need an "fn:" prefix (but it is defined).  '
                                'The XBRL Functions Registry functions do require an "xfi:" prefix.  Constructors require an "xs:" prefix.  '
                                'The expression is considered "matched" for the candidate concept QNames or fact items where the effective boolean value of the expression is "true()".  '), wraplength=360)
        self.optionControls = (
           rbUp,
           rbDn,
           rbText,
           rbRegex,
           rbXPath,
           #checkbox(frame, 2, y + 1, "All", "all"),
           checkbox(frame, 2, y + 1, "Concept label", "conceptLabel"),
           checkbox(frame, 2, y + 2, "   name", "conceptName"),
           checkbox(frame, 2, y + 3, "   type", "conceptType"),
           checkbox(frame, 2, y + 4, "   subs group", "conceptSubs"),
           checkbox(frame, 2, y + 5, "   period type", "conceptPer"),
           checkbox(frame, 2, y + 6, "   balance", "conceptBal"),
           checkbox(frame, 3, y + 1, "Fact label", "factLabel"),
           checkbox(frame, 3, y + 2, "   name", "factName"),
           checkbox(frame, 3, y + 3, "   value", "factValue"),
           checkbox(frame, 3, y + 4, "   context", "factCntx"),
           checkbox(frame, 3, y + 5, "   unit", "factUnit"),
           checkbox(frame, 3, y + 6, "Messages", "messagesLog"),
        
           # Note: if adding to this list keep Finder.FindOptions in sync
        
           )
        y += 7
        resultLabel = gridHdr(frame, 1, y, "Result:", anchor="w")
        resultLabel.grid(padx=8)
        self.resultText = gridCell(frame, 1, y + 1)
        self.resultText.grid(columnspan=3, padx=8)
        self.resultText.config(state="readonly")
        y += 2
        
        mainWin.showStatus(None)

        buttonFrame = Frame(frame)
        buttonFrame.grid(columnspan=4, sticky=E, padx=8)
        findButton = Button(buttonFrame, text=_("Find"), width=12, command=self.find)
        ToolTip(findButton, text=_('Compile (if regular expression or XPath 2), and find first match (if down direction) or last match (if up direction).  '), wraplength=240)
        nextButton = Button(buttonFrame, text=_("Next"), width=12, command=self.next)
        ToolTip(nextButton, text=_('Advance to the next matched object (in selected direction).  '), wraplength=240)
        closeButton = Button(buttonFrame, text=_("Close"), width=12, command=self.close)
        ToolTip(closeButton, text=_('Close the find dialog.  '), wraplength=240)
        findButton.grid(row=1, column=1, pady=3)
        nextButton.grid(row=1, column=2, pady=3)
        closeButton.grid(row=1, column=3, padx=3)
        
        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(1, weight=1)
        frame.columnconfigure(2, weight=1)
        frame.columnconfigure(3, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        if self.options["geometry"]:
            self.geometry(self.options["geometry"])
        else:
            self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        
        #self.bind("<Return>", self.ok)
        #self.bind("<Escape>", self.close)
        
        self.protocol("WM_DELETE_WINDOW", self.close)
        
        # make this dialog non-modal
        self.focus_set()
Exemplo n.º 54
0
     def __init__(self, tester):
         self.tester = tester
         self.mainWin = tester.cntlr
 
         parent = self.mainWin.parent
         super(DialogTransformTester, self).__init__(parent)
         self.parent = parent
         parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
         dialogX = int(parentGeometry.group(3))
         dialogY = int(parentGeometry.group(4))
         self.selectedGroup = None
 
         self.transient(self.parent)
         self.title(_("Transformation Tester"))
         
         frame = Frame(self)
         
         # load grid
         trRegLabel = label(frame, 0, 0, _("Registry:"))
         trReg = self.tester.trRegs[-1] # default is latest
         self.trRegName = gridCombobox(frame, 1, 0, 
                                       value=trReg,
                                       values=self.tester.trRegs, 
                                       comboboxselected=self.dialogTrRegComboBoxSelected)
         trRegToolTipMessage = _("Select Transformation Registry")
         ToolTip(self.trRegName, text=trRegToolTipMessage, wraplength=360)
         ToolTip(trRegLabel, text=trRegToolTipMessage, wraplength=360)
         
         trNameLabel = label(frame, 0, 1, _("Transform:"))
         self.trNameName = gridCombobox(frame, 1, 1, 
                                       value="",
                                       values=self.tester.getTrNames(trReg), 
                                       comboboxselected=self.dialogTrNameComboBoxSelected)
         trRegToolTipMessage = _("Select or enter transform")
         ToolTip(self.trRegName, text=trRegToolTipMessage, wraplength=360)
         ToolTip(trRegLabel, text=trRegToolTipMessage, wraplength=360)
 
         sourceLabel = label(frame, 0, 2, _("Source text:"))
         ToolTip(sourceLabel, text=_("Enter the source text which is to be transformed. "), wraplength=240)
         self.sourceVar = StringVar()
         self.sourceVar.set("")
         sourceEntry = Entry(frame, textvariable=self.sourceVar, width=50)
         sourceLabel.grid(row=2, column=0, sticky=W)
         sourceEntry.grid(row=2, column=1, sticky=EW, pady=3, padx=3)
 
         resultLabel = label(frame, 1, 3, _("Result:"))
         ToolTip(sourceLabel, text=_("Transformation result. "), wraplength=240)
         self.resultVar = StringVar()
         self.resultVar.set("")
         resultEntry = Entry(frame, textvariable=self.resultVar, width=50)
         resultLabel.grid(row=3, column=0, sticky=W)
         resultEntry.grid(row=3, column=1, sticky=EW, pady=3, padx=3)
 
         
         self.mainWin.showStatus(None)
 
         btnPad = 2 if self.mainWin.isMSW else 0 # buttons too narrow on windows
         okButton = Button(frame, text=_("Transform"), width=8 + btnPad, command=self.dialogOk)
         cancelButton = Button(frame, text=_("Done"), width=4 + btnPad, command=self.dialogClose)
         cancelButton.grid(row=4, column=0, sticky=E, columnspan=2, pady=3, padx=3)
         okButton.grid(row=4, column=0, sticky=E, columnspan=2, pady=3, padx=64)
         ToolTip(okButton, text=_("Transform the source entered. "), wraplength=240)
         ToolTip(cancelButton, text=_("Close this dialog. "), wraplength=240)
         
         frame.grid(row=0, column=0, sticky=(N,S,E,W))
         frame.columnconfigure(1, weight=3)
         frame.columnconfigure(2, weight=1)
         window = self.winfo_toplevel()
         window.columnconfigure(0, weight=1)
         self.geometry("+{0}+{1}".format(dialogX+150,dialogY+100))
         
         #self.bind("<Return>", self.ok)
         #self.bind("<Escape>", self.close)
         
         self.protocol("WM_DELETE_WINDOW", self.dialogClose)
         self.grab_set()
         
         self.wait_window(self)
Exemplo n.º 55
0
class DialogVidget(ToplevelVidget):
    """
    DialogVidget contains a Toplevel widget, a main Frame widget, a custom view
    widget, and two button widgets for `Confirm` and `Cancel`.
    """

    def __init__(
        self,
        view_widget=None,
        confirm_handler=None,
        confirm_buttion_text='Confirm',
        cancel_handler=None,
        cancel_buttion_text='Cancel',
        close_handler=None,
        master=None,
    ):
        """
        Initialize object.

        @param view_widget: Custom view widget.

        @param confirm_handler: Confirm button event handler.

        @param confirm_buttion_text: Confirm button text.

        @param cancel_handler: Cancel button event handler.

        @param cancel_buttion_text: Cancel button text.

        @param close_handler: Window close button event handler.

        @param master: Master widget.

        @return: None.
        """
        # Initialize ToplevelVidget
        ToplevelVidget.__init__(
            self,
            close_handler=close_handler,
            master=master,
        )

        # Create main frame
        self._frame = Frame(master=self._toplevel)

        # Custom view widget
        self._view_widget = view_widget

        # Confirm button event handler
        self._confirm_handler = confirm_handler \
            if confirm_handler is not None else self._confirm_handler_default

        # Create confirm button
        self._confirm_button = Button(
            master=self._toplevel,
            text=confirm_buttion_text,
            command=self._confirm_handler,
        )

        # Cancel button event handler
        self._cancel_handler = cancel_handler \
            if cancel_handler is not None else self._cancel_handler_default

        # Create cancel button
        self._cancel_button = Button(
            master=self._toplevel,
            text=cancel_buttion_text,
            command=self._cancel_handler,
        )

        # If the view widget is given
        if self._view_widget is not None:
            # Set view widget
            self.view_set(self._view_widget)

        # Update widget
        self._widget_update()

    def _widget_update(self):
        """
        Update widget.

        @return: None.
        """
        # Configure layout weights for children
        self._toplevel.rowconfigure(0, weight=1)

        self._toplevel.columnconfigure(0, weight=1)

        # Lay out the main frame widget
        self._frame.grid(
            in_=self._toplevel,
            row=0,
            column=0,
            sticky='NSEW',
        )

        # Do not use children to compute main frame's geometry info
        self._frame.grid_propagate(False)

        # Configure layout weights for children.

        # Row 0 is for the view widget.
        self._frame.rowconfigure(0, weight=1)

        # Row 1 is for the confirm and cancel button widgets.
        self._frame.rowconfigure(0, weight=0)

        # Use only one column
        self._frame.columnconfigure(0, weight=1)

        # Lay out the confirm button
        self._confirm_button.grid(
            in_=self._frame,
            row=1,
            column=0,
            sticky='W',
        )

        # Lay out the cancel button
        self._cancel_button.grid(
            in_=self._frame,
            row=1,
            column=0,
            sticky='E',
        )

    def main_frame(self):
        """
        Get the main frame widget.

        @return: Main frame widget.
        """
        # Return the main frame widget
        return self._frame

    def view_set(self, widget):
        """
        Set view widget.

        @param widget: View widget.

        @return: None.
        """
        # Hide old view widget
        if self._view_widget is not None:
            self._view_widget.grid_forget()

        # Store new view widget
        self._view_widget = widget

        # Lay out new view widget
        self._view_widget.grid(
            in_=self._frame,
            row=0,
            column=0,
            sticky='NSEW',
        )

    def confirm_button(self):
        """
        Get the confirm button widget.

        @return: Confirm button widget.
        """
        # Return the confirm button widget
        return self._confirm_button

    def confirm_handler_set(self, handler):
        """
        Set confirm button event handler.

        @handler: Confirm button event handler.

        @return: None.
        """
        # Store confirm button event handler
        self._confirm_handler = handler

        # Set confirm button event handler
        self._confirm_button.config(command=self._confirm_handler)

    def _confirm_handler_default(self):
        """
        Default confirm button event handler.

        @return: None.
        """
        # Do nothing
        pass

    def cancel_button(self):
        """
        Get the cancel button widget.

        @return: Cancel button widget.
        """
        # Return the cancel button widget
        return self._cancel_button

    def cancel_handler_set(self, handler):
        """
        Set cancel button event handler.

        @handler: Cancel button event handler.

        @return: None.
        """
        # Store cancel button event handler
        self._cancel_handler = handler

        # Set cancel button event handler
        self._cancel_button.config(command=self._cancel_handler)

    def _cancel_handler_default(self):
        """
        Default cancel button event handler.

        @return: None.
        """
        # Hide the toplevel widget
        self._toplevel.withdraw()

        # Release grab on the toplevel widget
        self._toplevel.grab_release()
Exemplo n.º 56
0
    def __init__(self, mainWin, packageNamesWithNewerFileDates):
        super(DialogPackageManager, self).__init__(mainWin.parent)
        
        self.ENABLE = _("Enable")
        self.DISABLE = _("Disable")
        self.parent = mainWin.parent
        self.cntlr = mainWin
        
        # copy plugins for temporary display
        self.packagesConfig = PackageManager.packagesConfig
        self.packagesConfigChanged = False
        self.packageNamesWithNewerFileDates = packageNamesWithNewerFileDates
        
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", self.parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))

        self.title(_("Taxonomy Packages Manager"))
        frame = Frame(self)
        
        # left button frame
        buttonFrame = Frame(frame, width=40)
        buttonFrame.columnconfigure(0, weight=1)
        addLabel = Label(buttonFrame, text=_("Find taxonomy packages:"), wraplength=64, justify="center")
        addLocalButton = Button(buttonFrame, text=_("Locally"), command=self.findLocally)
        ToolTip(addLocalButton, text=_("File chooser allows selecting taxonomy packages to add (or reload), from the local file system.  "
                                       "Select either a taxonomy package zip file, or a taxonomy manifest (.taxonomyPackage.xml) within an unzipped taxonomy package.  "), wraplength=240)
        addWebButton = Button(buttonFrame, text=_("On Web"), command=self.findOnWeb)
        ToolTip(addWebButton, text=_("Dialog to enter URL full path to load (or reload) package, from the web or local file system.  "
                                     "URL may be either a taxonomy package zip file, or a taxonomy manifest (.taxonomyPackage.xml) within an unzipped taxonomy package.  "), wraplength=240)
        manifestNameButton = Button(buttonFrame, text=_("Manifest"), command=self.manifestName)
        ToolTip(manifestNameButton, text=_("Provide non-standard archive manifest file name pattern (e.g., *taxonomyPackage.xml).  "
                                           "Uses unix file name pattern matching.  "
                                           "Multiple manifest files are supported in archive (such as oasis catalogs).  "
                                           "(Replaces search for either .taxonomyPackage.xml or catalog.xml).  "), wraplength=240)
        self.manifestNamePattern = ""
        addLabel.grid(row=0, column=0, pady=4)
        addLocalButton.grid(row=1, column=0, pady=4)
        addWebButton.grid(row=2, column=0, pady=4)
        manifestNameButton.grid(row=3, column=0, pady=4)
        buttonFrame.grid(row=0, column=0, rowspan=3, sticky=(N, S, W), padx=3, pady=3)
        
        # right tree frame (packages already known to arelle)
        packagesFrame = Frame(frame, width=700)
        vScrollbar = Scrollbar(packagesFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(packagesFrame, orient=HORIZONTAL)
        self.packagesView = Treeview(packagesFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, height=7)
        self.packagesView.grid(row=0, column=0, sticky=(N, S, E, W))
        self.packagesView.bind('<<TreeviewSelect>>', self.packageSelect)
        hScrollbar["command"] = self.packagesView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.packagesView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        packagesFrame.columnconfigure(0, weight=1)
        packagesFrame.rowconfigure(0, weight=1)
        packagesFrame.grid(row=0, column=1, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        self.packagesView.focus_set()

        self.packagesView.column("#0", width=120, anchor="w")
        self.packagesView.heading("#0", text=_("Name"))
        self.packagesView["columns"] = ("ver", "status", "date", "update", "descr")
        self.packagesView.column("ver", width=150, anchor="w", stretch=False)
        self.packagesView.heading("ver", text=_("Version"))
        self.packagesView.column("status", width=50, anchor="w", stretch=False)
        self.packagesView.heading("status", text=_("Status"))
        self.packagesView.column("date", width=170, anchor="w", stretch=False)
        self.packagesView.heading("date", text=_("File Date"))
        self.packagesView.column("update", width=50, anchor="w", stretch=False)
        self.packagesView.heading("update", text=_("Update"))
        self.packagesView.column("descr", width=200, anchor="w", stretch=False)
        self.packagesView.heading("descr", text=_("Description"))

        remappingsFrame = Frame(frame)
        vScrollbar = Scrollbar(remappingsFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(remappingsFrame, orient=HORIZONTAL)
        self.remappingsView = Treeview(remappingsFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, height=5)
        self.remappingsView.grid(row=0, column=0, sticky=(N, S, E, W))
        hScrollbar["command"] = self.remappingsView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.remappingsView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        remappingsFrame.columnconfigure(0, weight=1)
        remappingsFrame.rowconfigure(0, weight=1)
        remappingsFrame.grid(row=1, column=1, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        self.remappingsView.focus_set()
        
        self.remappingsView.column("#0", width=200, anchor="w")
        self.remappingsView.heading("#0", text=_("Prefix"))
        self.remappingsView["columns"] = ("remapping")
        self.remappingsView.column("remapping", width=500, anchor="w", stretch=False)
        self.remappingsView.heading("remapping", text=_("Remapping"))
        
        # bottom frame package info details
        packageInfoFrame = Frame(frame, width=700)
        packageInfoFrame.columnconfigure(1, weight=1)
        
        self.packageNameLabel = Label(packageInfoFrame, wraplength=600, justify="left", 
                                      font=font.Font(family='Helvetica', size=12, weight='bold'))
        self.packageNameLabel.grid(row=0, column=0, columnspan=6, sticky=W)
        self.packageVersionHdr = Label(packageInfoFrame, text=_("version:"), state=DISABLED)
        self.packageVersionHdr.grid(row=1, column=0, sticky=W)
        self.packageVersionLabel = Label(packageInfoFrame, wraplength=600, justify="left")
        self.packageVersionLabel.grid(row=1, column=1, columnspan=5, sticky=W)
        self.packageDescrHdr = Label(packageInfoFrame, text=_("description:"), state=DISABLED)
        self.packageDescrHdr.grid(row=2, column=0, sticky=W)
        self.packageDescrLabel = Label(packageInfoFrame, wraplength=600, justify="left")
        self.packageDescrLabel.grid(row=2, column=1, columnspan=5, sticky=W)
        self.packagePrefixesHdr = Label(packageInfoFrame, text=_("prefixes:"), state=DISABLED)
        self.packagePrefixesHdr.grid(row=3, column=0, sticky=W)
        self.packagePrefixesLabel = Label(packageInfoFrame, wraplength=600, justify="left")
        self.packagePrefixesLabel.grid(row=3, column=1, columnspan=5, sticky=W)
        ToolTip(self.packagePrefixesLabel, text=_("List of prefixes that this package remaps."), wraplength=240)
        self.packageUrlHdr = Label(packageInfoFrame, text=_("URL:"), state=DISABLED)
        self.packageUrlHdr.grid(row=4, column=0, sticky=W)
        self.packageUrlLabel = Label(packageInfoFrame, wraplength=600, justify="left")
        self.packageUrlLabel.grid(row=4, column=1, columnspan=5, sticky=W)
        ToolTip(self.packageUrlLabel, text=_("URL of taxonomy package (local file path or web loaded file)."), wraplength=240)
        self.packageDateHdr = Label(packageInfoFrame, text=_("date:"), state=DISABLED)
        self.packageDateHdr.grid(row=5, column=0, sticky=W)
        self.packageDateLabel = Label(packageInfoFrame, wraplength=600, justify="left")
        self.packageDateLabel.grid(row=5, column=1, columnspan=5, sticky=W)
        ToolTip(self.packageDateLabel, text=_("Date of currently loaded package file (with parenthetical node when an update is available)."), wraplength=240)
        self.packageEnableButton = Button(packageInfoFrame, text=self.ENABLE, state=DISABLED, command=self.packageEnable)
        ToolTip(self.packageEnableButton, text=_("Enable/disable package."), wraplength=240)
        self.packageEnableButton.grid(row=6, column=1, sticky=E)
        self.packageMoveUpButton = Button(packageInfoFrame, text=_("Move Up"), state=DISABLED, command=self.packageMoveUp)
        ToolTip(self.packageMoveUpButton, text=_("Move package up (above other remappings)."), wraplength=240)
        self.packageMoveUpButton.grid(row=6, column=2, sticky=E)
        self.packageMoveDownButton = Button(packageInfoFrame, text=_("Move Down"), state=DISABLED, command=self.packageMoveDown)
        ToolTip(self.packageMoveDownButton, text=_("Move package down (below other remappings)."), wraplength=240)
        self.packageMoveDownButton.grid(row=6, column=3, sticky=E)
        self.packageReloadButton = Button(packageInfoFrame, text=_("Reload"), state=DISABLED, command=self.packageReload)
        ToolTip(self.packageReloadButton, text=_("Reload/update package."), wraplength=240)
        self.packageReloadButton.grid(row=6, column=4, sticky=E)
        self.packageRemoveButton = Button(packageInfoFrame, text=_("Remove"), state=DISABLED, command=self.packageRemove)
        ToolTip(self.packageRemoveButton, text=_("Remove package from packages table (does not erase the package file)."), wraplength=240)
        self.packageRemoveButton.grid(row=6, column=5, sticky=E)
        packageInfoFrame.grid(row=2, column=0, columnspan=5, sticky=(N, S, E, W), padx=3, pady=3)
        packageInfoFrame.config(borderwidth=4, relief="groove")
        
        okButton = Button(frame, text=_("Close"), command=self.ok)
        ToolTip(okButton, text=_("Accept and changes (if any) and close dialog."), wraplength=240)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        ToolTip(cancelButton, text=_("Cancel changes (if any) and close dialog."), wraplength=240)
        okButton.grid(row=3, column=3, sticky=(S,E), pady=3)
        cancelButton.grid(row=3, column=4, sticky=(S,E), pady=3, padx=3)
        
        self.loadTreeViews()

        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(0, weight=0)
        frame.columnconfigure(1, weight=1)
        frame.rowconfigure(0, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        window.rowconfigure(0, weight=1)
        
        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)
        
        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
Exemplo n.º 57
0
def make_pane(parent: ttk.Frame):
    """Create all the widgets we use."""
    if not CONFIG_ORDER:
        # No configs at all...
        ttk.Label(parent, text=_('No Item Configuration!')).pack(fill='both')
        return

    CONFIG_ORDER.sort(key=lambda grp: grp.name)

    parent.columnconfigure(0, weight=1)

    # Need to use a canvas to allow scrolling
    canvas = tk.Canvas(parent, highlightthickness=0)
    canvas.grid(row=0, column=0, sticky='NSEW')
    parent.rowconfigure(0, weight=1)

    scrollbar = ttk.Scrollbar(
        parent,
        orient='vertical',
        command=canvas.yview,
    )
    scrollbar.grid(column=1, row=0, sticky="ns")
    canvas['yscrollcommand'] = scrollbar.set

    utils.add_mousewheel(canvas, canvas, parent)
    canvas_frame = ttk.Frame(canvas)
    canvas.create_window(0, 0, window=canvas_frame, anchor="nw")
    canvas_frame.rowconfigure(0, weight=1)

    for conf_row, config in enumerate(CONFIG_ORDER):
        frame = ttk.LabelFrame(canvas_frame, text=config.name)
        frame.columnconfigure(0, weight=1)
        frame.grid(row=conf_row, column=0, sticky='nsew')

        row = 0

        widget_count = len(config.widgets) + len(config.multi_widgets)

        # Now make the widgets.
        if config.widgets:
            for row, wid in enumerate(config.widgets):
                wid_frame = ttk.Frame(frame)
                wid_frame.grid(row=row, column=0, sticky='ew')
                wid_frame.columnconfigure(1, weight=1)

                label = ttk.Label(wid_frame, text=wid.name + ': ')
                label.grid(row=0, column=0)
                widget = wid.create_func(wid_frame, wid.values, wid.config)
                widget.grid(row=0, column=1, sticky='e')

                if wid.tooltip:
                    add_tooltip(widget, wid.tooltip)
                    add_tooltip(label, wid.tooltip)
                    add_tooltip(wid_frame, wid.tooltip)

        if config.widgets and config.multi_widgets:
            ttk.Separator(orient='horizontal').grid(
                row=1, column=0, sticky='ew',
            )

        # Skip if no timer widgets
        if not config.multi_widgets:
            continue

        # Continue from wherever we were.
        for row, wid in enumerate(config.multi_widgets, start=row+1):
            # If we only have 1 widget, don't add a redundant title.
            if widget_count == 1:
                wid_frame = ttk.Frame(frame)
            else:
                wid_frame = ttk.LabelFrame(frame, text=wid.name)

            wid_frame.grid(row=row, column=0, sticky='ew')
            wid.multi_func(
                wid_frame,
                wid.values,
                wid.config,
            )

            if wid.tooltip:
                add_tooltip(wid_frame, wid.tooltip)

    canvas.update_idletasks()
    canvas.config(
        scrollregion=canvas.bbox('ALL'),
        width=canvas_frame.winfo_reqwidth(),
    )

    def canvas_reflow(e):
        canvas['scrollregion'] = canvas.bbox('all')

    canvas.bind('<Configure>', canvas_reflow)
Exemplo n.º 58
0
    def __init__(self, mainWin, modulesWithNewerFileDates):
        super(DialogPluginManager, self).__init__(mainWin.parent)
        
        self.ENABLE = _("Enable")
        self.DISABLE = _("Disable")
        self.parent = mainWin.parent
        self.cntlr = mainWin
        
        # copy plugins for temporary display
        self.pluginConfig = PluginManager.pluginConfig
        self.pluginConfigChanged = False
        self.uiClassMethodsChanged = False
        self.modelClassesChanged = False
        self.disclosureSystemTypesChanged = False
        self.hostSystemFeaturesChanged = False
        self.modulesWithNewerFileDates = modulesWithNewerFileDates
        
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", self.parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))

        self.title(_("Plug-in Manager"))
        frame = Frame(self)
        
        # left button frame
        buttonFrame = Frame(frame, width=40)
        buttonFrame.columnconfigure(0, weight=1)
        addLabel = Label(buttonFrame, text=_("Find plug-in modules:"), wraplength=60, justify="center")
        addLocalButton = Button(buttonFrame, text=_("Locally"), command=self.findLocally)
        ToolTip(addLocalButton, text=_("File chooser allows selecting python module files to add (or reload) plug-ins, from the local file system."), wraplength=240)
        addWebButton = Button(buttonFrame, text=_("On Web"), command=self.findOnWeb)
        ToolTip(addWebButton, text=_("Dialog to enter URL full path to load (or reload) plug-ins, from the web or local file system."), wraplength=240)
        addLabel.grid(row=0, column=0, pady=4)
        addLocalButton.grid(row=1, column=0, pady=4)
        addWebButton.grid(row=2, column=0, pady=4)
        buttonFrame.grid(row=0, column=0, rowspan=2, sticky=(N, S, W), padx=3, pady=3)
        
        # right tree frame (plugins already known to arelle)
        modulesFrame = Frame(frame, width=700)
        vScrollbar = Scrollbar(modulesFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(modulesFrame, orient=HORIZONTAL)
        self.modulesView = Treeview(modulesFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, height=7)
        self.modulesView.grid(row=0, column=0, sticky=(N, S, E, W))
        self.modulesView.bind('<<TreeviewSelect>>', self.moduleSelect)
        hScrollbar["command"] = self.modulesView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.modulesView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        modulesFrame.columnconfigure(0, weight=1)
        modulesFrame.rowconfigure(0, weight=1)
        modulesFrame.grid(row=0, column=1, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        self.modulesView.focus_set()

        self.modulesView.column("#0", width=120, anchor="w")
        self.modulesView.heading("#0", text=_("Name"))
        self.modulesView["columns"] = ("author", "ver", "status", "date", "update", "descr", "license")
        self.modulesView.column("author", width=100, anchor="w", stretch=False)
        self.modulesView.heading("author", text=_("Author"))
        self.modulesView.column("ver", width=50, anchor="w", stretch=False)
        self.modulesView.heading("ver", text=_("Version"))
        self.modulesView.column("status", width=50, anchor="w", stretch=False)
        self.modulesView.heading("status", text=_("Status"))
        self.modulesView.column("date", width=70, anchor="w", stretch=False)
        self.modulesView.heading("date", text=_("File Date"))
        self.modulesView.column("update", width=50, anchor="w", stretch=False)
        self.modulesView.heading("update", text=_("Update"))
        self.modulesView.column("descr", width=200, anchor="w", stretch=False)
        self.modulesView.heading("descr", text=_("Description"))
        self.modulesView.column("license", width=70, anchor="w", stretch=False)
        self.modulesView.heading("license", text=_("License"))

        classesFrame = Frame(frame)
        vScrollbar = Scrollbar(classesFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(classesFrame, orient=HORIZONTAL)
        self.classesView = Treeview(classesFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, height=5)
        self.classesView.grid(row=0, column=0, sticky=(N, S, E, W))
        hScrollbar["command"] = self.classesView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.classesView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        classesFrame.columnconfigure(0, weight=1)
        classesFrame.rowconfigure(0, weight=1)
        classesFrame.grid(row=1, column=1, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        self.classesView.focus_set()
        
        self.classesView.column("#0", width=200, anchor="w")
        self.classesView.heading("#0", text=_("Class"))
        self.classesView["columns"] = ("modules",)
        self.classesView.column("modules", width=500, anchor="w", stretch=False)
        self.classesView.heading("modules", text=_("Modules"))
        
        # bottom frame module info details
        moduleInfoFrame = Frame(frame, width=700)
        moduleInfoFrame.columnconfigure(1, weight=1)
        
        self.moduleNameLabel = Label(moduleInfoFrame, wraplength=600, justify="left", 
                                     font=font.Font(family='Helvetica', size=12, weight='bold'))
        self.moduleNameLabel.grid(row=0, column=0, columnspan=4, sticky=W)
        self.moduleAuthorHdr = Label(moduleInfoFrame, text=_("author:"), state=DISABLED)
        self.moduleAuthorHdr.grid(row=1, column=0, sticky=W)
        self.moduleAuthorLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleAuthorLabel.grid(row=1, column=1, columnspan=3, sticky=W)
        self.moduleDescrHdr = Label(moduleInfoFrame, text=_("description:"), state=DISABLED)
        self.moduleDescrHdr.grid(row=2, column=0, sticky=W)
        self.moduleDescrLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleDescrLabel.grid(row=2, column=1, columnspan=3, sticky=W)
        self.moduleClassesHdr = Label(moduleInfoFrame, text=_("classes:"), state=DISABLED)
        self.moduleClassesHdr.grid(row=3, column=0, sticky=W)
        self.moduleClassesLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleClassesLabel.grid(row=3, column=1, columnspan=3, sticky=W)
        ToolTip(self.moduleClassesLabel, text=_("List of classes that this plug-in handles."), wraplength=240)
        self.moduleUrlHdr = Label(moduleInfoFrame, text=_("URL:"), state=DISABLED)
        self.moduleUrlHdr.grid(row=4, column=0, sticky=W)
        self.moduleUrlLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleUrlLabel.grid(row=4, column=1, columnspan=3, sticky=W)
        ToolTip(self.moduleUrlLabel, text=_("URL of plug-in module (local file path or web loaded file)."), wraplength=240)
        self.moduleDateHdr = Label(moduleInfoFrame, text=_("date:"), state=DISABLED)
        self.moduleDateHdr.grid(row=5, column=0, sticky=W)
        self.moduleDateLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleDateLabel.grid(row=5, column=1, columnspan=3, sticky=W)
        ToolTip(self.moduleDateLabel, text=_("Date of currently loaded module file (with parenthetical node when an update is available)."), wraplength=240)
        self.moduleLicenseHdr = Label(moduleInfoFrame, text=_("license:"), state=DISABLED)
        self.moduleLicenseHdr.grid(row=6, column=0, sticky=W)
        self.moduleLicenseLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleLicenseLabel.grid(row=6, column=1, columnspan=3, sticky=W)
        self.moduleImportsHdr = Label(moduleInfoFrame, text=_("imports:"), state=DISABLED)
        self.moduleImportsHdr.grid(row=7, column=0, sticky=W)
        self.moduleImportsLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleImportsLabel.grid(row=7, column=1, columnspan=3, sticky=W)
        self.moduleEnableButton = Button(moduleInfoFrame, text=self.ENABLE, state=DISABLED, command=self.moduleEnable)
        ToolTip(self.moduleEnableButton, text=_("Enable/disable plug in."), wraplength=240)
        self.moduleEnableButton.grid(row=8, column=1, sticky=E)
        self.moduleReloadButton = Button(moduleInfoFrame, text=_("Reload"), state=DISABLED, command=self.moduleReload)
        ToolTip(self.moduleReloadButton, text=_("Reload/update plug in."), wraplength=240)
        self.moduleReloadButton.grid(row=8, column=2, sticky=E)
        self.moduleRemoveButton = Button(moduleInfoFrame, text=_("Remove"), state=DISABLED, command=self.moduleRemove)
        ToolTip(self.moduleRemoveButton, text=_("Remove plug in from plug in table (does not erase the plug in's file)."), wraplength=240)
        self.moduleRemoveButton.grid(row=8, column=3, sticky=E)
        moduleInfoFrame.grid(row=2, column=0, columnspan=5, sticky=(N, S, E, W), padx=3, pady=3)
        moduleInfoFrame.config(borderwidth=4, relief="groove")
        
        okButton = Button(frame, text=_("Close"), command=self.ok)
        ToolTip(okButton, text=_("Accept and changes (if any) and close dialog."), wraplength=240)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        ToolTip(cancelButton, text=_("Cancel changes (if any) and close dialog."), wraplength=240)
        okButton.grid(row=3, column=3, sticky=(S,E), pady=3)
        cancelButton.grid(row=3, column=4, sticky=(S,E), pady=3, padx=3)
        
        enableDisableFrame = Frame(frame)
        enableDisableFrame.grid(row=3, column=1, sticky=(S,W), pady=3)
        enableAllButton = Button(enableDisableFrame, text=_("Enable All"), command=self.enableAll)
        ToolTip(enableAllButton, text=_("Enable all plug ins."), wraplength=240)
        disableAllButton = Button(enableDisableFrame, text=_("Disable All"), command=self.disableAll)
        ToolTip(disableAllButton, text=_("Disable all plug ins."), wraplength=240)
        enableAllButton.grid(row=1, column=1)
        disableAllButton.grid(row=1, column=2)
        
        self.loadTreeViews()

        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(0, weight=0)
        frame.columnconfigure(1, weight=1)
        frame.rowconfigure(0, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        window.rowconfigure(0, weight=1)
        
        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)
        
        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
Exemplo n.º 59
0
    def __init__(self, parent, openType, filesource, filenames, title, colHeader, showAltViewButton=False):
        if isinstance(parent, Cntlr):
            cntlr = parent
            parent = parent.parent # parent is cntlrWinMain
        else: # parent is a Toplevel dialog
            cntlr = parent.cntlr
        super(DialogOpenArchive, self).__init__(parent)
        self.parent = parent
        self.showAltViewButton = showAltViewButton
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False

        self.transient(self.parent)
        
        frame = Frame(self)

        treeFrame = Frame(frame, width=500)
        vScrollbar = Scrollbar(treeFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(treeFrame, orient=HORIZONTAL)
        self.treeView = Treeview(treeFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set)
        self.treeView.grid(row=0, column=0, sticky=(N, S, E, W))
        hScrollbar["command"] = self.treeView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.treeView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        treeFrame.columnconfigure(0, weight=1)
        treeFrame.rowconfigure(0, weight=1)
        treeFrame.grid(row=0, column=0, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        self.treeView.focus_set()
        
        if openType not in (PLUGIN, PACKAGE):
            cntlr.showStatus(_("loading archive {0}").format(filesource.url))
        self.filesource = filesource
        self.filenames = filenames
        self.selection = filesource.selection
        self.hasToolTip = False
        selectedNode = None

        if openType == ENTRY_POINTS:
            try:
                metadataFiles = filesource.taxonomyPackageMetadataFiles
                ''' take first for now
                if len(metadataFiles) != 1:
                    raise IOError(_("Taxonomy package contained more than one metadata file: {0}.")
                                  .format(', '.join(metadataFiles)))
                '''
                metadataFile = metadataFiles[0]
                metadata = filesource.url + os.sep + metadataFile
                self.metadataFilePrefix = os.sep.join(os.path.split(metadataFile)[:-1])
                if self.metadataFilePrefix:
                    self.metadataFilePrefix += "/"  # zip contents have /, never \ file seps
                self.taxonomyPkgMetaInf = '{}/META-INF/'.format(
                            os.path.splitext(os.path.basename(filesource.url))[0])

        
                self.taxonomyPackage = parsePackage(cntlr, filesource, metadata,
                                                    os.sep.join(os.path.split(metadata)[:-1]) + os.sep)
                
                
                if self.taxonomyPackage["entryPoints"]:
                    # may have instance documents too
                    self.packageContainedInstances = []
                    packageContentTypeCounts = {}
                    for suffix in (".xhtml", ".htm", ".html"):
                        for potentialInstance in filesource.dir:
                            if potentialInstance.endswith(".xhtml"):
                                _type = "Inline Instance"
                                self.packageContainedInstances.append([potentialInstance, _type])
                                packageContentTypeCounts[potentialInstance] = packageContentTypeCounts.get(potentialInstance, 0) + 1
                        if self.packageContainedInstances:
                            break 
                    if self.packageContainedInstances: # add sequences to any duplicated entry types
                        for _type, count in packageContentTypeCounts.items():
                            if count > 1:
                                _dupNo = 0
                                for i in range(len(self.packageContainedInstances)):
                                    if self.packageContainedInstances[i][0] == _type:
                                        _dupNo += 1
                                        self.packageContainedInstances[i][0] = "{} {}".format(_type, _dupNo)
                                    
                else:
                    # may be a catalog file with no entry oint names
                    openType = ARCHIVE  # no entry points to show, just archive
                    self.showAltViewButton = False
            except Exception as e:
                self.close()
                err = _("Failed to parse metadata; the underlying error was: {0}").format(e)
                messagebox.showerror(_("Malformed taxonomy package"), err)
                cntlr.addToLog(err)
                return
    
        if openType not in (PLUGIN, PACKAGE):
            cntlr.showStatus(None)
        
        if openType in (DISCLOSURE_SYSTEM, PLUGIN, PACKAGE):
            y = 3
        else:
            y = 1

        okButton = Button(frame, text=_("OK"), command=self.ok)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        okButton.grid(row=y, column=2, sticky=(S,E,W), pady=3)
        cancelButton.grid(row=y, column=3, sticky=(S,E,W), pady=3, padx=3)
        
        if self.showAltViewButton:
            self.altViewButton = Button(frame, command=self.showAltView)
            self.altViewButton.grid(row=y, column=0, sticky=(S,W), pady=3, padx=3)
        
        self.loadTreeView(openType, colHeader, title)

        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(0, weight=1)
        frame.rowconfigure(0, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        window.rowconfigure(0, weight=1)
        
        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)
        
        self.toolTipText = StringVar()
        if self.hasToolTip:
            self.treeView.bind("<Motion>", self.motion, '+')
            self.treeView.bind("<Leave>", self.leave, '+')
            self.toolTipText = StringVar()
            self.toolTip = ToolTip(self.treeView, 
                                   textvariable=self.toolTipText, 
                                   wraplength=640, 
                                   follow_mouse=True,
                                   state="disabled")
            self.toolTipRowId = None

        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        
        self.wait_window(self)