Exemple #1
0
    def add_slice_bar(self, slice_frame):
        """Add a slice selection options to slice_frame.

        Returns
        -------
        this_slice_label_number : Label
            the field displaying the current slice number
        this_new_slice : Entry
            the field allowing the user to fill in a slice number
        new_value : int
            the initial slice number to be set

        """

        # Have a line displaying slice number
        _slice_label = Label(slice_frame, text='Slice displayed : ')
        _slice_label.grid(column=0, row=0, sticky=['w', 'e'])
        this_slice_label_number = Label(slice_frame)
        this_slice_label_number.grid(column=1, row=0,
                                     sticky=['w', 'e'])

        # Allow to change slice number
        _goto = Label(slice_frame, text=' - go to slice :')
        _goto.grid(column=2, row=0, sticky=['w', 'e'])

        this_new_slice = Entry(slice_frame, width=6)
        this_new_slice.bind('<Return>', self.goto_slice)
        this_new_slice.bind('<KP_Enter>', self.goto_slice)
        this_new_slice.grid(column=3, row=0, sticky=['w', 'e'])

        self.image_scale = (self.screen_width - 200) / 4

        # Allow to scroll through the slices
        self._slice_scroll = lsb.LinkedScrollBar(master=slice_frame,
                                                 command=self.disp_im,
                                                 minVal=self._get_min_slice(),
                                                 maxVal=self._get_max_slice(),
                                                 step=1,
                                                 orient='horizontal')
        self._slice_scroll.grid(column=0,
                                row=1,
                                columnspan=self.image_nb,
                                sticky=['e', 'w', 's'])


        self._slice_label_number = this_slice_label_number
        self._new_slice = this_new_slice
        self.reset_slice_scroll()
Exemple #2
0
class GUI(Frame):
    def __init__(self, parent, register):
        Frame.__init__(self, parent, padding=(3, 3, 3, 3))
        self.parent = parent
        self.register = register
        self.logger = register.get_events_logger()
        self.init_ui()

        self.login()
        self.update_order()

    def login(self):
        logged_in = False
        while not logged_in:
            token = None
            while token is None:
                token = askstring(title="Please login", prompt="Login")
            try:
                self.register.login_employee(token)
                logged_in = True
            except CredentialException:
                self.logger.warning("invalid employee token '" + token +
                                    "', " + "unable to login")
        self.name_var.set(register.get_employee_name())
        # Put focus in barcode field
        self.barcode_field.focus()

    def logout(self, *args):
        self.register.logout_employee()
        self.name_var.set("")
        self.login()

    def print_count(self):
        try:
            print self.register.get_register_count()
        except CredentialException:
            self.logger.warning("insufficient privileges to print register " +
                                "count")
        # Put focus in barcode field
        self.barcode_field.focus()

    def add(self, token):
        try:
            self.register.add(token)
        except CredentialException:
            self.logger.warning("insufficient privileges to add an item")
        except ValueError:
            pass
        finally:
            self.update_order()
            # Put focus in barcode field
            self.barcode_field.focus()

    def add_custom(self, *args):
        name = askstring(title="Enter item name", prompt="Item name")
        if name is not None:
            price = askfloat(title="Enter item price",
                             prompt="Item price")
            if price is not None:
                try:
                    self.register.add_custom(name, price)
                except CredentialException:
                    self.logger.warning("insufficient privileges to add " +
                                        "a custom item")
                except ValueError as e:
                    self.logger.warning(e.__str__)
                finally:
                    self.update_order()
        # Put focus in barcode field
        self.barcode_field.focus()

    def remove(self, token):
        try:
            self.register.remove(token)
        except CredentialException:
            self.logger.warning("insufficient privileges to scan an item")
        except ValueError:
            self.logger.warning("token does not correspond to any item")
        except ItemNotFoundException:
            self.logger.warning("item not in order, unable to remove it")
        finally:
            self.update_order()
            # Put focus in barcode field
            self.barcode_field.focus()

    def clear_order(self, *args):
        try:
            self.register.clear_order()
        except CredentialException:
            self.logger.warning("insufficient privileges to clear the order")
        finally:
            self.update_order()
            # Put focus in barcode field
            self.barcode_field.focus()

    def adjust(self, *args):
        amount = askfloat(title="Enter adjustment amount",
                          prompt="Adjustment amount")
        if amount is not None:
            try:
                self.register.adjust(amount)
            except CredentialException:
                self.logger.warning("insufficient privileges to adjust " +
                                    "register count")
            except ValueError as e:
                self.logger.warning("invalid adjustment amount: " + e)
        # Put focus in barcode field
        self.barcode_field.focus()

    def checkout(self, *args):
        try:
            self.register.checkout_order()
        except CredentialException:
            self.logger.warning("insufficient privileges to checkout order")
        finally:
            self.update_order()
        # Put focus in barcode field
        self.barcode_field.focus()

    def count(self, *args):
        # TODO: implement a proper register count
        # TODO: add dialog box telling how register count went
        count = askfloat(title="Enter register count", prompt="Register count")
        if count is not None:
            try:
                self.register.count_register(count)
            except CredentialException:
                self.logger.warning("insufficient privileges to count " +
                                    "register")
        # Put focus in barcode field
        self.barcode_field.focus()

    def parse_barcode_field(self, event):
        command = self.barcode_field.get().strip()
        self.barcode_var.set("")
        tokens = command.split(" ")
        if tokens[0] == "print_count":
            self.print_count()
        elif tokens[0] == "print_order":
            self.print_order()
        elif tokens[0] == "remove":
            if len(tokens) < 2:
                self.logger.warning("need an item to remove")
                return None
            self.remove(tokens[1])
        elif tokens[0] == "adjust_count":
            if len(tokens) < 2:
                self.logger.warning("need an adjustment amount")
                return None
            self.adjust(tokens[1])
        elif tokens[0] == "custom":
            if len(tokens) < 3:
                self.logger.warning("need an name and a price")
                return None
            try:
                self.add_custom(tokens[1], float(tokens[2]))
            except ValueError:
                self.logger.warning("price is not valid")
        elif tokens[0] == "checkout":
            self.checkout()
        elif tokens[0] == "count":
            if len(tokens) < 2:
                self.logger.warning("need an register count")
                return None
            else:
                self.count(tokens[1])
        else:
            if tokens[0] != "":
                self.add(tokens[0])
        # Put focus in barcode field
        self.barcode_field.focus()

    def update_order(self):
        self.items_var.set(tuple(
            item.get_name() + " x " + str(quantity) for
            item, quantity in self.register.get_order().items()))
        self.total_var.set("Total: %0.2f$" % self.register.get_order_total())
        # Put focus in barcode field
        self.barcode_field.focus()

    def init_ui(self):
        # Window configuration
        screen_width = self.parent.winfo_screenwidth()
        screen_height = self.parent.winfo_screenheight()
        self.parent.geometry(
            '%dx%d+%d+%d' % (screen_width, screen_height, 0, 0))
        self.parent.title("Caisse Planck")
        self.parent.rowconfigure(0, weight=1)
        self.parent.columnconfigure(0, weight=1)

        self.grid(column=0, row=0, sticky=(N, S, E, W))
        self.rowconfigure(0, weight=0)
        self.rowconfigure(1, weight=1)
        self.rowconfigure(2, weight=1)
        self.rowconfigure(3, weight=1)
        self.rowconfigure(4, weight=1)
        self.rowconfigure(7, weight=0)
        self.rowconfigure(8, weight=0)
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=0)
        self.columnconfigure(2, weight=0)

        self.items_var = StringVar()
        self.items_list = Listbox(self, height=10, listvariable=self.items_var)
        self.items_list.grid(row=1, column=0, rowspan=8, sticky=(N, S, E, W))

        self.barcode_var = StringVar(self)
        self.barcode_field = Entry(self, textvariable=self.barcode_var)
        self.barcode_field.bind("<Return>", self.parse_barcode_field)
        self.barcode_field.grid(row=0, column=0, sticky=(N, E, W))

        self.benevole_label = Label(self, text="Volunteer:")
        self.benevole_label.grid(row=0, column=1, sticky=(N, W))

        self.name_var = StringVar(self)
        self.name_label = Label(self, textvar=self.name_var)
        self.name_label.grid(row=0, column=2, sticky=(N, W))


        self.parent.bind("<F1>", self.logout)
        self.logout_button = Button(self, text="Logout (F1)",
                                    command=self.logout)
        self.logout_button.grid(row=1, column=1, columnspan=2, sticky=(E, W))

        self.parent.bind("<F5>", self.count)
        self.count_button = Button(self, text="Count register (F5)",
                                   command=self.count)
        self.count_button.grid(row=2, column=1, columnspan=2, sticky=(E, W))

        self.parent.bind("<F6>", self.adjust)
        self.adjust_button = Button(self, text="Register adjustment (F6)",
                                    command=self.adjust)
        self.adjust_button.grid(row=3, column=1, columnspan=2, sticky=(E, W))

        self.parent.bind("<F6>", self.add_custom)
        self.custom_item_button = Button(self, text="Custom item (F7)",
                                         command=self.add_custom)
        self.custom_item_button.grid(row=4, column=1, columnspan=2,
                                     sticky=(E, W))

        self.total_var = StringVar(self, value="Total: 0.00$")
        self.total_label = Label(self, textvar=self.total_var)
        self.total_label.grid(row=7, column=1, columnspan=2, sticky=(S, E, W))

        self.parent.bind("<F12>", self.checkout)
        self.ok_button = Button(self, text="Ok (F12)", command=self.checkout)
        self.ok_button.grid(row=8, column=1, sticky=(S, E, W))

        self.parent.bind("<Escape>", self.clear_order)
        self.cancel_button = Button(self, text="Cancel (ESC)",
                                    command=self.clear_order)
        self.cancel_button.grid(row=8, column=2, sticky=(S, E, W))
Exemple #3
0
    def initUI(self):

        self.parent.title("Calculator")

        Style().configure("TButton", padding=(0, 5, 0, 5), font='serif 10')

        self.columnconfigure(0, pad=3)
        self.columnconfigure(1, pad=3)
        self.columnconfigure(2, pad=3)
        self.columnconfigure(3, pad=3)

        self.rowconfigure(0, pad=3)
        self.rowconfigure(1, pad=3)
        self.rowconfigure(2, pad=3)
        self.rowconfigure(3, pad=3)
        self.rowconfigure(4, pad=3)

        def calculate():
            expression = entry.get()
            entry.delete(0, END)
            entry.insert(0, str(eval(expression)))

        def evaluate(event):
            expression = entry.get()
            entry.delete(0, END)
            entry.insert(0, str(eval(expression)))

        def selectNumber(char):
            entry.insert(END, char)

        def backSpace():
            entry.delete(len(entry.get()) - 1, END)

        def deleteAll():
            entry.delete(0, END)

        entry = Entry(self)
        entry.grid(row=0, columnspan=4, sticky=W + E)
        entry.bind("<Return>", evaluate)
        cls = Button(self, text="Cls", command=lambda: deleteAll())
        cls.grid(row=1, column=0)
        bck = Button(self, text="Back", command=lambda: backSpace())
        bck.grid(row=1, column=1)
        lbl = Button(self)
        lbl.grid(row=1, column=2)
        clo = Button(self, text="Close", command=self.destroy)
        clo.grid(row=1, column=3)
        sev = Button(self, text="7", command=lambda: selectNumber("7"))
        sev.grid(row=2, column=0)
        eig = Button(self, text="8", command=lambda: selectNumber("8"))
        eig.grid(row=2, column=1)
        nin = Button(self, text="9", command=lambda: selectNumber("9"))
        nin.grid(row=2, column=2)
        div = Button(self, text="/", command=lambda: selectNumber("/"))
        div.grid(row=2, column=3)

        fou = Button(self, text="4", command=lambda: selectNumber("4"))
        fou.grid(row=3, column=0)
        fiv = Button(self, text="5", command=lambda: selectNumber("5"))
        fiv.grid(row=3, column=1)
        six = Button(self, text="6", command=lambda: selectNumber("6"))
        six.grid(row=3, column=2)
        mul = Button(self, text="*", command=lambda: selectNumber("*"))
        mul.grid(row=3, column=3)

        one = Button(self, text="1", command=lambda: selectNumber("1"))
        one.grid(row=4, column=0)
        two = Button(self, text="2", command=lambda: selectNumber("2"))
        two.grid(row=4, column=1)
        thr = Button(self, text="3", command=lambda: selectNumber("3"))
        thr.grid(row=4, column=2)
        mns = Button(self, text="-", command=lambda: selectNumber("-"))
        mns.grid(row=4, column=3)

        zer = Button(self, text="0", command=lambda: selectNumber("0"))
        zer.grid(row=5, column=0)
        dot = Button(self, text=".", command=lambda: selectNumber("."))
        dot.grid(row=5, column=1)
        equ = Button(self, text="=", command=lambda: calculate())
        equ.grid(row=5, column=2)
        pls = Button(self, text="+", command=lambda: selectNumber("+"))
        pls.grid(row=5, column=3)

        self.pack()
Exemple #4
0
def show_report(master, data):
    """Выводит панель генерации отчетов."""


    def choose_assortiment(event):
        """Функция, срабатывающая при выборе товара из списка товаров."""

        select = listbox_goods.curselection()
        if select:
            index = int(select[0])
            if assortiment[index]:
                show_report.goods = assortiment[index]
                title.configure(text=assortiment[index].name)
            else:
                show_report.goods = None
                title.configure(text=u'Товары:')
        checks_fill()

    #---------------------------------------

    def assortiment_fill():
        """Функция заполнения списков товаров/ингредиентов"""

        for q in range(len(assortiment)):       # Очищаем список товаров
            del(assortiment[0])
        listbox_goods.delete(0, END)

        for cath in queries.cathegories():
            assortiment.append(None)
            listbox_goods.insert(END, '')
            assortiment.append(None)
            head = '-' * (REPORT_WIDTH - len(cath.name) -1) + cath.name + u'-'
            listbox_goods.insert(END, head)

            for item in queries.items_in_cathegory(cath):
                assortiment.append(item)
                listbox_goods.insert(END, ' ' + item.name)
                if not item.show:
                    listbox_goods.itemconfig(END, {'fg':'grey'})

        assortiment.append(None)
        listbox_goods.insert(END, '')
        assortiment.append(None)
        head = '-' * (REPORT_WIDTH - len(u'Ингредиенты') -1) + u'Ингредиенты-'
        listbox_goods.insert(END, head)

        for item in queries.items_in_cathegory(None):
            assortiment.append(item)
            listbox_goods.insert(END, ' ' + item.name)
            if not item.show:
                listbox_goods.itemconfig(END, {'fg':'grey'})

    #---------------------------------------

    def checks_fill(event=None):
        """Функция заполнения списка параметров для отчета"""

        listbox_checks.delete(0, END)
        reporing = radioVar.get()
        listbox_checks.insert(END, reporing + ':')

        if varGoods.get():
            listbox_checks.insert(END, u'- товар' )
            if reporing == u'Расходы':
                listbox_checks.itemconfig(END, {'fg':'grey'})
            elif not show_report.goods:
                listbox_checks.itemconfig(END, {'fg':'red'})

        if varDate.get():
            listbox_checks.insert(END, u'- дата' )
            if reporing == u'Остатки':
                listbox_checks.itemconfig(END, {'fg':'grey'})
            elif not (cal_from.selection or cal_to.selection):
                listbox_checks.itemconfig(END, {'fg':'red'})

            elif (cal_from.selection and cal_to.selection) and (
                  cal_from.selection > cal_to.selection):
                listbox_checks.itemconfig(END, {'fg':'red'})

        if varCath.get():
            listbox_checks.insert(END, u'- категория' )
            if reporing == u'Расходы':
                listbox_checks.itemconfig(END, {'fg':'grey'})

        if varCheck.get():
            listbox_checks.insert(END, u'- чек' )
            if reporing <> u'Продажи':
                listbox_checks.itemconfig(END, {'fg':'grey'})
            else:
                try:
                    check1 = int(chekVar1.get())
                    check2 = int(chekVar2.get())
                except:
                    listbox_checks.itemconfig(END, {'fg':'red'})
                else:
                    if check1 > check2:
                        listbox_checks.itemconfig(END, {'fg':'red'})

        if varLost.get():
            listbox_checks.insert(END, u'- причина' )
            if reporing <> u'Списания':
                listbox_checks.itemconfig(END, {'fg':'grey'})

        if radioVar2.get() <> u'Не учитывать':
            listbox_checks.insert(END, u'- скидка' )
            if reporing <> u'Продажи':
                listbox_checks.itemconfig(END, {'fg':'grey'})


    #---------------------------------------

    class Calendar2(Calendar):
        """Класс с переопределенным (дополненным) методом клика по календарю."""

        def _pressed(self, evt):
            """Clicked somewhere in the calendar."""

            Calendar._pressed(self, evt)
            checks_fill()

    #---------------------------------------

    def apply():
        """Открывает окно с выбранным отчетом на основании выбранных фильтров"""

        args = {}

        if varGoods.get() and radioVar.get() <> u'Расходы':
            if show_report.goods:
                args['item'] = show_report.goods
            else:
                tkMessageBox.showinfo(u'Внимание!',
                          u'Товар не был выбран, так что учитываться не будет!')

        if varDate.get() and radioVar.get() <> u'Остатки':
            if cal_from.selection or cal_to.selection:
                if (cal_from.selection > cal_to.selection):
                    tkMessageBox.showinfo(u'Ошибка!',
              u'Начальный день акции больше конечного!\nФильтр не учитывается.')
                else:
                    if cal_from.selection:
                        args['from_date'] = cal_from.selection
                    if cal_to.selection:
                        args['to_date'] = cal_to.selection
            else:
                tkMessageBox.showinfo(u'Внимание!',
                         u'Даты не были выбраны, так что учитываться не будут!')

        if varCath.get():
            if radioVar.get() <> u'Расходы':
                args['cathegory'] = show_report.cathegory

        if varCheck.get():
            if radioVar.get() == u'Продажи':
                try:
                    check1 = int(chekVar1.get())
                    check2 = int(chekVar2.get())
                except:
                    tkMessageBox.showinfo(u'Ошибка!',
            u'Проверьте содержимое числовых полей чека!\nФильтр не учитвается.')
                else:
                    if check1 > check2:
                        tkMessageBox.showinfo(u'Ошибка!',
              u'Начальный номер чека больше конечного!\nФильтр не учитывается.')
                    else:
                        args['from_check'] = check1
                        args['to_check'] = check2

        if varLost.get():
            if radioVar.get() == u'Списания':
                args['reason'] = show_report.lost


        if radioVar2.get() <> u'Не учитывать':
            if radioVar.get() == u'Продажи':
                if radioVar2.get() == u'Со скидкой':
                    args['discount'] = True
                else:
                    args['discount'] = False


        if radioVar.get() == u'Продажи':
            report_sell(master, **args)
        elif radioVar.get() == u'Списания':
            report_lost(master, **args)
        elif radioVar.get() == u'Остатки':
            report_storage(master, **args)
        elif radioVar.get() == u'Приход':
            report_incoming(master, **args)
        elif radioVar.get() == u'Расходы':
            report_cash(master, **args)

    #=========================== СОЗДАНИЕ ИНТЕРФЕЙСА ===========================

    frame = Canvas(master, relief=GROOVE, highlightthickness=0)
    frame.pack(side=TOP, fill=BOTH, expand=YES)
    if USE_BACKGROUND:
        frame.create_image(0,0, anchor='nw', image=data.photo)

    #------------------------------ ЛЕВЫЙ ФРЕЙМ --------------------------------

    leftFrame = Frame(frame, relief=GROOVE)
    leftFrame.pack(side=LEFT, fill=Y, pady=CONTROL_PAD, padx=CONTROL_PAD/2)

    title = Label(leftFrame, text=u'Товары:',
                                        font=('Lucida Console', FONT_SIZE_BIG))
    title.pack(pady=5)

    varGoods = IntVar(leftFrame)
    chb_goods = Checkbutton(leftFrame, text=u'Фильтр по товару',
                                         variable=varGoods, command=checks_fill)
    chb_goods.pack(side=BOTTOM)

    assortiment = []
    show_report.goods = None

    scrollbar_goods = Scrollbar(leftFrame)
    listbox_goods = Listbox(leftFrame,
                       yscrollcommand=scrollbar_goods.set,
                       width = REPORT_WIDTH,
                       activestyle='dotbox',
                       font=('Lucida Console', BILL_FONT_SIZE))
    listbox_goods.pack(side=LEFT, fill=BOTH)
    scrollbar_goods.config(command=listbox_goods.yview)
    scrollbar_goods.pack(side=LEFT, fill=Y)

    listbox_goods.bind('<<ListboxSelect>>', choose_assortiment)

    #------------------------------ СРЕДНИЙ ФРЕЙМ ------------------------------

    middleFrame = Frame(frame, relief=GROOVE)
    middleFrame.pack(side=TOP, pady=CONTROL_PAD, padx=CONTROL_PAD, anchor='w',
                                       ipadx=CONTROL_PAD/3, ipady=CONTROL_PAD/3)

    radioVar = StringVar(middleFrame)
    radioVar.set("Продажи")

    variants = ("Продажи", "Остатки", "Приход", "Списания", "Расходы")

    listbox_checks = Listbox(middleFrame, width = 12, height=6,
                  activestyle='dotbox', font=('Lucida Console', BILL_FONT_SIZE))
    listbox_checks.pack(side=RIGHT, fill=Y, padx=CONTROL_PAD/2,
                                                             pady=CONTROL_PAD/2)

    Button(middleFrame, text='СФОРМИРОВАТЬ\nОТЧЕТ', style='Chosen.TButton',
                             command=apply).pack(side=RIGHT, padx = CONTROL_PAD,
                                         pady = CONTROL_PAD, ipadx=10, ipady=10)

    for txt in variants:
        Radiobutton(middleFrame, text=txt,indicatoron = 0, width = 10,
                         variable=radioVar, command=checks_fill, value=txt,
                         font=('Verdana', FONT_SIZE)).pack(padx = CONTROL_PAD,
                                                   pady=CONTROL_PAD/3, anchor=W)

    #-----------------------------------------

    middleFrame2 = Frame(frame, relief=GROOVE)
    middleFrame2.pack(padx=CONTROL_PAD, pady=CONTROL_PAD, anchor='w')


    date_from = Label(middleFrame2, text=u'Начальная дата:',
                                                  font = ('Verdana', FONT_SIZE))
    date_from.grid(column=0, row=0)
    cal_from = Calendar2(middleFrame2, firstweekday=0)
    cal_from.grid(column=0, row=1, pady=CONTROL_PAD, padx=CONTROL_PAD)

    date_to = Label(middleFrame2, text=u'Конечная дата\n(включительно):',
                                                  font = ('Verdana', FONT_SIZE))
    date_to.grid(column=1, row=0)
    cal_to = Calendar2(middleFrame2, firstweekday=0)
    cal_to.grid(column=1, row=1, pady=CONTROL_PAD, padx=CONTROL_PAD)

    varDate = IntVar(leftFrame)
    chb_date = Checkbutton(middleFrame2, text=u'Фильтр по датам',
                                          variable=varDate, command=checks_fill)
    chb_date.grid(column=0, row=2, columnspan=2, pady=CONTROL_PAD/3)


    #---------------------- Меню выбора категории --------------

    middleFrame3 = Frame(frame, relief=GROOVE)
    middleFrame3.pack(padx=CONTROL_PAD, pady=CONTROL_PAD, anchor='w')


    def menu_change(key):
        """Меняет текущую категорию."""
        if key:
            cathMenu.configure(text=key.name)
        else:
            cathMenu.configure(text=u'-Отсутствует-')
        show_report.cathegory = key


    def menu_update():
        """Обновляет меню выбора категорий."""

        menu  =  Menu(cathMenu, tearoff=0)
        cathMenu['menu'] = menu

        for cath in queries.cathegories():
            menu.add_command(label=cath.name, font=('Verdana', FONT_SIZE_BIG),
                                      command=lambda key=cath: menu_change(key))
        menu.add_command(label=u'-Отсутствует-', font=('Verdana',FONT_SIZE_BIG),
                                    command=lambda: menu_change(None))


    Style().configure('TMenubutton', font=('lucida console', FONT_SIZE_BIG),
                                                                justify='left')
    show_report.cathegory = None

    varCath = IntVar(middleFrame3)
    chb_cath = Checkbutton(middleFrame3, text=u'Фильтр по категории',
                                          variable=varCath, command=checks_fill)
    chb_cath.grid(column=0, row=1, columnspan=2,
                                              pady=(0, CONTROL_PAD))

    Label(middleFrame3, text='Категория:', font=('Verdana', FONT_SIZE_BIG)
                       ).grid(column=0, row=0, pady=CONTROL_PAD/3)

    smallFrame = Frame(middleFrame3, relief=GROOVE)
    smallFrame.grid(column=1, row=0, pady=CONTROL_PAD/3)


    cathMenu = Menubutton(smallFrame, text=u'-Отсутствует-', width=15,
                                                            style='TMenubutton')
    cathMenu.pack(fill=BOTH, pady=5, padx=5)
    menu_update()

    #----------------------------- ЧЕКИ ----------------------------

    check_frame = TkFrame(middleFrame3, relief=GROOVE, bg='#' + REPORT_COLOR)
    check_frame.grid(column=0, row=2, columnspan=2, pady=(CONTROL_PAD/3, 0),
                                                                  sticky='nwes')
    varCheck = IntVar(middleFrame3)
    chb_check = Checkbutton(middleFrame3, text=u'Фильтр по номеру чека',
                variable=varCheck, command=checks_fill, activebackground='#' +
                                     REPORT_COLOR, bg='#' + REPORT_COLOR)
    chb_check.grid(column=0, row=3, columnspan=2, pady=(0, CONTROL_PAD),
                                                                  sticky='nwes')

    chekVar1 = StringVar(check_frame, value=u'')
    ent1 = Entry(check_frame, textvariable=chekVar1, width=7,font=('Verdana',
       FONT_SIZE_BIG))
    ent1.pack(side=LEFT, pady=CONTROL_PAD/3, padx=CONTROL_PAD)
    ent1.bind("<KeyRelease>", checks_fill)

    Label(check_frame, text=u'<= номера чеков <=', bg='#' + REPORT_COLOR,
                                font = ('Verdana', FONT_SIZE)).pack(side=LEFT,
                                           pady=CONTROL_PAD/3, padx=CONTROL_PAD)
    chekVar2 = StringVar(check_frame, value=u'')
    ent2 = Entry(check_frame, textvariable=chekVar2, width=7,font=('Verdana',
       FONT_SIZE_BIG))
    ent2.pack(side=LEFT, pady=CONTROL_PAD/3, padx=CONTROL_PAD)
    ent2.bind("<KeyRelease>", checks_fill)

    #---------------------- Меню выбора причины списания --------------

    def menu_change_lost(key):
        """Меняет текущую причину списания."""
        if key:
            lostMenu.configure(text=key.reason)
        show_report.lost = key


    def menu_update_lost():
        """Обновляет меню выбора причин списания."""

        menu  =  Menu(cathMenu, tearoff=0)
        lostMenu['menu'] = menu

        for lost in queries.full_lost_reasons_list():
            menu.add_command(label=lost.reason, font=('Verdana', FONT_SIZE_BIG),
                                 command=lambda key=lost: menu_change_lost(key))


    Style().configure('TMenubutton', font=('lucida console', FONT_SIZE_BIG),
                                                                justify='left')
    lost_reasons_list = queries.lost_reasons_list()
    show_report.lost = lost_reasons_list[0] if lost_reasons_list else None

    varLost = IntVar(middleFrame)
    chb_lost = Checkbutton(middleFrame3, text=u'Фильтр по причине списания',
                                          variable=varLost, command=checks_fill)
    chb_lost.grid(column=0, row=5, columnspan=2, pady=(0, CONTROL_PAD))

    Label(middleFrame3, text='Причина списания:', font=('Verdana', FONT_SIZE_BIG)
                 ).grid(column=0, row=4, pady=CONTROL_PAD/3, padx=CONTROL_PAD/3)

    smallFrame2 = Frame(middleFrame3, relief=GROOVE)
    smallFrame2.grid(column=1, row=4, pady=CONTROL_PAD/3)

    lostMenu = Menubutton(smallFrame2, text=u'брак', width=19,
                                                            style='TMenubutton')
    lostMenu.pack(fill=BOTH, pady=5, padx=5)
    menu_update_lost()

    #--------------------------------------------------------------

    Label(middleFrame3, text='Фильтр по скидке.', font=('Verdana', FONT_SIZE),
            bg='#' + REPORT_COLOR).grid(column=0, row=7, sticky='nwes',
                                                                   columnspan=2)

    discFrame = TkFrame(middleFrame3, relief=GROOVE, bg='#' + REPORT_COLOR)
    discFrame.grid(column=0, row=6, columnspan=2, ipady=(CONTROL_PAD),
                                                                  sticky='nwes')
    radioVar2 = StringVar(middleFrame)
    radioVar2.set(u'Не учитывать')

    variants = (u'Не учитывать', u'Со скидкой', u'Без скидки')

    for txt in variants:
        Radiobutton(discFrame, text=txt,indicatoron = 0, width = 13,
            variable=radioVar2, command=checks_fill, value=txt,
            font=('Verdana', FONT_SIZE)).pack(side=LEFT, padx = CONTROL_PAD/2,
                                                  pady=CONTROL_PAD/3, anchor=W)

    #--------------------------------первый запуск-----------------------------

    assortiment_fill()
    checks_fill()
class CreateServer(Frame):

    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        self.controller = controller
        CreateServer.local_world = None
        label_1 = Label(self, text="Create server\n\n\n\n", font=TITLE_FONT, justify=CENTER, anchor=CENTER)
        label_2 = Label(self, text="Server name:")
        label_3 = Label(self, text="Gamefield (MxN):")
        CreateServer.plx_name = 'none'
        CreateServer.game_dim = '10X10'
        self.entry_1 = Entry(self)
        self.entry_2 = Entry(self)
        self.entry_2.insert(0, '10x10')
        self.entry_1.bind("<Key>", self.checkString)

        self.button1 = Button(self, text="Create",state="disabled", command= self.callback_set)
        self.button2 = Button(self, text="Back", command=lambda: controller.show_frame("StartPage"))

        label_1.pack(side="top", fill="x", pady=10)
        label_2.pack()
        self.entry_1.pack()
        label_3.pack()
        self.entry_2.pack()
        self.button1.pack(pady=10)
        self.button2.pack(pady=20)
    
    
    def com(self, controller, next_frame):
        controller.show_frame(next_frame)
        
    def checkString(self, event):
        if self.entry_1:
            self.button1.config(state="normal")
    
    def callback_set(self):
        set_global_state(1)
        if self.get_name_field():
            self.controller.show_frame("ChooseType")
    
    # process user inputs
    def get_name_field(self):
        CreateServer.plx_name = self.entry_1.get()
        CreateServer.game_dim = self.entry_2.get().upper()
        
        flag2 = False
        
        flag1 = self.string_check(CreateServer.plx_name,"Invalid server name")
        if flag1:
            flag2 = self.string_check(CreateServer.game_dim,"Invalid game field parameters")
        
        if flag2:
            m_split=CreateServer.game_dim.split('X')
            if len(m_split)==2:
                try:
                    _ = int(m_split[0])
                except:
                    flag2 = False  
                try:
                    _ = int(m_split[1])
                except:
                    flag2 = False
            else:
                flag2 = False
                
            if flag2 == False:
                tkMessageBox.showwarning("Error message", "Invalid game field parameters!")
        return flag1 & flag2
    
    # check if the string is usable
    def string_check(self,s,msg):
        temp = False
        try:
            s.decode('ascii')
        except UnicodeEncodeError:
            print "it was not an ascii-encoded unicode string"
            tkMessageBox.showwarning("Error message", msg)
        except UnicodeDecodeError:
            print "it was not an ascii-encoded unicode string"
            tkMessageBox.showwarning("Error message", msg)
        else:
            if len(CreateServer.plx_name) < 11 and len(CreateServer.plx_name) >= 1:
                temp = True
            else:
                tkMessageBox.showwarning("Error message", "Please input 1-10 characters!")
        return temp
    def __draw_current_choice(self, parent):
        
        choice = IntVar()
        other_player = StringVar()
        recommended = self.game.most_recommended_player_remaining()
        valuable = self.game.get_best_player_remaining()
        
        recommended_button = Radiobutton(parent, text=recommended, variable=choice, value=1)
        valuable_button = Radiobutton(parent, text=valuable, variable=choice, value=2)
        other_button = Radiobutton(parent, text="", variable=choice, takefocus=0, value=3)
        other_text = Entry(parent, textvariable=other_player)
        
        def text_focus(event):
            other_button.select()
        
        other_text.bind("<Button-1>", text_focus)

        def pick_player():

            decision = choice.get()

            if decision == 1:

                player = self.game.most_recommended_player_remaining()
                self.game.add_player_to_team(player)
                utils.remove_player_from_possible_players(
                    player,
                    self.game.connection,
                    self.game.cursor)
                self.user_pick_made.set(True)

            elif decision == 2:

                player = self.game.get_best_player_remaining()
                self.game.add_player_to_team(player)
                utils.remove_player_from_possible_players(
                    player,
                    self.game.connection,
                    self.game.cursor)
                self.user_pick_made.set(True)

            elif decision == 3:
                player = other_player.get()
                try:
                    self.game.add_player_to_team(player)
                    utils.remove_player_from_possible_players(
                        player,
                        self.game.connection,
                        self.game.cursor)
                    self.user_pick_made.set(True)
                except:
                    tkMessageBox.showinfo("Error", "Can't add that player to team, try again.")
                    self.user_pick_logic()

            else:
                tkMessageBox.showinfo("No Selection", "Please make a selection")
                self.user_pick_logic()

        def pick_player_button(event):
            pick_player()

        Label(parent, text="Recommended Player").grid(sticky="w", row=1)
        recommended_button.grid(sticky="w", row=1, column=1, columnspan=2)
        
        Label(parent, text="Most Valuable Player").grid(sticky="w", row=2)
        valuable_button.grid(sticky="w", row=2, column=1, columnspan=2)
        
        Label(parent, text="Choose other Player").grid(sticky="w", row=3)
        other_button.grid(sticky="w", row=3, column=1)
        other_text.grid(row=3, column=2, sticky="w", padx=5)
        
        pick_button = Button(parent, text="Pick", command=pick_player).grid(
            row=4, columnspan=3, sticky="ne", padx=5)
        self.parent.bind("<Return>", pick_player_button)
class EngineGui():
    def __init__(self, communicationProtocal):
        self.communicationProtocal = communicationProtocal

    def StartGui(self):
        self.tkRoot = Tk(baseName="")
        self.tkRoot.geometry("350x300+0+0")
        self.tkRoot.title("Engine SAPI GUI")
        self.GUIVisible = True

        frame = Frame(self.tkRoot)
        frame.style = Style()
        frame.style.theme_use("alt")
        frame.pack(fill=BOTH, expand=1)

        frame.columnconfigure(1, weight=1)
        frame.columnconfigure(7, pad=7)
        frame.rowconfigure(13, weight=1)
        frame.rowconfigure(13, pad=7)
        
        Label(frame, text="Start:").grid(row = 0, column=0)
        self.labelStart = Label(frame, text="0")
        self.labelStart.grid(row = 1, column=0)

        Label(frame, text="Length:").grid(row = 0, column=1)
        self.labelLength = Label(frame, text="0")
        self.labelLength.grid(row = 1, column=1)

        Label(frame, text="Total:").grid(row = 0, column=2)
        self.labelTotal = Label(frame, text="0")
        self.labelTotal.grid(row = 1, column=2)
        
        self.labelSentenceLeft = Label(frame, text="...")
        self.labelSentenceLeft.grid(row = 2, column=0, sticky=E)
        self.labelSentenceSpoken = Label(frame, text="...", foreground="red")
        self.labelSentenceSpoken.grid(row = 2, column=1)
        self.labelSentenceRight = Label(frame, text="...")
        self.labelSentenceRight.grid(row = 2, column=2, sticky=W, columnspan=2)   

        scrollbar = Scrollbar(frame, orient=VERTICAL)
        self.labelQueueToSpeak = Label(frame, text="Queue to speak:").grid(row = 3, column=0, pady=4, padx=5, sticky=W)
        self.listboxQueueToSpeak = Listbox(frame, width=50, height=3, yscrollcommand=scrollbar.set)
        
        scrollbar.config(command=self.listboxQueueToSpeak.yview)
        self.listboxQueueToSpeak.grid( sticky=N+S+E+W, row = 4, column = 0, columnspan = 2 ,rowspan = 3, padx=3)
        scrollbar.grid(sticky=N+S+W, row = 4, column = 2, rowspan = 3)

        self.buttonPauze = Button(frame, text="Pauze", command=self.communicationProtocal.handlePauze)
        self.buttonPauze.grid(row = 4, column=3)

        self.buttonStop = Button(frame, text="Stop", command=self.communicationProtocal.restartProcess)
        self.buttonStop.grid(row = 5, column=3)

        self.buttonResume = Button(frame, text="Resume", command=self.communicationProtocal.handleResume)
        self.buttonResume.grid(row = 6, column=3)

        Label(frame, text="Text to say:").grid(row = 7, column=0, padx=3, sticky=W)

        self.stringVarTextToSay = StringVar()
        self.entryTextToSay = Entry(frame, textvariable=self.stringVarTextToSay, width=500)
        self.entryTextToSay.grid(row=8, column=0, columnspan=3, padx=3, sticky=W)
        self.stringVarTextToSay.set("Hello SAPI Speak Engine")
        self.entryTextToSay.bind('<Return>', self.CallBackReturnSay)

        self.buttonSay = Button(frame, text="Say", command=self.CallBackButtonSay)
        self.buttonSay.grid(row = 8, column=3)

        Label(frame, text="Recover action:").grid(row = 9, column=0, padx=3, sticky=W)
        self.recoverActionLabelText = "None"
        self.labelRecoverAction = Label(frame, text=self.recoverActionLabelText, foreground="blue")
        self.labelRecoverAction.grid(row = 10, column=0)   

        Label(frame, text="Voice speed:").grid(row = 9, column=1, sticky=W)
        self.buttonSpeedDown = Button(frame, text="Speed down", command=self.communicationProtocal.handleSpeedDown)
        self.buttonSpeedDown.grid(row = 10, column=1, padx=3, sticky=E)

        self.speedValue = 0
        self.intVarSpeed = IntVar()
        vcmd = (self.tkRoot.register(self.OnValidateEntrySpeakSpeed), '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')
        self.entrySpeakSpeed = Entry(frame, textvariable=self.intVarSpeed, validate="key", validatecommand=vcmd, width=5)
        self.entrySpeakSpeed.grid(row=10,column=2)
        self.entrySpeakSpeed.bind('<Return>', self.CallBackSetSpeed)

        self.buttonSpeedUp = Button(frame, text="Speed up", command=self.communicationProtocal.handleSpeedUp)
        self.buttonSpeedUp.grid(row = 10, column=3)

        Label(frame, text="voice:").grid(row = 11, column=0, padx=3, sticky=W)
        self.buttonPrevVoice = Button(frame, text="Prev voice", command=self.communicationProtocal.handlePrevVoice)
        self.buttonPrevVoice.grid(row = 12, column=0, padx=3, sticky=W)

        self.buttonNextVoice = Button(frame, text="Next voice", command=self.communicationProtocal.handleNextVoice)
        self.buttonNextVoice.grid(row = 12, column=3)

        self.currentVoice = StringVar(self.tkRoot)
        self.currentVoice.set(self.communicationProtocal.CurrentVoiceName)

        engine = pyttsx.init()
        voices = engine.getProperty("voices")
        voiceNames = list()
        for x in xrange(0, len(voices)):
            voiceNames.append(voices[x].name)
        self.optionMenuVoices = OptionMenu(frame, self.currentVoice, *tuple(voiceNames), command=self.CallBackOptionMenuVoices)
        self.optionMenuVoices.config(width=500)
        self.optionMenuVoices.grid(sticky=W, row = 12, column = 1)
     
        #hide if close button is clicked
        self.tkRoot.protocol("WM_DELETE_WINDOW", self.HideGui)
        self.tkRoot.after(1000/32, self.Update)
        self.tkRoot.mainloop()  

    def Update(self):
        wordLocation = self.communicationProtocal.OnWordStartLocation
        wordLength = self.communicationProtocal.OnWordLength
        wordTotal = self.communicationProtocal.OnWordTotal

        if wordLocation:
            self.labelStart.configure(text=wordLocation)
        else:
            self.labelStart.configure(text="0")
        self.labelLength.configure(text=wordLength)
        if wordLength != 0 and wordTotal == 0:
            self.labelTotal.configure(text="Introduce")    
        else:
            self.labelTotal.configure(text=wordTotal)

        if len(self.communicationProtocal.SpeakQueue) != 0:
            if (wordLocation < 25):
                self.labelSentenceLeft.configure(text=str(self.communicationProtocal.SpeakQueue[0])[0:wordLocation])
            else:
                self.labelSentenceLeft.configure(text=str(self.communicationProtocal.SpeakQueue[0])[wordLocation-25:wordLocation])
            self.labelSentenceSpoken.configure(text=str(self.communicationProtocal.SpeakQueue[0])[wordLocation:wordLocation+wordLength])
            if (wordTotal - wordLocation - wordLength < 25):
                self.labelSentenceRight.configure(text=str(self.communicationProtocal.SpeakQueue[0])[wordLocation+wordLength:wordTotal])
            else:
                self.labelSentenceRight.configure(text=str(self.communicationProtocal.SpeakQueue[0])[wordLocation+wordLength:wordLocation+wordLength+25])
        else:
            self.labelSentenceLeft.configure(text="...")
            self.labelSentenceSpoken.configure(text="...")
            self.labelSentenceRight.configure(text="...")

        if (self.communicationProtocal.SpeakQueue != None and self.listboxQueueToSpeak.size() != len(self.communicationProtocal.SpeakQueue)):
            self.listboxQueueToSpeak.delete(0,self.listboxQueueToSpeak.size())
            for x in xrange(0,len(self.communicationProtocal.SpeakQueue)):
                self.listboxQueueToSpeak.insert(x, str(x)+": "+self.communicationProtocal.SpeakQueue[x])

        if (self.currentVoice.get() != self.communicationProtocal.CurrentVoiceName):
            self.currentVoice.set(self.communicationProtocal.CurrentVoiceName)

        if self.speedValue != self.communicationProtocal.CurrentRate:
            self.intVarSpeed.set(self.communicationProtocal.CurrentRate) 
            self.speedValue = self.communicationProtocal.CurrentRate

        if self.recoverActionLabelText != self.communicationProtocal.recoveryTask:
            self.recoverActionLabelText = self.communicationProtocal.recoveryTask
            self.labelRecoverAction.configure(text=self.recoverActionLabelText)

        if self.GUIVisible != self.communicationProtocal.GUIVisible:
            # self.GUIVisible ? self.HideGui : self.ShowGui
            self.HideGui() if self.GUIVisible else self.ShowGui()
            
        self.tkRoot.after(1000/32,self.Update)

    def OnValidateEntrySpeakSpeed(self, d, i, P, s, S, v, V, W):
        try :
            int(S)
            return True
        except ValueError:
            return False

    def CallBackSetSpeed(self):
        self.communicationProtocal.handleSetSpeed(self.intVarSpeed.get())

    def CallBackReturnSay(self, event):
        self.CallBackButtonSay()

    def CallBackButtonSay(self):
        self.communicationProtocal.handleSay(self.stringVarTextToSay.get())
        
    def CallBackOptionMenuVoices(self, selectedItem):
        self.communicationProtocal.handleSetVoice(selectedItem)

    def Close(self):
        self.tkRoot.quit()
        
    def HideGui(self):
        self.GUIVisible = False
        self.communicationProtocal.GUIVisible = False
        self.tkRoot.withdraw()
        
    def ShowGui(self):
        self.GUIVisible = True
        self.communicationProtocal.GUIVisible = True
        self.tkRoot.deiconify()
class ListFrame(LabelFrame):
    """
    A Frame representing one of the search term lists
    (e.g. Hashtags, Excluded Users).

    Displays all the items in the list,
    and allows the user to add or remove items.
    Methods should not be called directly;
    instead they should be bound as event handlers.
    """
    def __init__(self, name, add_handler, remove_handler, master=None):
        """
        Creates a ListFrame with the given name as its title.

        add_handler and remove_handler are functions to be called
        when items are added or removed, and should relay the information
        back to the Searcher (or whatever object actually uses the list).
        """
        LabelFrame.__init__(self, master)
        self['text'] = name
        self.add_handler = add_handler
        self.remove_handler = remove_handler
        self.list = Listbox(self)
        self.list.grid(row=0, columnspan=2)
        # Tkinter does not automatically close the right-click menu for us,
        # so we must close it when the user clicks away from the menu.
        self.list.bind("<Button-1>", lambda event: self.context_menu.unpost())
        self.list.bind("<Button-3>", self.open_menu)
        self.context_menu = Menu(self, tearoff=0)
        self.context_menu.add_command(label="Remove", command=self.remove)
        self.input = Entry(self)
        self.input.bind("<Return>", lambda event: self.add())
        self.input.grid(row=1, columnspan=2)
        self.add_button = Button(self)
        self.add_button['text'] = "Add"
        self.add_button['command'] = self.add
        self.add_button.grid(row=2, column=0, sticky=W + E)
        self.remove_button = Button(self)
        self.remove_button['text'] = "Remove"
        self.remove_button['command'] = self.remove
        self.remove_button.grid(row=2, column=1, sticky=W + E)

    def add(self):
        """
        Add the item in the input line to the list.
        """
        self.list.insert(END, self.input.get())
        self.add_handler(self.input.get())
        self.input.delete(0, END)

    def remove(self):
        """
        Remove the active (highlighted) item from the list.
        """
        deleted = self.list.get(ACTIVE)
        self.list.delete(ACTIVE)
        self.remove_handler(deleted)

    def open_menu(self, event):
        """
        Opens a right-click menu for the selected item.
        Currently the menu only has an option for removing the item.
        """
        index = self.list.index("@" + str(event.x) + "," + str(event.y))
        if index < 0:
            return
        self.context_menu.post(event.x_root, event.y_root)
        self.list.activate(index)
        self.list.selection_clear(0, END)
        self.list.selection_set(ACTIVE)
Exemple #9
0
class CommSearch(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent        
        self.initUI()
        
    def initUI(self):

        self.entries_found = []

        self.parent.title("Search your command cards")
        self.style = Style()
        self.style.theme_use("default")        
        self.pack()
        
        self.input_title = Label(self, text="Enter your command below")
        self.input_title.grid(row=0, columnspan=2)
        self.input_box = Entry(self, width=90)
        self.input_box.grid(row=1, column=0)
        self.input_box.focus()
        self.input_box.bind("<Key>", self.onUpdateSearch)
        self.search_btn = Button(self, text="Search", command=self.onSearch)
        self.search_btn.grid(row=1, column=1)
        self.output_box = Treeview(self, columns=("Example"))
        ysb = Scrollbar(self, orient='vertical', command=self.output_box.yview)
        xsb = Scrollbar(self, orient='horizontal', command=self.output_box.xview)
        self.output_box.configure(yscroll=ysb.set, xscroll=xsb.set)
        self.output_box.heading('Example', text='Example', anchor='w')
        self.output_box.column("#0",minwidth=0,width=0, stretch=NO)
        self.output_box.column("Example",minwidth=0,width=785)
        self.output_box.bind("<Button-1>", self.OnEntryClick)
        self.output_box.grid(row=3, columnspan=2)
        self.selected_box = Text(self, width=110, height=19)
        self.selected_box.grid(row=4, columnspan=2)
        self.gotoadd_btn = Button(self, text="Go to Add", command=self.onGoToAdd)
        self.gotoadd_btn.grid(row=5)

    def OnEntryClick(self, event):
        try:
            item = self.output_box.selection()[0]
        except IndexError:
            pass
        entry_title = self.output_box.item(item,"value")
        for item in self.entries_found:
            if str(entry_title) == str("('" + item.title.strip('\n') + "',)"):
                self.selected_box.delete(0.1, END)
                self.selected_box.insert(END, item.text + '\n')

    def onUpdateSearch(self, key):
    # Somehow calling self.onSearch() does not register last key
    # And we need to correct "special chars"
        global entries, entries_map
        text_entries = ""
        for item in self.output_box.get_children():
            self.output_box.delete(item)		
    # ...like, for instance, deleting last character
        if key.char == '\b':
            search_terms = str(self.input_box.get()[:-1])
        else: 
            search_terms = str(self.input_box.get() + key.char)
        self.entries_found = []
        self.entries_found = data.Search(search_terms,entries,entries_map)
        for item in range(len(self.entries_found)):
            aux = self.output_box.insert('', 'end', '', value=[self.entries_found[item].title.split('\n')[0]])

			
    def onSearch(self):
        global entries, entries_map
        text_entries = ""
        for item in self.output_box.get_children():
            self.output_box.delete(item)
        search_terms = str(self.input_box.get())
        for item in data.Search(search_terms,entries,entries_map):
            self.output_box.insert('', 'end', '', value=[self.entries_found[item].title.split('\n')[0]])
			
    def onGoToAdd(self):
        newroot = Tk()
        newcomm = CommAdd(newroot)
        newroot.geometry("800x600+0+0")
        newroot.mainloop()
 def initUI(self):
   
     self.parent.title("Calculator")
     
     Style().configure("TButton", padding=(0, 5, 0, 5), 
         font='serif 10')
     
     self.columnconfigure(0, pad=3)
     self.columnconfigure(1, pad=3)
     self.columnconfigure(2, pad=3)
     self.columnconfigure(3, pad=3)
     
     self.rowconfigure(0, pad=3)
     self.rowconfigure(1, pad=3)
     self.rowconfigure(2, pad=3)
     self.rowconfigure(3, pad=3)
     self.rowconfigure(4, pad=3)
     
     def calculate():
         expression=entry.get()   
         entry.delete(0, END)
         entry.insert(0,str(eval(expression)))
         
     def evaluate(event):
         expression=entry.get()   
         entry.delete(0, END)
         entry.insert(0,str(eval(expression)))
    
     def selectNumber(char):
         entry.insert(END,char)
      
     def backSpace():
         entry.delete(len(entry.get())-1,END)
     
     def deleteAll():
         entry.delete(0, END)
         
     entry = Entry(self)
     entry.grid(row=0, columnspan=4, sticky=W+E)
     entry.bind("<Return>", evaluate)
     cls = Button(self, text="Cls", command=lambda: deleteAll())
     cls.grid(row=1, column=0)
     bck = Button(self, text="Back",command=lambda: backSpace())
     bck.grid(row=1, column=1)
     lbl = Button(self)
     lbl.grid(row=1, column=2)    
     clo = Button(self, text="Close",command=self.destroy)
     clo.grid(row=1, column=3)        
     sev = Button(self, text="7",command=lambda: selectNumber("7"))
     sev.grid(row=2, column=0)        
     eig = Button(self, text="8",command=lambda: selectNumber("8"))
     eig.grid(row=2, column=1)         
     nin = Button(self, text="9",command=lambda: selectNumber("9"))
     nin.grid(row=2, column=2) 
     div = Button(self, text="/",command=lambda: selectNumber("/"))
     div.grid(row=2, column=3) 
     
     fou = Button(self, text="4",command=lambda: selectNumber("4"))
     fou.grid(row=3, column=0)        
     fiv = Button(self, text="5",command=lambda: selectNumber("5"))
     fiv.grid(row=3, column=1)         
     six = Button(self, text="6",command=lambda: selectNumber("6"))
     six.grid(row=3, column=2) 
     mul = Button(self, text="*",command=lambda: selectNumber("*"))
     mul.grid(row=3, column=3)    
     
     one = Button(self, text="1",command=lambda: selectNumber("1"))
     one.grid(row=4, column=0)        
     two = Button(self, text="2",command=lambda: selectNumber("2"))
     two.grid(row=4, column=1)         
     thr = Button(self, text="3",command=lambda: selectNumber("3"))
     thr.grid(row=4, column=2) 
     mns = Button(self, text="-",command=lambda: selectNumber("-"))
     mns.grid(row=4, column=3)         
     
     zer = Button(self, text="0",command=lambda: selectNumber("0"))
     zer.grid(row=5, column=0)        
     dot = Button(self, text=".",command=lambda: selectNumber("."))
     dot.grid(row=5, column=1)         
     equ = Button(self, text="=",command=lambda: calculate())
     equ.grid(row=5, column=2) 
     pls = Button(self, text="+",command=lambda: selectNumber("+"))
     pls.grid(row=5, column=3)
     
     self.pack()
Exemple #11
0
        item = sortable_list.create_item(value=i)
        label = Label(item, text="this is a label %s"%i)
        label.pack(anchor=W, padx= (4,0), pady= (4,0))

        sortable_list.add_item(item)

    frame = Frame(root)
    frame.pack(fill=X, pady=(0, 10))
    
    indexVar = IntVar()
    label = Label(frame, text="Entry index of item to delete:")
    label.pack(side=LEFT, padx=(10,6))
    entry_of_index = Entry(frame,textvariable= indexVar, width=3)
    
    def delete_item():
        try:
            index = indexVar.get()
        except ValueError:
            messagebox.showerror("Error", "Not a valid integer")
            return

        entry_of_index.delete(0, END)
        sortable_list.delete_item(index)
    entry_of_index.bind('<Return>', delete_item)

    entry_of_index.pack(side=LEFT)
    
    Button(frame, text="Delete", command=delete_item).pack(side=LEFT, padx=(3,0))

    root.mainloop()
Exemple #12
0
class LoggerDialog(Toplevel):
    def __init__(self, master, customers, payments, refresh):
        Toplevel.__init__(self,master)

        self.root = master
        self.refresh = refresh

        self.title("Check In")
        self.iconname = "Check In"

        self.name = StringVar() # variable for customer
        self.customers = customers # customers object
        self.payments = payments
        self.names = []
        self.workout = StringVar()
        self.workouts = []
        self.workouts_form = []
        self.date = StringVar()
        self.date.set(strftime("%m/%d/%Y"))
        self.refresh_time = 15 # in minutes
        self.output = '' # for the output label at the bottom
        self.schedule = Schedule()

        self.logger = Logger() #throws IOError if file is open

        inf = Frame(self)
        inf.pack(padx=10,pady=10,side='top')
        Label(inf, text="Name:").grid(row=0,column=0,sticky=E,ipady=2,pady=2,padx=10)
        Label(inf, text='Date:').grid(row=1,column=0,sticky=E,ipady=2,pady=2,padx=10)
        Label(inf, text="Workout:").grid(row=2,column=0,sticky=E,ipady=2,pady=2,padx=10)

        self.name_cb = Combobox(inf, textvariable=self.name, width=30,
                                values=self.names)
        self.name_cb.grid(row=0,column=1,sticky=W,columnspan=2)
        self.date_ent = Entry(inf, textvariable=self.date)
        self.date_ent.grid(row=1,column=1,sticky=W)
        self.date_ent.bind('<FocusOut>', self.update_workouts)
        Button(inf,text='Edit', command=self.enable_date_ent).grid(row=1,column=2,sticky=E)
        self.workout_cb = Combobox(inf, textvariable=self.workout, width=30,
                                   values=self.workouts_form,state='readonly')
        self.workout_cb.grid(row=2,column=1,sticky=W,columnspan=2)

        self.log_btn=Button(inf,text="Log Workout",command=self.log,width=12)
        self.log_btn.grid(row=3,column=1,columnspan=2,pady=4,sticky='ew')
        
        stf = Frame(self)
        stf.pack(padx=10,pady=10,fill='x',side='top')
        self.scrolled_text = ScrolledText(stf,height=15,width=50,wrap='word',state='disabled')
        self.scrolled_text.pack(expand=True,fill='both')

        self.update_workouts()
        self.update_names()

        self.bind('<Return>',self.log)
        self.name_cb.focus_set()  # set the focus here when created

        #disable the date field
        self.disable_date_ent()

        #start time caller
        self.time_caller()

    def output_text(self,outstr):
        self.scrolled_text['state'] = 'normal'
        self.scrolled_text.insert('end',outstr)
        self.scrolled_text.see('end')
        self.scrolled_text['state'] = 'disabled'

    def log(self, e=None):
        #check to see if name is blank
        logged = False
        if self.name.get() == '':
            self.output_text("! - Please select your name.\n")
        elif self.workout.get() not in self.workouts_form:
            self.output_text("! - Select valid workout.\n")
        elif self.name.get() not in self.names: # new customer
            self.new_customer_error()
        else: # log the workout
            name = self.name.get().split(' ',2)
            (line, r) = self.customers.find(name[2],name[0],name[1])
            name_str = str(self.name.get())
            date = datetime.strptime(str(self.date.get()),'%m/%d/%Y')

            if not line:
                self.output_text("!! - No record: " + self.name.get() + ".\n")

            while (not logged):
                try:
                    self.logger.log(self.workouts[self.workout_cb.current()][0],
                                    self.workouts[self.workout_cb.current()][1],
                                    name_str, day=date)
                    logged = True
                except IOError:
                    showerror("Error writting to file", "Please close " + self.logger.filename + " and press OK.")


            if logged:
                self.output_text(self.name.get() + " - " + line[3] + "\n")
                logged_payment = False
                while(not logged_payment):
                    try:
                        if line[3] == 'Monthly':
                            payment_due = self.payments.next_payment_due(name_str)
                            if payment_due < datetime.today():
                                self.output_text("$ - Please pay your monthly dues.\n")
                            else:
                                self.output_text("$ - Next payment due: " + payment_due.strftime("%B %d, %Y\n"))
                        elif line[3] == 'Punch Card':
                            punch = self.payments.punch(name_str)
                            if punch == 0:
                                self.output_text("$ - Last punch on card, please purchase another.\n")
                            elif not punch:
                                self.output_text("$ - Please purchase another punch card.\n")
                            else:
                                self.output_text("$ - You have " + str(punch) + " remaining workouts on your card.\n")
                        elif line[3] == 'Drop In':
                            self.payments.drop_in(name_str, date)
                            self.output_text("$ - Drop In payment logged.\n")
                        logged_payment = True
                    except IOError:
                        # this is bad, you logged a workout and you failed to log payment
                        showerror("Error writting to file", "Please close " + self.payments.filename + " and press OK.")
                    else:
                        #exception not raised
                        try: #accessing log file here
                            workout_count = str(workouts_this_month(name_str,self.logger.filename,date.strftime("%B"))) 
                            self.output_text("Workouts you've completed this month: " + workout_count + "\n")
                        except IOError:
                            showerror("Error reading from file", "Please close " + self.logger.filename + " and press OK.")

                self.refresh()
            
    def new_customer_error(self):
        self.ncd = NewCustomerDialog(self,self.customers,self.refresh)
        if askquestion(title="New Customer?",
            message="Add new customer: " + self.name.get(),
            parent = self) == 'yes':

            temp = self.name.get().split(' ')
            self.ncd.fname.set(temp[0])
            if len(temp) == 2:
                self.ncd.lname.set(temp[1])
            elif len(temp) == 3:
                self.ncd.mname.set(temp[1])
                self.ncd.lname.set(temp[2])
            elif len(temp) > 3:
                self.ncd.mname.set(temp[1])
                self.ncd.lname.set(' '.join(temp[2:4]))

            self.ncd.show()

        if self.ncd.new_customer_name:
            self.add_name(self.ncd.new_customer_name)
            self.output_text("+ - " + self.ncd.new_customer_name + " added.\n")

    def disable_date_ent(self, e=None):
        self.date_ent['state'] = 'disabled'

    def enable_date_ent(self, e=None):
        self.date_ent['state'] = 'normal'
        
    def time_caller(self):
        #updates every 15 min automatically
        msec = self.refresh_time * 6000

        self.update_time_now() #update time to current time
        self.set_workout_now()
        self.update_workouts() #update the workouts
        
        self.after(msec, self.time_caller) #call again

    def update_time_now(self):
        self.enable_date_ent()
        self.date.set(strftime("%m/%d/%Y"))

    def set_workout_now(self):
        #set workout field
        if len(self.workouts) == 0:
            self.disable_date_ent()
            return #no workouts
        index = 0
        now = datetime.today()
        for i, workout in enumerate(self.workouts):
            test = datetime.combine(date.today(),workout[0])
            if now < (test - timedelta(minutes=15)):
                index = i
                break
        self.workout_cb.current(index)
        self.disable_date_ent()
            
    def update_workouts(self, e=None):
        try:
            self.populate_workouts()
            self.workout_cb['values'] = self.workouts_form
        except ValueError:
            self.workout.set(' Enter Valid Date ')
        if len(self.workouts) > 0 and e:
            self.workout_cb.current(0)
            
    def populate_workouts(self):
        today = datetime.strptime(str(self.date.get()), "%m/%d/%Y") #get date
        dow = self.schedule.weekday_to_str(today.weekday()) #get dow string

        self.workouts = self.schedule.get_wkday(dow)
        self.workouts_form = []
        for w in self.workouts:
            self.workouts_form.append(w[0].strftime("%H:%M") + ' - ' + w[1])
        if len(self.workouts) == 0:
            self.workout.set(' No workouts today ')

    def update_names(self):
        self.populate_names()
        if len(self.names) == 0: self.names = ['']
        self.name_cb['values'] = self.names
        self.name_cb.set(' ')

    def add_name(self, name):
        self.names.append(name)
        split_names = [x.split(' ') for x in self.names]
        split_names.sort(key = lambda x: ' '.join([x[2],x[0],x[1]]))
        self.names = [' '.join(x) for x in split_names]
        self.name_cb['values'] = self.names
        self.name.set(name)
        
    def populate_names(self):
        try:
            clist = self.customers.get_list()
        except IOError:
            self.output_text("! - " + self.customers.filename + " open in another application.\n")
            return
        clist.sort(key = lambda x: ', '.join(x[0:3]).lower())
        self.names = []
        for line in clist:
            self.names.append(' '.join([line[1],line[2],line[0]]))

    def find_line(self, name):
        [fname, mname, lname] = name.split(' ')
        try:
            return self.customers.find(lname, fname, mname)
        except IOError:
            self.output_text("! - " + self.customers.filename + " open in another application.\n")
            return None
Exemple #13
0
class ElementalCodingGUI(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.elemental_coding = ElementalCoding()
        self.huffman_coding = HuffmanCoding()
        self.dictionary_coding = DictionaryCoding()
        self.init_ui()
        self.current_encoding = 5

    def init_ui(self):
        self.parent.title("Information Theory")
        Style().configure("TButton", padding=(0, 5, 0, 5), font='Verdana 10')

        self.columnconfigure(0, pad=3)
        self.columnconfigure(1, pad=3)
        self.columnconfigure(2, pad=3)
        self.columnconfigure(3, pad=3)
        self.columnconfigure(4, pad=3)

        self.rowconfigure(0, pad=3)
        self.rowconfigure(1, pad=3)
        self.rowconfigure(2, pad=3)
        self.rowconfigure(3, pad=3)
        self.rowconfigure(4, pad=3)
        self.rowconfigure(5, pad=3)

        string_to_search_label = Label(self, text="Search a string: ")
        string_to_search_label.grid(row=0, column=0, rowspan=2)
        self.string_to_search_textfield = Entry(self)
        self.string_to_search_textfield.grid(row=0, column=1, rowspan=2, columnspan=2, sticky=W)
        self.string_to_search_textfield.bind('<Return>', self.get_string_from_textfield)
        self.compression_ratio_text = StringVar()
        self.compression_ratio_text.set('Compression Ratio: ')
        compression_ratio_label = Label(self, textvariable=self.compression_ratio_text).grid(row=0, column=2,
                                                                                             columnspan=4)

        Separator(self, orient=HORIZONTAL).grid(row=1)
        string_to_encode_label = Label(self, text="Encode a string: ")
        string_to_encode_label.grid(row=2, column=0, rowspan=2)
        self.string_to_encode_textfield = Entry(self)
        self.string_to_encode_textfield.grid(row=2, column=1, rowspan=2, columnspan=2, sticky=W)
        self.string_to_encode_textfield.bind('<Return>', self.get_string_from_textfield_to_encode)

        Separator(self, orient=HORIZONTAL).grid(row=3)
        self.area = Text(self)
        self.area.grid(row=4, column=0, columnspan=3, rowspan=1, padx=5, sticky=E + W)
        self.area.config(width=10, height=15)
        self.possible_options_text = StringVar()
        self.possible_options_text.set("Possible Options: ")
        self.possible_options_label = Label(self, textvariable=self.possible_options_text).grid(row=4, column=3,
                                                                                                sticky=N)

        huffman_coding_button = Button(self, text="Huffman",
                                       command=self.huffman_coding_callback).grid(row=5, column=0)
        arithmetic_coding_button = Button(self, text="Arithmetic Coding",
                                          command=self.arithmetic_coding_callback).grid(row=5, column=1)
        dictionary_coding_button = Button(self, text="Dictionary",
                                          command=self.dictionary_coding_callback).grid(row=5, column=2)
        elias_coding_button = Button(self, text="Elias",
                                     command=self.elias_coding_callback).grid(row=5, column=3)
        our_coding_button = Button(self, text="Elemental Coding",
                                   command=self.elemental_coding_callback).grid(row=5, column=4)
        self.pack()
        self.elemental_coding_callback()

    def get_string_from_textfield_to_encode(self, event):
        text_to_encode = self.string_to_encode_textfield.get()
        if text_to_encode == '':
            text_to_encode = 'a'
        if self.current_encoding == 1:
            self.huffman_coding.encode(text_to_encode)
            self.set_text_in_text_area(output)
            compression_ratio = self.huffman_coding.compression_ratio
            self.compression_ratio_text.set('Compression Ratio: ' + str(compression_ratio))
        if self.current_encoding == 2:
            pass
        if self.current_encoding == 3:
            pass
        if self.current_encoding == 4:
            pass
        if self.current_encoding == 5:
            self.elemental_coding.getElementList()
            self.elemental_coding.codeElemental(text_to_encode)
            self.elemental_coding.encodeText()
            output = self.elemental_coding.printCodedText()
            compression_ratio = self.elemental_coding.get_compression_ratio()
            self.compression_ratio_text.set('Compression Ratio: ' + str(compression_ratio))
            #self.set_text_in_text_area(output)

    def get_string_from_textfield(self, event):
        text_to_encode = self.string_to_sitemearch_textfield.get()
        possible_options = self.elemental_coding.lookForString(text_to_encode)
        self.possible_options_text.set('Possible Options: ' + possible_options)
        self.string_to_search_textfield.delete(END)

    def huffman_coding_callback(self):
        self.current_encoding = 1
        output = self.huffman_coding.encode_default_file()
        self.set_text_in_text_area(output)
        compression_ratio = self.huffman_coding.compression_ratio
        self.compression_ratio_text.set('Compression Ratio: ' + str(compression_ratio))
        print "HUFMAAN!"

    def arithmetic_coding_callback(self):
        self.current_encoding = 2
        text_to_encode = self.string_to_encode_textfield.get()
        if text_to_encode == '':
            text_to_encode = ' '
        for char in text_to_encode:
            if char not in arithmetic_intervals:
                can_encode = False
            else:
                can_encode = True
        if can_encode:
            codificacion = interval_coding(text_to_encode, arithmetic_intervals)
            self.compression_ratio_text.set(str(codificacion[2]))
        else:
            self.compression_ratio_text.set("Error: no en intervalos\n"
                                            "Si desea comprobar este metodo,"
                                            "introduce un string en el cuadro\n"
                                            "\"Encode text\"")

        print "Arithmetic!"

    def dictionary_coding_callback(self):
        self.current_encoding = 3
        contents = get_file_contents(os.getcwd() + '/pagina.txt')
        compress_text = self.dictionary_coding.compress(contents)
        compression_ratio = len(compress_text) / float(len(contents))
        self.compression_ratio_text.set('Compression Ratio: ' + str(compression_ratio) )
        compress_text = [str(item) for item in compress_text]
        self.set_text_in_text_area(''.join(compress_text))
        print "Dictionary!"

    def elias_coding_callback(self):
        self.current_encoding = 4
        text_to_encode = self.string_to_encode_textfield.get()
        if text_to_encode == '':
            text_to_encode = ' '
        for char in text_to_encode:
            if char not in elias_intervals:
                can_encode = False
            else:
                can_encode = True
        if can_encode:
            codificacion = interval_coding(text_to_encode, elias_intervals)
            self.compression_ratio_text.set(str(codificacion[2]) + "%")
        else:
            self.compression_ratio_text.set("Error: no en intervalos\n"
                                            "Si desea comprobar este metodo,"
                                            "introduce un string en el cuadro\n"
                                            "\"Encode text\"")


    def set_text_in_text_area(self, output):
        self.area.config(state=NORMAL)
        self.area.delete("1.0", END)
        self.area.insert(INSERT, output)
        self.area.config(state=DISABLED)

    def elemental_coding_callback(self):
        self.current_encoding = 5
        self.elemental_coding.getElementList()
        self.elemental_coding.processFile('pagina.txt')
        self.elemental_coding.encodeText()
        output = self.elemental_coding.printCodedText()
        self.set_text_in_text_area(output)
        compression_ratio = self.elemental_coding.get_compression_ratio()
        self.compression_ratio_text.set('Compression Ratio: ' + str(compression_ratio))
        print "Our Coding!"
Exemple #14
0
class GUI(Frame):
    def __init__(self, parent, register):
        Frame.__init__(self, parent, padding=(3, 3, 3, 3))
        self.parent = parent
        self.register = register
        self.logger = register.get_events_logger()
        self.init_ui()

        self.login()
        self.update_order()

    def login(self):
        logged_in = False
        while not logged_in:
            token = None
            while token is None:
                token = askstring(title="Please login", prompt="Login")
            try:
                self.register.login_employee(token)
                logged_in = True
            except CredentialException:
                self.logger.warning("invalid employee token '" + token +
                                    "', " + "unable to login")
        self.name_var.set(register.get_employee_name())
        # Put focus in barcode field
        self.barcode_field.focus()

    def logout(self, *args):
        self.register.logout_employee()
        self.name_var.set("")
        self.login()

    def print_count(self):
        try:
            print self.register.get_register_count()
        except CredentialException:
            self.logger.warning("insufficient privileges to print register " +
                                "count")
        # Put focus in barcode field
        self.barcode_field.focus()

    def add(self, token):
        try:
            self.register.add(token)
        except CredentialException:
            self.logger.warning("insufficient privileges to add an item")
        except ValueError:
            pass
        finally:
            self.update_order()
            # Put focus in barcode field
            self.barcode_field.focus()

    def add_custom(self, *args):
        name = askstring(title="Enter item name", prompt="Item name")
        if name is not None:
            price = askfloat(title="Enter item price", prompt="Item price")
            if price is not None:
                try:
                    self.register.add_custom(name, price)
                except CredentialException:
                    self.logger.warning("insufficient privileges to add " +
                                        "a custom item")
                except ValueError as e:
                    self.logger.warning(e.__str__)
                finally:
                    self.update_order()
        # Put focus in barcode field
        self.barcode_field.focus()

    def remove(self, token):
        try:
            self.register.remove(token)
        except CredentialException:
            self.logger.warning("insufficient privileges to scan an item")
        except ValueError:
            self.logger.warning("token does not correspond to any item")
        except ItemNotFoundException:
            self.logger.warning("item not in order, unable to remove it")
        finally:
            self.update_order()
            # Put focus in barcode field
            self.barcode_field.focus()

    def clear_order(self, *args):
        try:
            self.register.clear_order()
        except CredentialException:
            self.logger.warning("insufficient privileges to clear the order")
        finally:
            self.update_order()
            # Put focus in barcode field
            self.barcode_field.focus()

    def adjust(self, *args):
        amount = askfloat(title="Enter adjustment amount",
                          prompt="Adjustment amount")
        if amount is not None:
            try:
                self.register.adjust(amount)
            except CredentialException:
                self.logger.warning("insufficient privileges to adjust " +
                                    "register count")
            except ValueError as e:
                self.logger.warning("invalid adjustment amount: " + e)
        # Put focus in barcode field
        self.barcode_field.focus()

    def checkout(self, *args):
        try:
            self.register.checkout_order()
        except CredentialException:
            self.logger.warning("insufficient privileges to checkout order")
        finally:
            self.update_order()
        # Put focus in barcode field
        self.barcode_field.focus()

    def count(self, *args):
        # TODO: implement a proper register count
        # TODO: add dialog box telling how register count went
        count = askfloat(title="Enter register count", prompt="Register count")
        if count is not None:
            try:
                self.register.count_register(count)
            except CredentialException:
                self.logger.warning("insufficient privileges to count " +
                                    "register")
        # Put focus in barcode field
        self.barcode_field.focus()

    def parse_barcode_field(self, event):
        command = self.barcode_field.get().strip()
        self.barcode_var.set("")
        tokens = command.split(" ")
        if tokens[0] == "print_count":
            self.print_count()
        elif tokens[0] == "print_order":
            self.print_order()
        elif tokens[0] == "remove":
            if len(tokens) < 2:
                self.logger.warning("need an item to remove")
                return None
            self.remove(tokens[1])
        elif tokens[0] == "adjust_count":
            if len(tokens) < 2:
                self.logger.warning("need an adjustment amount")
                return None
            self.adjust(tokens[1])
        elif tokens[0] == "custom":
            if len(tokens) < 3:
                self.logger.warning("need an name and a price")
                return None
            try:
                self.add_custom(tokens[1], float(tokens[2]))
            except ValueError:
                self.logger.warning("price is not valid")
        elif tokens[0] == "checkout":
            self.checkout()
        elif tokens[0] == "count":
            if len(tokens) < 2:
                self.logger.warning("need an register count")
                return None
            else:
                self.count(tokens[1])
        else:
            if tokens[0] != "":
                self.add(tokens[0])
        # Put focus in barcode field
        self.barcode_field.focus()

    def update_order(self):
        self.items_var.set(
            tuple(item.get_name() + " x " + str(quantity)
                  for item, quantity in self.register.get_order().items()))
        self.total_var.set("Total: %0.2f$" % self.register.get_order_total())
        # Put focus in barcode field
        self.barcode_field.focus()

    def init_ui(self):
        # Window configuration
        screen_width = self.parent.winfo_screenwidth()
        screen_height = self.parent.winfo_screenheight()
        self.parent.geometry('%dx%d+%d+%d' %
                             (screen_width, screen_height, 0, 0))
        self.parent.title("Caisse Planck")
        self.parent.rowconfigure(0, weight=1)
        self.parent.columnconfigure(0, weight=1)

        self.grid(column=0, row=0, sticky=(N, S, E, W))
        self.rowconfigure(0, weight=0)
        self.rowconfigure(1, weight=1)
        self.rowconfigure(2, weight=1)
        self.rowconfigure(3, weight=1)
        self.rowconfigure(4, weight=1)
        self.rowconfigure(7, weight=0)
        self.rowconfigure(8, weight=0)
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=0)
        self.columnconfigure(2, weight=0)

        self.items_var = StringVar()
        self.items_list = Listbox(self, height=10, listvariable=self.items_var)
        self.items_list.grid(row=1, column=0, rowspan=8, sticky=(N, S, E, W))

        self.barcode_var = StringVar(self)
        self.barcode_field = Entry(self, textvariable=self.barcode_var)
        self.barcode_field.bind("<Return>", self.parse_barcode_field)
        self.barcode_field.grid(row=0, column=0, sticky=(N, E, W))

        self.benevole_label = Label(self, text="Volunteer:")
        self.benevole_label.grid(row=0, column=1, sticky=(N, W))

        self.name_var = StringVar(self)
        self.name_label = Label(self, textvar=self.name_var)
        self.name_label.grid(row=0, column=2, sticky=(N, W))

        self.parent.bind("<F1>", self.logout)
        self.logout_button = Button(self,
                                    text="Logout (F1)",
                                    command=self.logout)
        self.logout_button.grid(row=1, column=1, columnspan=2, sticky=(E, W))

        self.parent.bind("<F5>", self.count)
        self.count_button = Button(self,
                                   text="Count register (F5)",
                                   command=self.count)
        self.count_button.grid(row=2, column=1, columnspan=2, sticky=(E, W))

        self.parent.bind("<F6>", self.adjust)
        self.adjust_button = Button(self,
                                    text="Register adjustment (F6)",
                                    command=self.adjust)
        self.adjust_button.grid(row=3, column=1, columnspan=2, sticky=(E, W))

        self.parent.bind("<F6>", self.add_custom)
        self.custom_item_button = Button(self,
                                         text="Custom item (F7)",
                                         command=self.add_custom)
        self.custom_item_button.grid(row=4,
                                     column=1,
                                     columnspan=2,
                                     sticky=(E, W))

        self.total_var = StringVar(self, value="Total: 0.00$")
        self.total_label = Label(self, textvar=self.total_var)
        self.total_label.grid(row=7, column=1, columnspan=2, sticky=(S, E, W))

        self.parent.bind("<F12>", self.checkout)
        self.ok_button = Button(self, text="Ok (F12)", command=self.checkout)
        self.ok_button.grid(row=8, column=1, sticky=(S, E, W))

        self.parent.bind("<Escape>", self.clear_order)
        self.cancel_button = Button(self,
                                    text="Cancel (ESC)",
                                    command=self.clear_order)
        self.cancel_button.grid(row=8, column=2, sticky=(S, E, W))
Exemple #15
0
class ListFrame(LabelFrame):
    """
    A Frame representing one of the search term lists
    (e.g. Hashtags, Excluded Users).

    Displays all the items in the list,
    and allows the user to add or remove items.
    Methods should not be called directly;
    instead they should be bound as event handlers.
    """

    def __init__(self, name, add_handler, remove_handler, master=None):
        """
        Creates a ListFrame with the given name as its title.

        add_handler and remove_handler are functions to be called
        when items are added or removed, and should relay the information
        back to the Searcher (or whatever object actually uses the list).
        """
        LabelFrame.__init__(self, master)
        self['text'] = name
        self.add_handler = add_handler
        self.remove_handler = remove_handler
        self.list = Listbox(self)
        self.list.grid(row=0, columnspan=2)
        # Tkinter does not automatically close the right-click menu for us,
        # so we must close it when the user clicks away from the menu.
        self.list.bind("<Button-1>", lambda event: self.context_menu.unpost())
        self.list.bind("<Button-3>", self.open_menu)
        self.context_menu = Menu(self, tearoff=0)
        self.context_menu.add_command(label="Remove", command=self.remove)
        self.input = Entry(self)
        self.input.bind("<Return>", lambda event: self.add())
        self.input.grid(row=1, columnspan=2)
        self.add_button = Button(self)
        self.add_button['text'] = "Add"
        self.add_button['command'] = self.add
        self.add_button.grid(row=2, column=0, sticky=W+E)
        self.remove_button = Button(self)
        self.remove_button['text'] = "Remove"
        self.remove_button['command'] = self.remove
        self.remove_button.grid(row=2, column=1, sticky=W+E)

    def add(self):
        """
        Add the item in the input line to the list.
        """
        self.list.insert(END, self.input.get())
        self.add_handler(self.input.get())
        self.input.delete(0, END)

    def remove(self):
        """
        Remove the active (highlighted) item from the list.
        """
        deleted = self.list.get(ACTIVE)
        self.list.delete(ACTIVE)
        self.remove_handler(deleted)

    def open_menu(self, event):
        """
        Opens a right-click menu for the selected item.
        Currently the menu only has an option for removing the item.
        """
        index = self.list.index("@" + str(event.x) + "," + str(event.y))
        if index < 0:
            return
        self.context_menu.post(event.x_root, event.y_root)
        self.list.activate(index)
        self.list.selection_clear(0, END)
        self.list.selection_set(ACTIVE)
Exemple #16
0
class CommSearch(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent
        self.initUI()

    def initUI(self):

        self.entries_found = []

        self.parent.title("Search your command cards")
        self.style = Style()
        self.style.theme_use("default")
        self.pack()

        self.input_title = Label(self, text="Enter your command below")
        self.input_title.grid(row=0, columnspan=2)
        self.input_box = Entry(self, width=90)
        self.input_box.grid(row=1, column=0)
        self.input_box.focus()
        self.input_box.bind("<Key>", self.onUpdateSearch)
        self.search_btn = Button(self, text="Search", command=self.onSearch)
        self.search_btn.grid(row=1, column=1)
        self.output_box = Treeview(self, columns=("Example"))
        ysb = Scrollbar(self, orient='vertical', command=self.output_box.yview)
        xsb = Scrollbar(self,
                        orient='horizontal',
                        command=self.output_box.xview)
        self.output_box.configure(yscroll=ysb.set, xscroll=xsb.set)
        self.output_box.heading('Example', text='Example', anchor='w')
        self.output_box.column("#0", minwidth=0, width=0, stretch=NO)
        self.output_box.column("Example", minwidth=0, width=785)
        self.output_box.bind("<Button-1>", self.OnEntryClick)
        self.output_box.grid(row=3, columnspan=2)
        self.selected_box = Text(self, width=110, height=19)
        self.selected_box.grid(row=4, columnspan=2)
        self.gotoadd_btn = Button(self,
                                  text="Go to Add",
                                  command=self.onGoToAdd)
        self.gotoadd_btn.grid(row=5)

    def OnEntryClick(self, event):
        try:
            item = self.output_box.selection()[0]
        except IndexError:
            pass
        entry_title = self.output_box.item(item, "value")
        for item in self.entries_found:
            if str(entry_title) == str("('" + item.title.strip('\n') + "',)"):
                self.selected_box.delete(0.1, END)
                self.selected_box.insert(END, item.text + '\n')

    def onUpdateSearch(self, key):
        # Somehow calling self.onSearch() does not register last key
        # And we need to correct "special chars"
        global entries, entries_map
        text_entries = ""
        for item in self.output_box.get_children():
            self.output_box.delete(item)

    # ...like, for instance, deleting last character
        if key.char == '\b':
            search_terms = str(self.input_box.get()[:-1])
        else:
            search_terms = str(self.input_box.get() + key.char)
        self.entries_found = []
        self.entries_found = data.Search(search_terms, entries, entries_map)
        for item in range(len(self.entries_found)):
            aux = self.output_box.insert(
                '',
                'end',
                '',
                value=[self.entries_found[item].title.split('\n')[0]])

    def onSearch(self):
        global entries, entries_map
        text_entries = ""
        for item in self.output_box.get_children():
            self.output_box.delete(item)
        search_terms = str(self.input_box.get())
        for item in data.Search(search_terms, entries, entries_map):
            self.output_box.insert(
                '',
                'end',
                '',
                value=[self.entries_found[item].title.split('\n')[0]])

    def onGoToAdd(self):
        newroot = Tk()
        newcomm = CommAdd(newroot)
        newroot.geometry("800x600+0+0")
        newroot.mainloop()