Пример #1
0
class SelectMultiple(TwoCells):
    def __init__(self, parent, text, values, **kwargs):
        super().__init__(parent, **kwargs)
        self.label = Label(self.frame, text=text)
        self.label.grid(column=0, row=0, padx=5, pady=5, sticky=W)
        self.selected_options = StringVar(self.frame)
        self.selected_options.set(values)
        self.listbox = Listbox(self.frame,
                               listvariable=self.selected_options,
                               selectmode=MULTIPLE)
        self.listbox.grid(column=1, row=0, padx=5, pady=5, sticky=E)

    def disable(self):
        self.listbox.configure(state=DISABLED)
        return self

    def enable(self):
        self.listbox.configure(state=NORMAL)
        return self

    def set(self, values):
        if values:
            self.enable()
        else:
            self.disable()
        self.listbox.selection_clear(0, self.listbox.size())
        for value in values:
            for index in range(self.listbox.size()):
                if value == self.listbox.get(index):
                    self.listbox.selection_set(index)
                    self.listbox.event_generate("<<ListboxSelect>>")

    def get(self):
        return [self.listbox.get(i) for i in self.listbox.curselection()]
Пример #2
0
    def __init__(self):
        super().__init__()
        # -----------------------------------------INPUT--------------------------------------------------
        global inputText
        inputFrame = LabelFrame(self, bd=0, text='Ввод текста')
        inputText = Text(inputFrame, height=8, width=80, wrap=WORD)
        # -------------------------------------------OUTPUT------------------------------------------------
        global outputText
        outputFrame = LabelFrame(self, bd=0, text='Вывод словаря')
        outputText = Listbox(outputFrame, height=10, width=120)
        scrollb = Scrollbar(outputFrame, command=outputText.yview)
        scrollb.grid(row=4, column=5, sticky='nsew')
        outputText.grid(row=4, column=0, sticky='nsew', columnspan=5)
        outputText.configure(yscrollcommand=scrollb.set)
        # ------------------------------------------MENU---------------------------------------------------
        mainMenu = Menu(self)
        fileSubMenu = Menu(mainMenu, tearoff=0)
        fileSubMenu.add_command(label="Новый файл", command=newFile)
        fileSubMenu.add_command(label="Открыть...", command=openFile)
        fileSubMenu.add_command(label="Сохранить...", command=saveFile)
        fileSubMenu.add_command(label="Печать...", command=printFile)
        fileSubMenu.add_command(label="Выход", command=self.exitFile)

        helpSubMenu = Menu(mainMenu, tearoff=0)
        helpSubMenu.add_command(label="Помощь", command=helpMenu)
        helpSubMenu.add_command(label="О программе", command=aboutProgramMenu)

        mainMenu.add_cascade(label="Файл", menu=fileSubMenu)
        mainMenu.add_cascade(label="Справка", menu=helpSubMenu)
        self.config(menu=mainMenu)
        # ------------------------------------------Buttons---------------------------------------------------
        buttonsFrame = Frame(self, bd=5)
        addWordsButton = Button(buttonsFrame,
                                text='Добавить',
                                width=25,
                                height=2)
        addWordsButton.config(command=addWord)
        addWordsButton.pack(side='left')
        spaceLabel1 = Label(buttonsFrame, width=7, height=2)
        spaceLabel1.pack(side='left')
        addWordsButton = Button(buttonsFrame,
                                text='Очистить',
                                width=25,
                                height=2)
        addWordsButton.config(command=cleanWord)
        addWordsButton.pack(side='left')
        spaceLabel2 = Label(buttonsFrame, width=7, height=2)
        spaceLabel2.pack(side='left')
        generateNewWordsButton = Button(buttonsFrame,
                                        text='Сгенерировать',
                                        width=25,
                                        height=2)
        generateNewWordsButton.config(command=generateWord)
        generateNewWordsButton.pack(side='left')
        self.title('Lab 1')
        outputFrame.pack()
        inputFrame.pack()
        inputText.pack()
        buttonsFrame.pack()
        self.geometry('800x400')
Пример #3
0
class AlexListBox(Frame):
    def __init__(self,
                 parent,
                 items=[],
                 width=20,
                 height=10,
                 selectioncommand=None):

        super().__init__(parent)

        self.selectioncommand = selectioncommand

        self.listbox = Listbox(self, width=width, height=height)
        self.listbox.grid(row=0, column=0)
        scrollbar_y = AlexScrollbar(self, command=self.listbox.yview)
        scrollbar_y.grid(row=0, column=1, sticky=N + S)
        self.listbox.configure(yscrollcommand=scrollbar_y.set)
        scrollbar_x = AlexScrollbar(self,
                                    command=self.listbox.xview,
                                    orient=HORIZONTAL)
        scrollbar_x.grid(row=1, column=0, sticky=E + W)
        self.listbox.configure(xscrollcommand=scrollbar_x.set)
        if self.selectioncommand is not None:
            self.listbox.bind('<<ListboxSelect>>', self._select_callback)
        self.set_items(items)

    def _select_callback(self, event):

        selection = self.get()
        # ignore unselect
        if selection != None:
            self.selectioncommand(selection)

    def set_items(self, items):

        self.listbox.delete(0, END)
        self.items = []
        for item in items:
            self.items.append(item)
            self.listbox.insert(END, "%s" % item)

    def get_items(self):

        return self.items

    def get(self):

        selections = self.listbox.curselection()
        if len(selections) > 0:
            return self.items[selections[0]]
        else:
            return None

    def set(self, selection):

        self.listbox.selection_clear(0, len(self.items))
        for i in range(0, len(self.items)):
            if self.items[i] == selection:
                self.listbox.selection_set(i)
Пример #4
0
class FeasDisp(ttk.Frame):
    """Widget for displaying all of the feasible states in the conflict."""

    def __init__(self, master=None, conflict=None, *args):
        """Initialize the widget."""
        ttk.Frame.__init__(self, master, padding=5)
        self.columnconfigure(1, weight=1)
        self.rowconfigure(2, weight=1)

        self.conflict = conflict

        self.dispFormat = StringVar(value='pattern')
        self.dispList = StringVar()
        self.feasList = []

        self.fmts = {'Pattern': 'YN-', 'List (YN)': 'YN',
                     'List (ordered and [decimal])': 'ord_dec'}
        cBoxOpts = ('Pattern', 'List (YN)', 'List (ordered and [decimal])')
        self.feasText = ttk.Label(self, text='Feasible States')
        self.feasText.grid(row=0, column=0, columnspan=3)
        self.cBox = ttk.Combobox(self, textvariable=self.dispFormat,
                                 values=cBoxOpts, state='readonly')
        self.cBoxLb = ttk.Label(self, text='Format:')
        self.feasLBx = Listbox(self, listvariable=self.dispList)
        self.scrl = ttk.Scrollbar(self, orient=VERTICAL,
                                  command=self.feasLBx.yview)

        # ###########
        self.cBoxLb.grid(column=0, row=1, sticky=NSEW, pady=3)
        self.cBox.grid(column=1, row=1, columnspan=2, sticky=NSEW, pady=3)
        self.feasLBx.grid(column=0, row=2, columnspan=2, sticky=NSEW)
        self.scrl.grid(column=2, row=2, sticky=NSEW)

        self.cBox.bind('<<ComboboxSelected>>', self.fmtSel)
        self.feasLBx.configure(yscrollcommand=self.scrl.set)

        self.dispFormat.set('Pattern')
        self.fmtSel()

    def fmtSel(self, *args):
        """Action on selection of a new format."""
        self.refreshList()

    def setFeas(self, feasList):
        """Change the list of feasible states to be displayed."""
        self.feasList = feasList
        self.refreshList()

    def refreshList(self):
        """Update the list of feasible states displayed and the format."""
        fmt = self.fmts[self.dispFormat.get()]
        if fmt == "YN-":
            feas = self.conflict.feasibles.dash
        if fmt == "YN":
            feas = self.conflict.feasibles.yn
        if fmt == "ord_dec":
            feas = self.conflict.feasibles.ordDec
        self.dispList.set(tuple(feas))
Пример #5
0
def main():
    root = Tk()
    backend.create()
    root.title("Bookstore manager")
    root.resizable(False, False)
    title_label = Label(root, text="Title")
    title_entry = Entry(root)
    author_label = Label(root, text="Author")
    author_entry = Entry(root)
    year_label = Label(root, text="Year")
    year_entry = Entry(root)
    isbn_label = Label(root, text="ISBN")
    isbn_entry = Entry(root)
    scroll = Scrollbar(root, orient="vertical", width=20)
    view_all = Button(root, text="View All", width=17,
                      command=lambda: backend.print_all(listbox))
    search_entry = Button(root, text="Search Entry", width=17,
                          command=lambda: backend.search(listbox,
                                                         title_entry.get(),
                                                         author_entry.get(),
                                                         year_entry.get(),
                                                         isbn_entry.get()))
    add_entry = Button(root, text="Add Entry", width=17,
                       command=lambda: backend.insert(listbox,
                                                      title_entry.get(),
                                                      author_entry.get(),
                                                      int(year_entry.get()),
                                                      int(isbn_entry.get())))
    update = Button(root, text="Update", width=17,
                    command=lambda: backend.update(listbox, title_entry,
                                                   author_entry,
                                                   year_entry,
                                                   isbn_entry))
    delete = Button(root, text="Delete", width=17,
                    command=lambda: backend.delete(listbox))
    close = Button(root, text="Close", width=17, command=root.quit)
    listbox = Listbox(root, height=12, width=27)
    listbox.configure(yscrollcommand=scroll.set)
    scroll.configure(command=listbox.yview)
    title_label.grid(row=0, column=0, padx=10)
    title_entry.grid(row=0, column=1, padx=10, pady=2)
    author_label.grid(row=0, column=2)
    author_entry.grid(row=0, column=3, padx=10)
    year_label.grid(row=1, column=0)
    year_entry.grid(row=1, column=1, padx=10)
    isbn_label.grid(row=1, column=2)
    isbn_entry.grid(row=1, column=3, padx=10, pady=2)
    listbox.grid(row=2, column=0, rowspan=6, columnspan=2, padx=2, pady=6)
    scroll.grid(row=2, column=2, rowspan=6)
    view_all.grid(row=2, column=3)
    search_entry.grid(row=3, column=3)
    add_entry.grid(row=4, column=3)
    update.grid(row=5, column=3)
    delete.grid(row=6, column=3)
    close.grid(row=7, column=3)
    root.mainloop()
Пример #6
0
class Onglet:
    def __init__(self, root, title, data):
        #creation d'un onglet
        self.resultScreen = Listbox(root, width='1200', fg='black')
        self.resultScreen.pack()

        #ajout de la barre de scroll
        self.scroll = Scrollbar(self.resultScreen,
                                command=self.resultScreen.yview)
        self.scroll.pack()

        #configuration de la typo
        self.resultScreen.configure(font='System')
        self.resultScreen.configure(yscrollcommand=self.scroll.set)

        #ajout de l'onglet a la fenetre
        root.add(self.resultScreen, text=title)
Пример #7
0
class Output(Frame):
    def __init__(self, parent, *args, **kwargs):
        super(Output, self).__init__(parent, *args, **kwargs)
        self.create_list()
        self.pack_propagate(False)

    def create_list(self):
        self.listbox = Listbox(self)
        scroll = Scrollbar(self, orient='vertical', command=self.listbox.yview)
        self.listbox.configure(yscrollcommand=scroll.set)

        self.listbox.pack(side='left', fill='both', expand=True)
        scroll.pack(side='left', fill='y')

    def insert(self, value):
        self.listbox.insert('end', str(value))

    def clear(self):
        self.listbox.delete(0, 'end')
Пример #8
0
class ContentBox(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent

        _filelist_frame = ttk.LabelFrame(self.parent,
                                         text='File List',
                                         padding='5 5 5 5')
        _filelist_frame.pack(side='top', fill='both', expand=True)

        self._filelist_box = Listbox(_filelist_frame,
                                     listvariable=self.parent._filelist,
                                     height=10,
                                     width=25)
        self._filelist_box.pack(side='left', fill='both', expand=True, padx=5)
        self._filelist_box.bind('<Double-1>', self.parent.listbox_select)
        _scrollbar = ttk.Scrollbar(_filelist_frame,
                                   orient='vertical',
                                   command=self._filelist_box.yview)
        _scrollbar.pack(side='left', fill='y')
        self._filelist_box.configure(yscrollcommand=_scrollbar.set)
Пример #9
0
	def __addTextbox(self,dx=85,dy=24,x1=27,y=47,x2=624,sdy=430):
		scrolly=Scrollbar(self,activebackground="#171212",bg="#343838",orient=VERTICAL,troughcolor="#171212")
		listbox=Listbox(self,
						height=dy, 
						width=dx ,
						background="#343838",
						borderwidth=0,
						highlightcolor="#4d86a1",
						selectbackground="#4d86a1",
						activestyle=NONE,
						highlightbackground="#4a4a4a",
						yscrollcommand=scrolly.set)

		listbox.config(font=("", 10),fg="#FFFFFF")
		listbox.place(x=x1,y=y+21)
		scrolly.place(x=x2,y=y,height=sdy)	
		self.__list_listbox.append(listbox)
		self.__list_scrollbar.append(scrolly)
		
		listbox.configure(yscrollcommand=scrolly.set)
		scrolly.configure(command=listbox.yview)
Пример #10
0
class SelectDeviceFrame(CopilotInnerFrame):
    def __init__(self, master, config, state):
        super(SelectDeviceFrame, self).__init__(master, config)

        self._state = state

        if self._state.action == 'copy':
            self._frame_lbl['text'] = 'Copy To Device'
        elif self._state.action == 'delete':
            self._frame_lbl['text'] = 'Delete From Device'

        self._next_btn['command'] = self._next_cmd

        self._dev_list = Listbox(self._master, font=self._config.item_font)
        self._dev_list.grid(row=1, column=0, columnspan=3, sticky='nsew')
        self._dev_list.configure(yscrollcommand=self._sb.set)
        self._sb['command'] = self._dev_list.yview

        self._refresh_drives()

    def _next_cmd(self):
        if len(self._dev_list.curselection()) > 0:
            item_idx = int(self._dev_list.curselection()[0])
            self._state.to_device = self._parts[item_idx]
            if self._state.action == 'copy':
                self._new_state_window(DeviceToFrame, self._state)
            elif self._state.action == 'delete':
                self._new_state_window(CopyFileFrame, self._state)

    def _refresh_drives(self):
        self._parts = []
        for drive in usb_drives():
            for part in drive.partitions():
                drive_opt = DriveOption(drive, part)
                self._parts.append(drive_opt)
                self._dev_list.insert('end', drive_opt)
Пример #11
0
class Player(object):

    """Player class"""

    def __init__(self):

        """Initialisation of the Player object"""

        self.cfg = None
        self.db = None
        self.root = Tk()
        self.URL1L = StringVar(master=self.root)
        self.URL2L = StringVar(master=self.root)
        self.URL3L = StringVar(master=self.root)
        self.URL4L = StringVar(master=self.root)
        self.URL5L = StringVar(master=self.root)
        self.files = {}
        self.start()

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

    def start(self):

        """Start the Player"""

        print("*** Starting the Player ***")
        # Configuration
        self.cfg = Config()
        while not self.cfg.readConf() or not self.cfg.checkConf():
            self.displayConfig()
        if self.cfg.readConf() and self.cfg.checkConf():
            # Database
            self.db = Db(self.cfg)
            if self.db.openDb():
                self.display()
                return(True)
            else:
                error("Database not open")
                return(False)
        else:
            error("Cannot read configuration file")
            return(False)

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

    def stop(self):

        """Stop the Player"""

        msg = "Do you want to quit Raspyplayer ?"
        if messagebox.askokcancel("Raspyplayer MC", msg):
            print("*** Stopping the Player ***")
            self.db.closeDb()
            self.root.destroy()

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

    def scanDB(self):

        """Add movies in DB"""

        print("*** Adding movies in database")
        self.db.initDb()
        scanFiles(self.db, self.cfg, self.cfg.PATH)
        self.db.commitDb()
        return(True)

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

    def loadAllMovies(self):

        """Load movies from DB"""

        self.files = self.db.getAllMovies()
        return(True)

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

    def loadSrcMovies(self, src):

        """Load movies matching search pattern"""

        self.files = self.db.getSrcMovies(src)
        return(True)

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

    def play(self, url, file):

        """Play a movie"""

        print("Playing {}".format(file))
        if self.cfg.useOmx():
            if not url:
                sub = file[0:-3] + "srt"
                if isfile(sub):
                    cmd = self.cfg.OMXCMD2.format(self.cfg.OPT, self.cfg.OUT, sub, file)
                else:
                    cmd = self.cfg.OMXCMD1.format(self.cfg.OPT, self.cfg.OUT, file)
            else:
                cmd = self.cfg.OMXCMD1.format(self.cfg.OPT, self.cfg.OUT, file)
        else:
            cmd = self.cfg.MPLRCMD.format(file)
        if DEBUG:
            print(cmd)
        system(cmd)
        return(True)

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

    def directPlay(self):

        """Direct play a file"""
        file = askopenfilename(title="Select a movie")
        if file:
            ps = playScreen()
            self.play(False, file)
            ps.destroy()
        return(True)
        
    #---------------------------------------------------------------------#

    def displayHelp(self):

        """Display help"""

        messagebox.showinfo("Help...", getHelp())
        return(True)

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

    def displayConfig(self):

        """Display Config Window"""

        self.cfg.display(self)
        self.askToRefreshDataBase()
        return(True)

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

    def playSelection(self):

        """Play selected files"""

        sel = self.ui_files.curselection()
        ps = playScreen()
        for i in sel:
            f = self.ui_files.get(i)
            self.play(False, self.files[f])
        ps.destroy()
        return(True)

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

    def playUrl(self, url):

        """Play selected url"""

        ps = playScreen()
        self.play(True, url)
        ps.destroy()
        return(True)

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

    def display(self):

        """Display the player"""

        self.createGui()
        self.cfg.toggleUrl(self)
        self.askToRefreshDataBase()
        self.root.mainloop()

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

    def askToRefreshDataBase(self):

        """Ask to refresh database"""

        msg = "Do you want to refresh the movies database ?"
        if messagebox.askokcancel("Raspyplayer MC", msg):
            self.refreshDataBase()
        else:
            self.refreshFilesList()
        return(True)

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

    def refreshDataBase(self):

        """Refresh the movies database"""

        if isdir(self.cfg.PATH):
            self.scanDB()
            self.refreshFilesList()
            return(True)

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

    def refreshFilesList(self):

        """Refresh the list of files"""

        src = self.ui_srcentry.get()
        # Empty variables :
        self.files = {}
        if self.ui_files.size() > 0:
            self.ui_files.delete(0, END)
        # Get files in DB :
        if src == "" or src == "*":
            if DEBUG:
                print("Get ALL")
            self.loadAllMovies()
        else:
            if DEBUG:
                print("Get '{}'".format(src))
            self.loadSrcMovies(('%'+src+'%',))
        # Sort results :
        liste = list()
        for f, p in self.files.items():
            liste.append(f)
        liste.sort(key=str.lower)
        # Display result :
        for file in liste:
            self.ui_files.insert(END, file)
        return(True)

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

    def playUrl1(self):

        """Play URL 1"""

        self.playUrl(self.cfg.URL1)

    def playUrl2(self):

        """Play URL 2"""

        self.playUrl(self.cfg.URL2)

    def playUrl3(self):

        """Play URL 3"""

        self.playUrl(self.cfg.URL3)

    def playUrl4(self):

        """Play URL 4"""

        self.playUrl(self.cfg.URL4)

    def playUrl5(self):

        """Play URL 5"""

        self.playUrl(self.cfg.URL5)

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

    def evtPlay(self, evt):
        self.playSelection()

    def evtRefresh(self, evt):
        self.refreshFilesList()

    def evtScan(self, evt):
        self.askToRefreshDataBase()

    def evtCfg(self, cfg):
        self.displayConfig()

    def evtHelp(self, evt):
        self.displayHelp()

    def evtQuit(self, evt):
        self.stop()

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

    def createGui(self):

        """Create the GUI for Player"""

        print("*** Creating GUI ***")
        self.root.title("Raspyplayer Media Center v{}".format(VERSION))
        font = Font(self.root, size=26, family='Sans')
        #self.root.attributes('-fullscreen', True)
        self.root.attributes('-zoomed', '1')
        
        # Top Frame (search group)
        self.ui_topframe = Frame(self.root, borderwidth=2)
        self.ui_topframe.pack({"side": "top"})
        # Label search
        self.ui_srclabel = Label(self.ui_topframe, text="Search:",
            font=font)
        self.ui_srclabel.grid(row=1, column=0, padx=2, pady=2)
        # Entry search
        self.ui_srcentry = Entry(self.ui_topframe, font=font)
        self.ui_srcentry.grid(row=1, column=1, padx=2, pady=2)
        self.ui_srcentry.bind("<Return>", self.evtRefresh)
        # Button search
        self.ui_srcexec = Button(self.ui_topframe, text="Search",
            command=self.refreshFilesList, font=font)
        self.ui_srcexec.grid(row=1, column=2, padx=2, pady=2)

        # Frame (contain Middle and Url frames)
        self.ui_frame = Frame(self.root, borderwidth=2)
        self.ui_frame.pack(fill=BOTH, expand=1)

        # Middle Frame (files group)
        self.ui_midframe = Frame(self.ui_frame, borderwidth=2)
        self.ui_midframe.pack({"side": "left"}, fill=BOTH, expand=1)
        # Files liste and scrollbar
        self.ui_files = Listbox(self.ui_midframe,
            selectmode=EXTENDED, font=font)
        self.ui_files.pack(side=LEFT, fill=BOTH, expand=1)
        self.ui_files.bind("<Return>", self.evtPlay)
        self.ui_filesscroll = Scrollbar(self.ui_midframe,
            command=self.ui_files.yview)
        self.ui_files.configure(yscrollcommand=self.ui_filesscroll.set)
        self.ui_filesscroll.pack(side=RIGHT, fill=Y)

        # Url Frame (url group)
        self.ui_urlframe = Frame(self.ui_frame, borderwidth=2)
        self.ui_urlframe.pack({"side": "right"})
        # Button Url 1
        self.ui_buturl1 = Button(self.ui_urlframe, textvariable=self.URL1L,
            command=self.playUrl1, font=font)
        self.ui_buturl1.grid(row=1, column=0, padx=2, pady=2)
        # Button Url 2
        self.ui_buturl2 = Button(self.ui_urlframe, textvariable=self.URL2L,
            command=self.playUrl2, font=font)
        self.ui_buturl2.grid(row=2, column=0, padx=2, pady=2)
        # Button Url 3
        self.ui_buturl3 = Button(self.ui_urlframe, textvariable=self.URL3L,
            command=self.playUrl3, font=font)
        self.ui_buturl3.grid(row=3, column=0, padx=2, pady=2)
        # Button Url 4
        self.ui_buturl4 = Button(self.ui_urlframe, textvariable=self.URL4L,
            command=self.playUrl4, font=font)
        self.ui_buturl4.grid(row=4, column=0, padx=2, pady=2)
        # Button Url 5
        self.ui_buturl5 = Button(self.ui_urlframe, textvariable=self.URL5L,
            command=self.playUrl5, font=font)
        self.ui_buturl5.grid(row=5, column=0, padx=2, pady=2)

        # Bottom Frame (buttons group)
        self.ui_botframe = Frame(self.root, borderwidth=2)
        self.ui_botframe.pack({"side": "left"})
        # Button Play
        self.ui_butplay = Button(self.ui_botframe, text="Play",
            command=self.playSelection, font=font)
        self.ui_butplay.grid(row=1, column=0, padx=2, pady=2)
        # Button Refresh
        self.ui_butscan = Button(self.ui_botframe, text="Scan",
            command=self.askToRefreshDataBase, font=font)
        self.ui_butscan.grid(row=1, column=1, padx=2, pady=2)
        # Button Direct Play
        self.ui_butdplay = Button(self.ui_botframe, text="Direct Play",
            command=self.directPlay, font=font)
        self.ui_butdplay.grid(row=1, column=2, padx=2, pady=2)
        # Button Config
        self.ui_butconf = Button(self.ui_botframe, text="Config",
            command=lambda : self.cfg.display(self), font=font)
        self.ui_butconf.grid(row=1, column=3, padx=2, pady=2)
        # Button Help
        self.ui_buthelp = Button(self.ui_botframe, text="Help",
            command=self.displayHelp, font=font)
        self.ui_buthelp.grid(row=1, column=4, padx=2, pady=2)
        # Button Quit
        self.ui_butquit = Button(self.ui_botframe, text="Quit",
            command=self.stop, font=font)
        self.ui_butquit.grid(row=1, column=5, padx=2, pady=2)

        # General bindings
        self.root.bind("<F1>", self.evtHelp)
        self.root.bind("<F2>", self.evtCfg)
        self.root.bind("<F3>", self.evtRefresh)
        self.root.bind("<F5>", self.evtScan)
        self.root.bind("<F12>", self.evtQuit)
        return(True)
Пример #12
0
# Listbox window.
message = 'Recordings: Double click to play, right click to convert file to mp3'
lbox_frame = LabelFrame(root, fg='blue', text=message)
lbox_frame.grid(padx=10, pady=10)

lst_bx = Listbox(master=lbox_frame,
                 selectmode='single',
                 width=52,
                 height=10,
                 fg='black',
                 bg='lightgoldenrod')

# Scrollbars for above listbox.
scrl_bar = Scrollbar(lbox_frame, orient='vertical')
scrl_bar.pack(side=RIGHT, fill=Y)
lst_bx.configure(yscrollcommand=scrl_bar.set)
scrl_bar.configure(command=lst_bx.yview)

scrl_bar2 = Scrollbar(lbox_frame, orient='horizontal')
scrl_bar2.pack(side=BOTTOM, fill=X)
lst_bx.configure(xscrollcommand=scrl_bar2.set)
scrl_bar2.configure(command=lst_bx.xview)

# Mouse button bindings.
lst_bx.pack()
lst_bx.bind('<Double-1>', play_file)  # Dbl click to play file.
lst_bx.bind('<Button-3>', convert_2_mp3)  # Right click to convert to mp3.
get_list_of_recordings()

# Bottom window.
bot_frame = LabelFrame(root)
Пример #13
0
year_text = StringVar()
e3 = Entry(window, textvariable=year_text)
e3.grid(row=1, column=1)

isbn_text = StringVar()
e4 = Entry(window, textvariable=isbn_text)
e4.grid(row=1, column=3)

list1 = Listbox(window, height=6, width=35)
list1.grid(row=2, column=0, rowspan=6, columnspan=2)

sb1 = Scrollbar(window)
sb1.grid(row=2, column=3, rowspan=6)

list1.configure(yscrollcommand=sb1.set)
sb1.configure(command=list1.yview)

list1.bind('<<ListboxSelect>>', get_selected_row)

b1 = Button(window, text="View all", width=12, command=view_command)
b1.grid(row=2, column=3)

b2 = Button(window, text="Search entry", width=12, command=search_command)
b2.grid(row=3, column=3)

b3 = Button(window, text="Add entry", width=12, command=add_command)
b3.grid(row=4, column=3)

b4 = Button(window, text="Updated selected", width=12, command=update_command)
b4.grid(row=5, column=3)
Пример #14
0
class Combobox_Autocomplete(Entry, object):
    def __init__(self, master, list_of_items=None, autocomplete_function=None,
                 listbox_width=None, listbox_height=7, ignorecase_match=False,
                 startswith_match=True, vscrollbar=True, hscrollbar=True, **kwargs):
        if hasattr(self, "autocomplete_function"):
            if autocomplete_function is not None:
                raise ValueError(
                    "Combobox_Autocomplete subclass has 'autocomplete_function' implemented")
        else:
            if autocomplete_function is not None:
                self.autocomplete_function = autocomplete_function
            else:
                if list_of_items is None:
                    raise ValueError(
                        "If not given complete function, list_of_items can't be 'None'")
                elif ignorecase_match:
                    if startswith_match:
                        def matches_function(entry_data, item):
                            return item.startswith(entry_data)
                    else:
                        def matches_function(entry_data, item):
                            return item in entry_data
                    self.autocomplete_function = lambda entry_data: [
                        item for item in self.list_of_items if matches_function(entry_data, item)]
                else:
                    if startswith_match:
                        def matches_function(escaped_entry_data, item):
                            if re.match(escaped_entry_data, item, re.IGNORECASE):
                                return True
                            else:
                                return False
                    else:
                        def matches_function(escaped_entry_data, item):
                            if re.search(escaped_entry_data, item, re.IGNORECASE):
                                return True
                            else:
                                return False
                    def autocomplete_function2(entry_data):
                        escaped_entry_data = re.escape(entry_data)
                        return [item for item in self.list_of_items if matches_function(escaped_entry_data, item)]
                    self.autocomplete_function = autocomplete_function2
        self._listbox_height = int(listbox_height)
        self._listbox_width = listbox_width
        self.list_of_items = list_of_items
        self._use_vscrollbar = vscrollbar
        self._use_hscrollbar = hscrollbar
        kwargs.setdefault("background", "white")
        if "textvariable" in kwargs:
            self._entry_var = kwargs["textvariable"]
        else:
            self._entry_var = kwargs["textvariable"] = StringVar()
        Entry.__init__(self, master, **kwargs)
        self._trace_id = self._entry_var.trace('w', self._on_change_entry_var)
        self._listbox = None
        self.bind("<Tab>", self._on_tab)
        self.bind("<Up>", self._previous)
        self.bind("<Down>", self._next)
        self.bind('<Control-n>', self._next)
        self.bind('<Control-p>', self._previous)
        self.bind("<Return>", self._update_entry_from_listbox)
        self.bind("<Escape>", lambda event: self.unpost_listbox())
    def _on_tab(self, event):
        self.post_listbox()
        return "break"
    def _on_change_entry_var(self, name, index, mode):
        entry_data = self._entry_var.get()
        if entry_data == '':
            self.unpost_listbox()
            self.focus()
        else:
            values = self.autocomplete_function(entry_data)
            if values:
                if self._listbox is None:
                    self._build_listbox(values)
                else:
                    self._listbox.delete(0, END)
                    height = min(self._listbox_height, len(values))
                    self._listbox.configure(height=height)
                    for item in values:
                        self._listbox.insert(END, item)
            else:
                self.unpost_listbox()
                self.focus()
    def _build_listbox(self, values):
        listbox_frame = Frame()
        self._listbox = Listbox(listbox_frame, background="white",
                                selectmode=SINGLE, activestyle="none",
                                exportselection=False)
        self._listbox.grid(row=0, column=0, sticky=N+E+W+S)
        self._listbox.bind("<ButtonRelease-1>",
                           self._update_entry_from_listbox)
        self._listbox.bind("<Return>", self._update_entry_from_listbox)
        self._listbox.bind("<Escape>", lambda event: self.unpost_listbox())
        self._listbox.bind('<Control-n>', self._next)
        self._listbox.bind('<Control-p>', self._previous)
        if self._use_vscrollbar:
            vbar = Scrollbar(listbox_frame, orient=VERTICAL,
                             command=self._listbox.yview)
            vbar.grid(row=0, column=1, sticky=N+S)
            self._listbox.configure(
                yscrollcommand=lambda f, l: autoscroll(vbar, f, l))
        elif self._use_hscrollbar:
            hbar = Scrollbar(listbox_frame, orient=HORIZONTAL,
                             command=self._listbox.xview)
            hbar.grid(row=1, column=0, sticky=E+W)
            self._listbox.configure(
                xscrollcommand=lambda f, l: autoscroll(hbar, f, l))
            listbox_frame.grid_columnconfigure(0, weight=1)
            listbox_frame.grid_rowconfigure(0, weight=1)
            x = -self.cget("borderwidth") - self.cget("highlightthickness")
            y = self.winfo_height()-self.cget("borderwidth") - \
            self.cget("highlightthickness")
        elif self._listbox_width:
            width = self._listbox_width
        else:
            width = self.winfo_width()
        listbox_frame.place(in_=self, x=x, y=y, width=width)
        height = min(self._listbox_height, len(values))
        self._listbox.configure(height=height)
        for item in values:
            self._listbox.insert(END, item)
    def post_listbox(self):
        if self._listbox is not None:
            return
        entry_data = self._entry_var.get()
        if entry_data == '':
            return
        values = self.autocomplete_function(entry_data)
        if values:
            self._build_listbox(values)
    def unpost_listbox(self):
        if self._listbox is not None:
            self._listbox.master.destroy()
            self._listbox = None
    def get_value(self):
        return self._entry_var.get()
    def set_value(self, text, close_dialog=False):
        self._set_var(text)
        if close_dialog:
            self.unpost_listbox()
        self.icursor(END)
        self.xview_moveto(1.0)
    def _set_var(self, text):
        self._entry_var.trace_vdelete("w", self._trace_id)
        self._entry_var.set(text)
        self._trace_id = self._entry_var.trace('w', self._on_change_entry_var)
    def _update_entry_from_listbox(self, event):
        if self._listbox is not None:
            current_selection = self._listbox.curselection()
            if current_selection:
                text = self._listbox.get(current_selection)
                self._set_var(text)
            self._listbox.master.destroy()
            self._listbox = None
            self.focus()
            self.icursor(END)
            self.xview_moveto(1.0)
        return "break"
    def _previous(self, event):
        if self._listbox is not None:
            current_selection = self._listbox.curselection()
            if len(current_selection) == 0:
                self._listbox.selection_set(0)
                self._listbox.activate(0)
            else:
                index = int(current_selection[0])
                self._listbox.selection_clear(index)
                if index == 0:
                    index = END
                else:
                    index -= 1
                self._listbox.see(index)
                self._listbox.selection_set(first=index)
                self._listbox.activate(index)
        return "break"
    def _next(self, event):
        if self._listbox is not None:
            current_selection = self._listbox.curselection()
            if len(current_selection) == 0:
                self._listbox.selection_set(0)
                self._listbox.activate(0)
            else:
                index = int(current_selection[0])
                self._listbox.selection_clear(index)
                if index == self._listbox.size() - 1:
                    index = 0
                else:
                    index += 1
                self._listbox.see(index)
                self._listbox.selection_set(index)
                self._listbox.activate(index)
        return "break"
Пример #15
0
favs_btn = Button(btn_frame, bg='red3', text=' Favs ', command=view_favs)
favs_btn.grid(row=1, column=4, pady=4, padx=4)

# Create listbox.
main_lst_bx = Listbox(master=listbox_frame,
                      selectmode='single',
                      width=48,
                      height=8,
                      fg='black',
                      bg='olivedrab3')

# Add scrollbars to listbox.
scrl_bar_y = Scrollbar(listbox_frame, orient='vertical')
scrl_bar_y.pack(side=RIGHT, fill=Y)
main_lst_bx.configure(yscrollcommand=scrl_bar_y.set)
scrl_bar_y.configure(command=main_lst_bx.yview)

scrl_bar_x = Scrollbar(listbox_frame, orient='horizontal')
scrl_bar_x.pack(side=BOTTOM, fill=X)
main_lst_bx.configure(xscrollcommand=scrl_bar_x.set)
scrl_bar_x.configure(command=main_lst_bx.xview)
main_lst_bx.pack()

# Bind mouse right click to listbox.
main_lst_bx.bind('<Button-3>', popup)

# Add check buttons.
VAR1 = IntVar()
Checkbutton(listbox_frame, text='Hear insult', variable=VAR1).pack(side=LEFT)
VAR2 = IntVar()
class Gui():
    def __init__(self):
        '''Essa classe modela a interface gráfica
        da aplicação
        '''
        self.window = Tk()
        self.window.wm_title("Cadastro de Clientes")

        self.txtNacionalidade = StringVar()
        self.txtTipo_Documento = StringVar()
        self.txtCPF = StringVar()
        self.txtNumero_CNH = StringVar()
        self.txtSobrenome = StringVar()
        self.txtEmail = StringVar()
        self.txtGenero = StringVar()
        self.txtTelefone = StringVar()

        self.lblnacionalidade = Label(self.window, text="Nacionalidade")
        self.lbltipo_documento = Label(self.window, text="Tipo de documento")
        self.lblcpf = Label(self.window, text="CPF")

        self.lblnumero_cnh = Label(self.window, text="Numero da CNH")
        self.lblsobrenome = Label(self.window, text="Sobrenome")
        self.lblemail = Label(self.window, text="Email")
        self.lblgenero = Label(self.window, text="Gênero")
        self.lbltelefone = Label(self.window, text="Telefone")

        self.entNacionalidade = Entry(self.window,
                                      textvariable=self.txtNacionalidade)
        self.entTipo_Documento = Entry(self.window,
                                       textvariable=self.txtTipo_Documento)
        self.entGenero = Entry(self.window, textvariable=self.txtGenero)
        self.entTelefone = Entry(self.window, textvariable=self.txtTelefone)

        self.entNumero_CNH = Entry(self.window,
                                   textvariable=self.txtNumero_CNH)
        self.entSobrenome = Entry(self.window, textvariable=self.txtSobrenome)
        self.entEmail = Entry(self.window, textvariable=self.txtEmail)
        self.entCPF = Entry(self.window, textvariable=self.txtCPF)

        self.listClientes = Listbox(self.window, width=45)
        self.scrollClientes = Scrollbar(self.window)

        self.btnViewAll = Button(self.window, text="Ver todos")
        self.btnBuscar = Button(self.window, text="Buscar")
        self.btnInserir = Button(self.window, text="Continuar")
        self.btnUpdate = Button(self.window, text="Atualizar Selecionados")
        self.btnDel = Button(self.window, text="Deletar Selecionados")
        self.btnClose = Button(self.window, text="Fechar")

    def configure_layout(self):
        "Configurando os itens na janela em grid"

        #Associando os objetos a grid da janela...
        self.lblnacionalidade.grid(row=0, column=0)
        self.lbltipo_documento.grid(row=1, column=0)
        self.lblcpf.grid(row=2, column=0)
        self.lblgenero.grid(row=3, column=0)
        self.lbltelefone.grid(row=4, column=0)

        self.entNacionalidade.grid(row=0, column=1)
        self.entTipo_Documento.grid(row=1, column=1)
        self.entCPF.grid(row=2, column=1)
        self.entGenero.grid(row=3, column=1)
        self.entTelefone.grid(row=4, column=1)

        self.lblnumero_cnh.grid(row=5, column=0)
        self.lblsobrenome.grid(row=6, column=0)
        self.lblemail.grid(row=7, column=0)

        self.entNumero_CNH.grid(row=5, column=1)
        self.entSobrenome.grid(row=6, column=1)
        self.entEmail.grid(row=7, column=1)

        self.listClientes.grid(
            row=0, column=2, rowspan=10
        )  #rowspan para fazer com que o objeto ocupe mais de uma linha.
        self.scrollClientes.grid(row=0, column=3, rowspan=10)
        self.btnViewAll.grid(
            row=8, column=0, columnspan=2
        )  #columnspan para fazer com que o objeto ocupe mais de uma linha.
        self.btnBuscar.grid(row=9, column=0, columnspan=2)
        self.btnInserir.grid(row=10, column=0, columnspan=2)
        self.btnUpdate.grid(row=11, column=0, columnspan=2)
        self.btnDel.grid(row=12, column=0, columnspan=2)
        self.btnClose.grid(row=13, column=0, columnspan=2)

        #Associando a Scrollbar com a Listbox...
        self.listClientes.configure(yscrollcommand=self.scrollClientes.set)
        self.scrollClientes.configure(command=self.listClientes.yview)

    def configure_sizes(self):
        "definindo o tamanho dos elementos"
        x_pad = 5
        y_pad = 3
        '''
        * Precisamos aplicar o padding para quase todos os 
        elementos, definir a largura dos botões e mais alguns
        pontos estéticos. Isso poderia ser feito manualmente,
        repetindo o código para todos os elementos. Todavia, 
        não vamos fazer assim.
        * Faremos a mudança de estilo da seguinte forma: Uma
        iteração por todos os elementos da janela, realizando
        as alterações conforme passamos pelos elementos.
        '''
        for child in self.window.winfo_children():
            widget_class = child.__class__.__name__
            if widget_class == "Button":
                child.grid_configure(sticky='WE', padx=x_pad, pady=y_pad)
            elif widget_class == "Listbox":
                child.grid_configure(padx=0, pady=0, sticky='NS')
            elif widget_class == "Scrollbar":
                child.grid_configure(padx=0, pady=0, sticky='NS')
            else:
                child.grid_configure(padx=x_pad, pady=y_pad, sticky='N')
        '''
        * padx e pady: Padding para o eixo X e Y do elemento. 
        É referente ao espaço entre a borda deste elemento e 
        a borda dos outros elementos da janela;
        * sticky: Indica em qual ponto da janela (norte – N, 
        sul – S, leste – E ou oeste W) o objeto estará ancorado. 
        Se você combinar o ponto leste e oeste (EW), o elemento 
        ocupará todo o espaço horizontal da coluna em que está 
        localizado. O mesmo ocorre se colocarmos NS (norte-sul), 
        o elemento ocupará todo o espaço vertical.
        * Para o ListBox e o ScrollBar, vamos definir padding zero 
        para que eles fiquem colados, parecendo que são apenas um elemento.
        '''

    def run(self):
        self.configure_layout()
        self.configure_sizes()
        self.window.mainloop()
Пример #17
0
class FeasDisp(ttk.Frame):
    """Widget for displaying all of the feasible states in the conflict."""
    def __init__(self, master=None, conflict=None, *args):
        """Initialize the widget."""
        ttk.Frame.__init__(self, master, padding=5)
        self.columnconfigure(1, weight=1)
        self.rowconfigure(2, weight=1)

        self.conflict = conflict

        self.dispFormat = StringVar(value='pattern')
        self.dispList = StringVar()
        self.feasList = []

        self.fmts = {
            'Pattern': 'YN-',
            'List (YN)': 'YN',
            'List (ordered and [decimal])': 'ord_dec'
        }
        cBoxOpts = ('Pattern', 'List (YN)', 'List (ordered and [decimal])')
        self.feasText = ttk.Label(self, text='Feasible States')
        self.feasText.grid(row=0, column=0, columnspan=3)
        self.cBox = ttk.Combobox(self,
                                 textvariable=self.dispFormat,
                                 values=cBoxOpts,
                                 state='readonly')
        self.cBoxLb = ttk.Label(self, text='Format:')
        self.feasLBx = Listbox(self, listvariable=self.dispList)
        self.scrl = ttk.Scrollbar(self,
                                  orient=VERTICAL,
                                  command=self.feasLBx.yview)

        # ###########
        self.cBoxLb.grid(column=0, row=1, sticky=NSEW, pady=3)
        self.cBox.grid(column=1, row=1, columnspan=2, sticky=NSEW, pady=3)
        self.feasLBx.grid(column=0, row=2, columnspan=2, sticky=NSEW)
        self.scrl.grid(column=2, row=2, sticky=NSEW)

        self.cBox.bind('<<ComboboxSelected>>', self.fmtSel)
        self.feasLBx.configure(yscrollcommand=self.scrl.set)

        self.dispFormat.set('Pattern')
        self.fmtSel()

    def fmtSel(self, *args):
        """Action on selection of a new format."""
        self.refreshList()

    def setFeas(self, feasList):
        """Change the list of feasible states to be displayed."""
        self.feasList = feasList
        self.refreshList()

    def refreshList(self):
        """Update the list of feasible states displayed and the format."""
        fmt = self.fmts[self.dispFormat.get()]
        if fmt == "YN-":
            feas = self.conflict.feasibles.dash
        if fmt == "YN":
            feas = self.conflict.feasibles.yn
        if fmt == "ord_dec":
            feas = self.conflict.feasibles.ordDec
        self.dispList.set(tuple(feas))
Пример #18
0
# 2.1 listbox
list_box = Listbox(root,
                   height=16,
                   width=40,
                   font='helvetica 13',
                   bg='light blue')
list_box.grid(row=3, column=1, columnspan=14, sticky=W + E, padx=15, pady=40)
list_box.bind('<<ListboxSelect>>', get_selected_row)

# 2.2 Scroll bar:
scroll = Scrollbar(root)
scroll.grid(row=1, column=8, rowspan=14, sticky=W)

# 2.3 Attach scroll_bar to the list_box:
list_box.configure(yscrollcommand=scroll.set)
scroll.configure(command=list_box.yview)

# 3. Bottom buttons ( 15 row  -  list box 1-14 rows)

view_all_btn = Button(root,
                      text='View all records',
                      bg='black',
                      fg='white',
                      font='helvetica 10 bold',
                      command=view_records)
view_all_btn.grid(row=15, column=1)

clear_screen_btn = Button(root,
                          text='Clear Screen',
                          bg='dark red',
Пример #19
0
class InstanceEditor(Toplevel):

    def __init__(self):
        Toplevel.__init__(self)
        self.focus_set()
        self.grab_set()

        self.result = None
        self.module_data = None
        self.mod_applis = None
        self.title(ugettext("Instance editor"))
        self.grid_columnconfigure(0, weight=1)
        self.grid_rowconfigure(0, weight=1)

        self.ntbk = ttk.Notebook(self)
        self.ntbk.grid(row=0, column=0, columnspan=1, sticky=(N, S, E, W))

        self.frm_general = Frame(self.ntbk, width=350, height=150)
        self.frm_general.grid_columnconfigure(0, weight=0)
        self.frm_general.grid_columnconfigure(1, weight=1)
        self._general_tabs()
        self.ntbk.add(self.frm_general, text=ugettext('General'))

        self.frm_database = Frame(self.ntbk, width=350, height=150)
        self.frm_database.grid_columnconfigure(0, weight=0)
        self.frm_database.grid_columnconfigure(1, weight=1)
        self._database_tabs()
        self.ntbk.add(self.frm_database, text=ugettext('Database'))

        btnframe = Frame(self, bd=1)
        btnframe.grid(row=1, column=0, columnspan=1)
        Button(btnframe, text=ugettext("OK"), width=10, command=self.apply).grid(
            row=0, column=0, sticky=(N, S, E))
        Button(btnframe, text=ugettext("Cancel"), width=10, command=self.destroy).grid(
            row=0, column=1, sticky=(N, S, W))

    def _database_tabs(self):
        Label(self.frm_database, text=ugettext("Type")).grid(
            row=0, column=0, sticky=(N, W), padx=5, pady=3)
        self.typedb = ttk.Combobox(
            self.frm_database, textvariable=StringVar(), state=READLONY)
        self.typedb.bind("<<ComboboxSelected>>", self.typedb_selection)
        self.typedb.grid(row=0, column=1, sticky=(N, S, E, W), padx=5, pady=3)
        Label(self.frm_database, text=ugettext("Name")).grid(
            row=1, column=0, sticky=(N, W), padx=5, pady=3)
        self.namedb = Entry(self.frm_database)
        self.namedb.grid(row=1, column=1, sticky=(N, S, E, W), padx=5, pady=3)
        Label(self.frm_database, text=ugettext("User")).grid(
            row=2, column=0, sticky=(N, W), padx=5, pady=3)
        self.userdb = Entry(self.frm_database)
        self.userdb.grid(row=2, column=1, sticky=(N, S, E, W), padx=5, pady=3)
        Label(self.frm_database, text=ugettext("Password")).grid(
            row=3, column=0, sticky=(N, W), padx=5, pady=3)
        self.pwddb = Entry(self.frm_database)
        self.pwddb.grid(row=3, column=1, sticky=(N, S, E, W), padx=5, pady=3)

    def _general_tabs(self):
        Label(self.frm_general, text=ugettext("Name")).grid(
            row=0, column=0, sticky=(N, W), padx=5, pady=3)
        self.name = Entry(self.frm_general)
        self.name.grid(row=0, column=1, sticky=(N, S, E, W), padx=5, pady=3)
        Label(self.frm_general, text=ugettext("Appli")).grid(
            row=1, column=0, sticky=(N, W), padx=5, pady=3)
        self.applis = ttk.Combobox(
            self.frm_general, textvariable=StringVar(), state=READLONY)
        self.applis.bind("<<ComboboxSelected>>", self.appli_selection)
        self.applis.grid(row=1, column=1, sticky=(N, S, E, W), padx=5, pady=3)
        Label(self.frm_general, text=ugettext("Modules")).grid(
            row=2, column=0, sticky=(N, W), padx=5, pady=3)
        self.modules = Listbox(self.frm_general, selectmode=EXTENDED)
        self.modules.configure(exportselection=False)
        self.modules.grid(row=2, column=1, sticky=(N, S, E, W), padx=5, pady=3)
        Label(self.frm_general, text=ugettext("Language")).grid(
            row=3, column=0, sticky=(N, W), padx=5, pady=3)
        self.language = ttk.Combobox(
            self.frm_general, textvariable=StringVar(), state=READLONY)
        self.language.grid(
            row=3, column=1, sticky=(N, S, E, W), padx=5, pady=3)
        Label(self.frm_general, text=ugettext("CORE-connectmode")
              ).grid(row=4, column=0, sticky=(N, W), padx=5, pady=3)
        self.mode = ttk.Combobox(
            self.frm_general, textvariable=StringVar(), state=READLONY)
        self.mode.bind("<<ComboboxSelected>>", self.mode_selection)
        self.mode.grid(row=4, column=1, sticky=(N, S, E, W), padx=5, pady=3)
        Label(self.frm_general, text=ugettext("Password")).grid(
            row=5, column=0, sticky=(N, W), padx=5, pady=3)
        self.password = Entry(self.frm_general, show="*")
        self.password.grid(
            row=5, column=1, sticky=(N, S, E, W), padx=5, pady=3)

    def typedb_selection(self, event):

        visible = list(self.typedb[VALUES]).index(self.typedb.get()) != 0
        for child_cmp in self.frm_database.winfo_children()[2:]:
            if visible:
                child_cmp.config(state=NORMAL)
            else:
                child_cmp.config(state=DISABLED)

    def appli_selection(self, event):
        if self.applis.get() != '':
            appli_id = list(self.applis[VALUES]).index(self.applis.get())
            luct_glo = LucteriosGlobal()
            current_inst_names = luct_glo.listing()
            appli_root_name = self.mod_applis[appli_id][0].split('.')[-1]
            default_name_idx = 1
            while appli_root_name + six.text_type(default_name_idx) in current_inst_names:
                default_name_idx += 1
            self.name.delete(0, END)
            self.name.insert(
                0, appli_root_name + six.text_type(default_name_idx))
            mod_depended = self.mod_applis[appli_id][2]
            self.modules.select_clear(0, self.modules.size())
            for mod_idx in range(len(self.module_data)):
                current_mod = self.module_data[mod_idx]
                if current_mod in mod_depended:
                    self.modules.selection_set(mod_idx)

    def mode_selection(self, event):
        visible = list(self.mode[VALUES]).index(self.mode.get()) != 2
        for child_cmp in self.frm_general.winfo_children()[-2:]:
            if visible:
                child_cmp.config(state=NORMAL)
            else:
                child_cmp.config(state=DISABLED)

    def apply(self):
        from lucterios.framework.settings import DEFAULT_LANGUAGES, get_locale_lang
        if self.name.get() == '':
            showerror(ugettext("Instance editor"), ugettext("Name empty!"))
            return
        if self.applis.get() == '':
            showerror(ugettext("Instance editor"), ugettext("No application!"))
            return
        db_param = "%s:name=%s,user=%s,password=%s" % (
            self.typedb.get(), self.namedb.get(), self.userdb.get(), self.pwddb.get())
        security = "MODE=%s" % list(
            self.mode[VALUES]).index(self.mode.get())
        if self.password.get() != '':
            security += ",PASSWORD=%s" % self.password.get()
        module_list = [
            self.module_data[int(item)] for item in self.modules.curselection()]
        appli_id = list(self.applis[VALUES]).index(self.applis.get())
        current_lang = get_locale_lang()
        for lang in DEFAULT_LANGUAGES:
            if lang[1] == self.language.get():
                current_lang = lang[0]
        self.result = (self.name.get(), self.mod_applis[appli_id][
                       0], ",".join(module_list), security, db_param, current_lang)
        self.destroy()

    def _load_current_data(self, instance_name):
        from lucterios.framework.settings import DEFAULT_LANGUAGES, get_locale_lang
        lct_inst = LucteriosInstance(instance_name)
        lct_inst.read()
        self.name.delete(0, END)
        self.name.insert(0, lct_inst.name)
        self.name.config(state=DISABLED)
        applis_id = 0
        for appli_iter in range(len(self.mod_applis)):
            if self.mod_applis[appli_iter][0] == lct_inst.appli_name:
                applis_id = appli_iter
                break
        self.applis.current(applis_id)
        if lct_inst.extra['']['mode'] is not None:
            self.mode.current(lct_inst.extra['']['mode'][0])
        else:
            self.mode.current(2)
        self.mode_selection(None)
        typedb_index = 0
        for typedb_idx in range(len(self.typedb[VALUES])):
            if self.typedb[VALUES][typedb_idx].lower() == lct_inst.database[0].lower():
                typedb_index = typedb_idx
                break
        self.typedb.current(typedb_index)
        self.typedb.config(state=DISABLED)
        self.typedb_selection(None)
        self.namedb.delete(0, END)
        if 'name' in lct_inst.database[1].keys():
            self.namedb.insert(0, lct_inst.database[1]['name'])
        self.userdb.delete(0, END)
        if 'user' in lct_inst.database[1].keys():
            self.userdb.insert(0, lct_inst.database[1]['user'])
        self.pwddb.delete(0, END)
        if 'password' in lct_inst.database[1].keys():
            self.pwddb.insert(0, lct_inst.database[1]['password'])
        self.modules.select_clear(0, self.modules.size())
        for mod_idx in range(len(self.module_data)):
            current_mod = self.module_data[mod_idx]
            if current_mod in lct_inst.modules:
                self.modules.select_set(mod_idx)
        current_lang = get_locale_lang()
        if 'LANGUAGE_CODE' in lct_inst.extra.keys():
            current_lang = lct_inst.extra['LANGUAGE_CODE']
        for lang in DEFAULT_LANGUAGES:
            if lang[0] == current_lang:
                self.language.current(self.language[VALUES].index(lang[1]))

    def execute(self, instance_name=None):
        from lucterios.framework.settings import DEFAULT_LANGUAGES, get_locale_lang
        self.mode[VALUES] = [ugettext(
            "CORE-connectmode.0"), ugettext("CORE-connectmode.1"), ugettext("CORE-connectmode.2")]
        self.language[VALUES] = [lang[1] for lang in DEFAULT_LANGUAGES]
        self.typedb[VALUES] = ["SQLite", "MySQL", "PostgreSQL"]
        lct_glob = LucteriosGlobal()
        _, self.mod_applis, mod_modules = lct_glob.installed()
        self.mod_applis.sort(key=lambda item: get_module_title(item[0]))
        self.modules.delete(0, END)
        self.module_data = []
        module_list = []
        for mod_module_item in mod_modules:
            module_list.append(
                (get_module_title(mod_module_item[0]), mod_module_item[0]))
        module_list.sort(key=lambda module: module[0])
        for module_title, module_name in module_list:
            self.modules.insert(END, module_title)
            self.module_data.append(module_name)
        appli_list = []
        for mod_appli_item in self.mod_applis:
            appli_list.append(get_module_title(mod_appli_item[0]))
        self.applis[VALUES] = appli_list
        if instance_name is not None:
            self._load_current_data(instance_name)
        else:
            self.typedb.current(0)
            self.mode.current(2)
            if len(appli_list) > 0:
                self.applis.current(0)
            self.appli_selection(None)
            self.mode_selection(None)
            self.typedb_selection(None)
            for lang in DEFAULT_LANGUAGES:
                if lang[0] == get_locale_lang():
                    self.language.current(self.language[VALUES].index(lang[1]))
        center(self)
Пример #20
0
class Main(Frame):
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        self.controller = controller
        self.db_set = False

        self.configure(relief=GROOVE)
        self.configure(borderwidth="2")

        # Manual link adding
        self.manual_btn = Button(self)
        self.manual_btn.place(relx=0.07, rely=0.81, height=45, width=130)
        self.manual_btn.configure(activebackground="#d9d9d9")
        self.manual_btn.configure(highlightbackground="#d9d9d9")
        self.manual_btn.configure(pady="0")
        self.manual_btn.configure(text="Add manually")
        self.manual_btn.configure(width=130)

        self.file_btn = Button(self)
        self.file_btn.place(relx=0.67, rely=0.81, height=45, width=150)
        self.file_btn.configure(activebackground="#d9d9d9")
        self.file_btn.configure(highlightbackground="#d9d9d9")
        self.file_btn.configure(pady="0")
        self.file_btn.configure(text="Add from file")

        self.label = Label(self)
        self.label.place(relx=0.08, rely=0.0, height=61, width=484)
        self.label.configure(text="Create new playlists and add content to them")
        self.label.configure(width=485)

        self.listbox = Listbox(self)
        self.listbox.place(relx=0.38, rely=0.22, relheight=0.31, relwidth=0.17)
        self.listbox.configure(background="white")
        self.listbox.configure(disabledforeground="#a3a3a3")
        self.listbox.configure(foreground="#000000")
        self.listbox.configure(selectmode=SINGLE)
        self.listbox.configure(width=105)
        for name, value in config.configparser.items('Playlists'):
            if os.path.isdir(value):
                self.listbox.insert('end', name)
            else:
                config.remove_value('Playlists', name)
        self.listbox.bind('<<ListboxSelect>>', self.onselect)

        self.label_name = Label(self)
        self.label_name.place(relx=0.7, rely=0.22, height=31, width=84)
        self.label_name.configure(foreground="#000000")
        self.label_name.configure(text="Name")
        self.label_name.configure(width=85)

        self.entry = Entry(self)
        self.entry.place(relx=0.63, rely=0.31, relheight=0.08, relwidth=0.29)
        self.entry.configure(background="white")
        self.entry.configure(foreground="#000000")
        self.entry.configure(insertbackground="black")
        self.entry.configure(takefocus="0")
        self.entry.configure(width=175)

        self.change_name = Button(self)
        self.change_name.place(relx=0.7, rely=0.42, height=34, width=97)
        self.change_name.configure(activebackground="#d9d9d9")
        self.change_name.configure(highlightbackground="#d9d9d9")
        self.change_name.configure(highlightcolor="black")
        self.change_name.configure(pady="0")
        self.change_name.configure(text="Rename")
        self.change_name.configure(width=100)

        self.new_playlist = Button(self, command=self.new_database)
        self.new_playlist.place(relx=0.08, rely=0.28, height=54, width=107)
        self.new_playlist.configure(activebackground="#d9d9d9")
        self.new_playlist.configure(highlightbackground="#d9d9d9")
        self.new_playlist.configure(highlightcolor="black")
        self.new_playlist.configure(pady="0")
        self.new_playlist.configure(text="Create new playlist")
        self.new_playlist.configure(width=105)

        self.db_name = Entry(self)
        self.db_name.place(relx=0.07, rely=0.44, relheight=0.08, relwidth=0.22)
        self.db_name.configure(fg='grey')
        self.db_name.configure(width=135)
        self.db_name.insert(0, "Input database name here")
        self.db_name.bind('<Button-1>', lambda event: greytext(self.db_name))

    def onselect(self, event):
        w = event.widget
        index = int(w.curselection()[0])
        value = w.get(index)
        set_database(config.configparser.get('Playlists', value))
        if not database.check_integrity():
            messagebox.showwarning('Integrity check failed', 'You might be missing some entries in your list')
        if not self.db_set:
            self.manual_btn.configure(command=lambda: self.controller.show_frame('AddManually'))
            self.file_btn.configure(command=lambda: self.controller.show_frame('ReadFromFile'))
            self.db_set = True

    def new_database(self):
        name = self.db_name.get()
        names = config.configparser.options('Playlists')
        print(name, names)
        if name.strip() == '' or self.db_name.cget('fg') == 'grey':
            messagebox.showerror('Invalid name', "Please input a valid name for the database")
            return
        if name in names:
            messagebox.showerror('Name already in use', "Please select another name")
            return
        path = '../playlists/%s/' % name
        if set_database(path, create=True) is False:
            return
        config.set_value('Playlists', name, path)
        self.listbox.insert('end', name)
Пример #21
0
class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("")
        # self.style = Style()
        # self.style.theme_use("clam")
        # self.pack(fill=BOTH, expand = 1)

        self.quitbutton = Button(self, text="Quit", command=lambda: self.quit())

        self.quitbutton.grid(row=3, column=1, pady=4)

        self.labelErrorPointer = Label(self, text="◀")

        self.labellist = []
        self.entrylist = []
        self.verifylist = []
        self.misclist = []

        self.optionCreate = "Create"
        self.optionUpcoming = "Upcoming"
        self.optionPast = "Past"

        self.prevmode = self.optionCreate
        self.curmode = self.optionCreate
        self.optionvar = tkinter.StringVar(self)
        self.optionvar.trace("w", self.permaloop)
        self.optionvar.set(self.optionCreate)
        self.option = OptionMenu(self, self.optionvar, self.optionCreate, self.optionUpcoming, self.optionPast)

        self.optionpostmodevar = tkinter.StringVar(self)
        self.optionpostmodevar.trace("w", self.permaloop)
        self.optionpostmodevar.set("url")
        self.optionpostmode = OptionMenu(self, self.optionpostmodevar, "url", "text")

        self.labelText = Label(self, text="Selftext:")
        self.entryText = Text(self)
        self.labelURL = Label(self, text="URL:")
        self.entryURL = Entry(self)
        self.entryURL.configure(width=60)

        self.sql = sqlite3.connect("sql.db")
        print("Loaded SQL Database")
        self.cur = self.sql.cursor()

        self.cur.execute(
            "CREATE TABLE IF NOT EXISTS upcoming(ID TEXT, SUBREDDIT TEXT, TIME INT, TITLE TEXT, URL TEXT, BODY TEXT)"
        )
        self.cur.execute(
            "CREATE TABLE IF NOT EXISTS past(ID TEXT, SUBREDDIT TEXT, TIME INT, TITLE TEXT, URL TEXT, BODY TEXT, POSTLINK TEXT)"
        )
        self.cur.execute("CREATE TABLE IF NOT EXISTS internal(NAME TEXT, ID INT)")
        print("Loaded Completed table")
        self.cur.execute("SELECT * FROM internal")
        f = self.cur.fetchone()
        if not f:
            print("Database is new. Adding ID counter")
            self.cur.execute("INSERT INTO internal VALUES(?, ?)", ["counter", 1])
            self.idcounter = 1
        else:
            self.idcounter = f[1]
            print("Current ID counter: " + str(self.idcounter))

        self.sql.commit()

        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()

        w = 853
        h = 480
        x = (sw - w) / 2
        y = (sh - h) / 2

        self.parent.geometry("%dx%d+%d+%d" % (w, h, x, y - 50))

        self.login()

    def login(self):

        try:
            self.quitbutton.grid_forget()
            self.quitbutton.grid(row=9000, column=0, columnspan=20)

            self.option.grid(row=1, column=0, columnspan=8, pady=8)

            self.updategui(fullclean=True)
        except praw.errors.InvalidUserPass:
            pass
            print("Invalid username or password")
            self.entryPassword.delete(0, 200)
            self.labelErrorPointer.grid(row=1, column=2)

    def permaloop(self, *args):
        self.curmode = self.optionvar.get()
        print("Was: " + self.prevmode + " | Now: " + self.curmode)
        if self.curmode != self.prevmode:
            self.prevmode = self.curmode
            self.updategui(fullclean=True)
        else:
            self.updategui(False)

    def getTime(self, bool):
        timeNow = datetime.datetime.now(datetime.timezone.utc)
        timeUnix = timeNow.timestamp()
        if bool == False:
            return timeNow
        else:
            return timeUnix

    def addentrytobase(self, subreddit, title, url="", body="", mode="", ptime=""):
        curtime = round(self.getTime(True))
        try:
            t = (
                self.entryMo.get()
                + " "
                + self.entryDa.get()
                + " "
                + self.entryYr.get()
                + " "
                + self.entryHH.get()
                + ":"
                + self.entryMM.get()
            )
            plandate = datetime.datetime.strptime(t, "%B %d %Y %H:%M")
            plandate = plandate.timestamp()
        except ValueError:
            print("Invalid Day")
            return False

        if mode == "url":
            url = self.entryURL.get()
            body = ""
            if "http://" not in url and "https://" not in url:
                print("Please enter a proper URL")
                return False
        if mode == "text":
            body = self.entryText.get("1.0", "end")
            url = ""

        if plandate < curtime:
            print("Please enter a time in the future")
            return False

        if not all(char in string.ascii_letters + string.digits + "_-" for char in subreddit):
            print("Subreddit contains invalid characters")
            return False

        if len(subreddit) == 0:
            print("You must enter a subreddit")
            return False

        if len(title) == 0:
            print("You must enter a title")
            return False
        if len(title) > 300:
            print("Title is too long. " + str(len(title)) + "/300 char max")
            return False
        if len(body) > 15000:
            print("Body is too long. " + str(len(body)) + "/15,000 char max")

        print("Timestamp:", plandate)
        self.cur.execute(
            "INSERT INTO upcoming VALUES(?, ?, ?, ?, ?, ?)",
            [self.idcounter, subreddit, int(plandate), title, url, body],
        )
        self.idcounter += 1
        self.cur.execute("UPDATE internal SET ID=? WHERE NAME=?", [self.idcounter, "counter"])
        self.sql.commit()
        print("Post Saved!")
        self.entryText.delete("1.0", "end")
        self.entryURL.delete(0, "end")
        self.entryTitle.delete(0, "end")
        # self.updategui(halfclean=True)

    def dropentryfrombase(self, ID):
        try:
            ID = int(ID)
        except ValueError:
            print("You must enter a number")
            return
        print("Dropping Item " + str(ID) + " from Upcoming")
        self.cur.execute("DELETE FROM upcoming WHERE ID=?", [ID])
        self.sql.commit()
        self.updategui(fullclean=True)

    def printbasetofile(self, db):
        filea = open(db + ".txt", "w")
        if db == "past":
            self.cur.execute("SELECT * FROM past")
        if db == "upcoming":
            self.cur.execute("SELECT * FROM upcoming")
        f = self.cur.fetchall()
        print("Printed " + db + " unimpeded to file")
        for item in f:
            i = list(item)
            d = datetime.datetime.fromtimestamp(i[2])
            i[2] = datetime.datetime.strftime(d, "%b %d %H:%M")
            i.remove("")

            print(str(i)[1:-1], file=filea)
        filea.close()

    def updategui(self, halfclean=False, fullclean=False):

        if self.curmode == self.optionCreate:
            try:
                print(self.optionpostmodevar.get())

                if self.optionpostmodevar.get() == "url":
                    self.entryText.delete("1.0", "end")
                    self.labelText.grid_forget()
                    self.entryText.grid_forget()

                    self.labelURL.grid(row=8, column=0, columnspan=30)
                    self.entryURL.grid(row=9, column=0, columnspan=12, pady=10)

                if self.optionpostmodevar.get() == "text":
                    self.entryURL.delete(0, "end")
                    self.labelURL.grid_forget()
                    self.entryURL.grid_forget()

                    self.labelText.grid(row=8, column=0, columnspan=30)
                    self.entryText.configure(width=40, height=8)
                    self.entryText.grid(row=9, column=0, columnspan=12)
            except AttributeError:
                pass

        if fullclean == True:
            print("Cleaning GUI")
            for item in self.labellist:
                item.grid_forget()
            for item in self.entrylist:
                item.grid_forget()
            for item in self.verifylist:
                item.grid_forget()
            for item in self.misclist:
                item.grid_forget()
            self.labellist = []
            self.entrylist = []
            self.verifylist = []
            self.misclist = []

            if self.curmode == self.optionCreate:
                self.newrowindex = 6
                self.labelSubreddit = Label(self, text="Subreddit:    /r/")
                self.labelTitle = Label(self, text="Post title:  ")
                self.entrySubreddit = Entry(self)
                self.entryTitle = Entry(self)

                self.labelHH = Label(self, text="Schedule time (Local timezone):")
                nowlist = datetime.datetime.strftime(datetime.datetime.now(), "%B %d %Y %H %M").split()

                self.entryMo = Spinbox(
                    self,
                    width=9,
                    values=(
                        "January",
                        "February",
                        "March",
                        "April",
                        "May",
                        "June",
                        "July",
                        "August",
                        "September",
                        "October",
                        "November",
                        "December",
                    ),
                )
                self.entryMo.delete(0, "end")
                self.entryMo.insert(0, nowlist[0])

                self.entryDa = Spinbox(self, width=2, from_=1, to=31)
                self.entryDa.delete(0, "end")
                self.entryDa.insert(0, nowlist[1])

                self.entryYr = Spinbox(self, width=4, from_=2014, to=2500)
                self.entryYr.delete(0, "end")
                self.entryYr.insert(0, nowlist[2])

                self.entryHH = Spinbox(self, from_=0, to=23, width=2)
                self.entryHH.delete(0, "end")
                self.entryHH.insert(0, nowlist[3])

                self.entryMM = Spinbox(self, from_=0, to=59, width=2)
                self.entryMM.delete(0, "end")
                self.entryMM.insert(0, nowlist[4])

                self.buttonAddentry = Button(
                    self,
                    text="Save",
                    command=lambda: self.addentrytobase(
                        self.entrySubreddit.get(), self.entryTitle.get(), mode=self.optionpostmodevar.get()
                    ),
                )

                self.misclist.append(self.labelSubreddit)
                self.misclist.append(self.entrySubreddit)
                self.misclist.append(self.labelHH)
                self.misclist.append(self.entryHH)
                self.misclist.append(self.entryMM)
                self.misclist.append(self.entryMo)
                self.misclist.append(self.entryDa)
                self.misclist.append(self.entryYr)
                self.misclist.append(self.labelTitle)
                self.misclist.append(self.entryTitle)
                self.misclist.append(self.buttonAddentry)
                self.misclist.append(self.optionpostmode)
                self.misclist.append(self.labelText)
                self.misclist.append(self.entryText)
                self.misclist.append(self.labelURL)
                self.misclist.append(self.entryURL)

                self.labelSubreddit.grid(row=2, column=0, sticky="e")
                self.labelTitle.grid(row=3, column=0, sticky="e")
                self.entrySubreddit.grid(row=2, column=1, columnspan=3, sticky="w")
                self.entryTitle.grid(row=3, column=1, columnspan=3, sticky="w")
                self.entryMo.grid(row=4, column=1, sticky="e")
                self.entryDa.grid(row=4, column=2)
                self.entryYr.grid(row=4, column=3)
                self.labelHH.grid(row=4, column=0, sticky="se", pady=5)
                self.entryHH.grid(row=5, column=1, sticky="e")
                self.entryMM.grid(row=5, column=2, sticky="w")
                self.optionpostmode.grid(row=6, column=0, columnspan=20, pady=10)
                self.buttonAddentry.grid(row=200, column=0, columnspan=20)

            if self.curmode == self.optionUpcoming:
                self.cur.execute("SELECT * FROM upcoming")
                dobutton = True

            if self.curmode == self.optionPast:
                self.cur.execute("SELECT * FROM past")
                dobutton = False

            if self.curmode == self.optionPast or self.curmode == self.optionUpcoming:

                self.listboxId = Listbox(self)
                self.listboxId.configure(width=118, height=20, font=("Courier 8"))
                self.misclist.append(self.listboxId)

                self.listboxScroller = Scrollbar(self, orient="horizontal", command=self.listboxId.xview)
                self.listboxScroller.grid(row=4, column=0, columnspan=900)
                self.listboxId.grid(row=3, column=0, columnspan=10)

                self.listboxId.configure(xscrollcommand=self.listboxScroller.set)
                self.misclist.append(self.listboxScroller)

                self.buttonPrinter = Button(self, text="Print to .txt file")
                if self.curmode == self.optionPast:
                    self.buttonPrinter.configure(command=lambda: self.printbasetofile("past"))
                if self.curmode == self.optionUpcoming:
                    self.buttonPrinter.configure(command=lambda: self.printbasetofile("upcoming"))

                self.buttonPrinter.grid(row=6, column=0, columnspan=90)
                self.misclist.append(self.buttonPrinter)

                if dobutton == True:
                    self.entryDelete = Entry(self)
                    self.buttonDelete = Button(
                        self, text="Delete Item: ", command=lambda: self.dropentryfrombase(self.entryDelete.get())
                    )
                    self.buttonDelete.grid(row=5, column=0, sticky="e")
                    self.entryDelete.grid(row=5, column=1, sticky="w")
                    self.misclist.append(self.entryDelete)
                    self.misclist.append(self.buttonDelete)

                fetched = self.cur.fetchall()
                for item in fetched:
                    d = datetime.datetime.fromtimestamp(item[2])
                    info = datetime.datetime.strftime(d, "%b %d %H:%M")

                    if item[4] == "":
                        infx = item[5]
                    if item[5] == "":
                        infx = item[4]
                    if self.curmode == self.optionPast:
                        infy = "." + item[6]
                    else:
                        infy = ""

                    self.listboxId.insert(
                        "end",
                        item[0]
                        + "." * (6 - len(item[0]))
                        + item[1][:10]
                        + "." * (12 - len(item[1][:10]))
                        + info
                        + "." * (15 - len(info[:14]))
                        + item[3][:18]
                        + "." * (20 - len(item[3][:14]))
                        + infx[:45]
                        + "." * (47 - len(infx[:45]))
                        + infy,
                    )

    def morerows(self, label, columnm, columnn, limit, *args):
        self.redditlabel = Label(self, text=label)
        self.redditlabel.grid(row=self.newrowindex, column=columnm, sticky="e")
        self.labellist.append(self.redditlabel)

        self.redditentry = Entry(self)
        self.redditentry.grid(row=self.newrowindex, column=columnn, columnspan=9)
        self.entrylist.append(self.redditentry)

        self.newrowindex += 1
        if self.newrowindex >= limit:
            self.morerowbutton.grid_forget()
        print(self.newrowindex)
Пример #22
0
class Window:
    def __init__(self, window):
        self.window = window
        # Setting title name
        self.window.wm_title("Restaurants Yelp")

        # Setting location for "Restaurant Name"
        self.l1 = Label(window, text='Restaurant Name')
        self.l1.grid(row=0, column=0, sticky='w')

        # Setting location for "Address"
        self.l2 = Label(window, text='Address')
        self.l2.grid(row=1, column=0, sticky='w')

        # Setting location for "Average Price (Less than)"
        self.l3 = Label(window, text='Average Price (Less than)')
        self.l3.grid(row=0, column=2, sticky='w')

        # Setting location for "Distance (Less than)
        self.l4 = Label(window, text='Distance (Less than)')
        self.l4.grid(row=1, column=2, sticky='w')

        # Setting location for "Natinality"
        self.l5 = Label(window, text='Nationality')
        self.l5.grid(row=2, column=0, sticky='w')

        # Configure the name restaurant toolbar, and its location
        self.name_text = StringVar()
        self.e1 = Entry(window, textvariable=self.name_text)
        self.e1.bind("<Button-1>", self.clear_box)
        self.e1.grid(row=0, column=1)

        # Configure the address toolbar, and its location
        self.address_text = StringVar()
        self.e2 = Entry(window, textvariable=self.address_text)
        self.e2.bind("<Button-1>", self.clear_box)
        self.e2.grid(row=1, column=1)

        # Configure the average price toolbar, and its location
        self.avgp_text = StringVar()
        self.e3 = Entry(window, textvariable=self.avgp_text)
        self.e3.bind("<Button-1>", self.clear_box)
        self.e3.grid(row=0, column=3)

        # Configure the Distance toolbar, and its location
        self.distance_text = StringVar()
        self.e4 = Entry(window, textvariable=self.distance_text)
        self.e4.bind("<Button-1>", self.clear_box)
        self.e4.grid(row=1, column=3)

        # Configure the nationality toolbar, and its location
        self.nationality_text = StringVar()
        self.e5 = Entry(window, textvariable=self.nationality_text)
        self.e5.bind("<Button-1>", self.clear_box)
        self.e5.grid(row=2, column=1)

        self.l0 = Label(window, text='')
        self.l0.grid(row=3, column=0)

        # Configure the "Search By Input" button
        # It calls search_command function
        self.b0 = Button(window,
                         text='Search By Input',
                         width=17,
                         command=self.search_command)
        self.b0.grid(row=2, column=3)

        # Configure console for output
        self.list1 = Listbox(window)
        self.list1.grid(row=4, column=1, rowspan=5, columnspan=3, sticky='ew')

        # Configure Scrollbar for output
        self.sb1 = Scrollbar(window)
        self.sb1.grid(row=4, column=4, rowspan=5, sticky='ns')
        self.list1.configure(yscrollcommand=self.sb1.set)
        self.sb1.configure(command=self.list1.yview)

        # Configure "View All" button, and its location
        # It calls function view_command
        self.b1 = Button(window,
                         text='View All',
                         width=12,
                         command=self.view_command)
        self.b1.grid(row=4, column=0)

        # Setting Label "Search:"
        self.l6 = Label(window, text='Search: ')
        self.l6.grid(row=5, column=0)

        # Configure button "By Location", and its location
        # It calls function search_by_location_command
        self.b2 = Button(window,
                         text='By Location',
                         width=12,
                         command=self.search_by_location_command)
        self.b2.grid(row=6, column=0)

        # Configure button "By High Price", and its location
        # It calls function search_by_high_price_command
        self.b3 = Button(window,
                         text='By High Price',
                         width=12,
                         command=self.search_by_high_price_command)
        self.b3.grid(row=7, column=0)

        # Configure button "By Low Price", and its location
        # It calls function search_by_low_price_command
        self.b4 = Button(window,
                         text='By Low Price',
                         width=12,
                         command=self.search_by_low_price_command)
        self.b4.grid(row=8, column=0)

        # Configure button "Close", and its location
        # It calls function close
        self.b5 = Button(window, text='Close', width=12, command=self.close)
        self.b5.grid(row=9, column=0, columnspan=4)

    """
    Method view_command: Fill all information the list of retaurant into output console
    """

    def view_command(self):
        self.list1.delete(0, END)
        for restaurant in restaurants.view():
            self.list1.insert(END, restaurant)

    def search_by_high_price_command(self):
        self.list1.delete(0, END)
        for restaurant in restaurants.search_by_price(lowest=False):
            self.list1.insert(END, f"Restaurant name: {restaurant.name}")
            self.list1.insert(END, f"Address: {restaurant.address}")
            self.list1.insert(END,
                              f"Average Price: {restaurant.average_price}$")
            self.list1.insert(END, f"Distance: {restaurant.distance} miles")
            self.list1.insert(END, f"Nationality: {restaurant.nationality}")
            self.list1.insert(END, "")

    def search_by_low_price_command(self):
        self.list1.delete(0, END)
        for restaurant in restaurants.search_by_price():
            self.list1.insert(END, f"Restaurant name: {restaurant.name}")
            self.list1.insert(END, f"Address: {restaurant.address}")
            self.list1.insert(END,
                              f"Average Price: {restaurant.average_price}$")
            self.list1.insert(END, f"Distance: {restaurant.distance} miles")
            self.list1.insert(END, f"Nationality: {restaurant.nationality}")
            self.list1.insert(END, "")

    def search_by_location_command(self):
        self.list1.delete(0, END)
        for restaurant in restaurants.search_by_location():
            self.list1.insert(END, restaurant)

    def search_command(self):
        self.list1.delete(0, END)
        try:
            searched = restaurants.search(self.name_text.get(),
                                          self.address_text.get(),
                                          self.avgp_text.get(),
                                          self.distance_text.get(),
                                          self.nationality_text.get())
            if searched:
                for restaurant in searched:
                    self.list1.insert(END, restaurant)
            else:
                messagebox.showwarning(
                    title="No Restaurant",
                    message="Cannot find any restaurant, try again")
        except ValueError:
            messagebox.showerror(
                title="Wrong Input",
                message="Average Price and Distance must be a decimal number")

    def clear_box(self, event):
        event.widget.delete(0, END)

    def close(self):
        self.window.destroy()
Пример #23
0
    buttons.append(b)

stdCanvas = Canvas(frame1, bg='green', width=340, height=900)
stdCanvas.place(x=10, y=210)

stdScrollbar = Scrollbar(stdCanvas, orient="vertical")
stdScrollbar.pack(side="right", fill="y")
stdListBox = Listbox(stdCanvas,
                     width=40,
                     height=48,
                     background="black",
                     foreground="white",
                     font=('Consolas', 10, 'bold'))
stdListBox.pack()
stdListBox.insert(tk.END, "LIST OF STANDARDIZED WORDS..")
stdListBox.configure(yscrollcommand=stdScrollbar.set)
stdScrollbar.config(command=stdListBox.yview)

#FRAME 2

loadFileBtn = HoverButton(frame2, text="Load", command=load_file)
loadFileBtn.place(x=710, y=955)
loadFileInput = Entry(frame2, width=42, justify="left", font=('Consolas', 12))
loadFileInput.place(x=775, y=959)
loadFileInput.configure(background="black",
                        foreground="white",
                        font=('Consolas', 12))

word_label = Label(frame2, text="WORD")
word_label.place(x=5, y=5)
word_label.configure(background="black",
class DMselector(ttk.Frame):
    """Listbox for DM Creation, Selection, and Sorting."""
    def __init__(self, master, conflict):
        """Initialize DM selection/creation Widget."""
        ttk.Frame.__init__(self, master)
        self.conflict = conflict
        self.dms = conflict.decisionMakers
        # variables
        self.listVariable = StringVar(
            value=tuple(['Double Click to Add Item']))
        self.selIdx = None
        self.selectedDM = None

        # widgets
        self.label = ttk.Label(self, text="Decision Makers")
        self.dmListDisp = Listbox(self, listvariable=self.listVariable)
        self.scrollY = ttk.Scrollbar(self,
                                     orient=VERTICAL,
                                     command=self.dmListDisp.yview)
        self.upBtn = ttk.Button(self, width=10, text='Up', command=self.upCmd)
        self.downBtn = ttk.Button(self,
                                  width=10,
                                  text='Down',
                                  command=self.downCmd)
        self.delBtn = ttk.Button(self,
                                 width=10,
                                 text='Delete',
                                 command=self.delCmd)

        # configuration
        self.dmListDisp.configure(yscrollcommand=self.scrollY.set)
        self.columnconfigure(0, weight=1)
        self.rowconfigure(1, weight=1)

        self.label.grid(column=0, row=0, columnspan=5, sticky=NSEW)
        self.dmListDisp.grid(column=0, row=1, columnspan=5, sticky=NSEW)
        self.scrollY.grid(column=5, row=1, sticky=NSEW)
        self.upBtn.grid(column=2, row=2, sticky=NSEW)
        self.downBtn.grid(column=3, row=2, sticky=NSEW)
        self.delBtn.grid(column=4, row=2, sticky=NSEW)

        self.dmListDisp.bind('<<ListboxSelect>>', self.selChgCmd)
        self.dmListDisp.bind('<Double-1>', self.editCmd)
        self.dmListDisp.bind('<Delete>', self.delCmd)
        self.dmListDisp.bind('<Return>', self.editCmd)

    def refresh(self, event=None):
        """Refresh widget contents."""
        self.updateList()
        for idx in range(len(self.dms)):
            self.dmListDisp.itemconfigure(idx, foreground='black')
        self.dmListDisp.itemconfigure(len(self.dms), foreground='#A0A0A0')

    def updateList(self, event=None):
        """Update the value in the displayed listVariable."""
        self.listVariable.set(
            tuple(self.dms.names() + ['Double Click to Add Item']))

    def moveEntry(self, idx, idx2):
        """Move an item from idx to idx2."""
        self.dms.insert(idx2, self.dms.pop(idx))
        self.updateList()
        self.dmListDisp.selection_clear(idx)
        self.dmListDisp.selection_set(idx2)
        self.selChgCmd()
        self.event_generate("<<dmOptChg>>")

    def upCmd(self, event=None):
        """Move the selected element up one space in the list."""
        idx = self.selIdx
        # check that there is an entry selected, and it isn't the first entry.
        if idx not in [-1, 0, len(self.dms)]:
            self.moveEntry(idx, idx - 1)

    def downCmd(self, event=None):
        """Move the selected element down one space in the list."""
        idx = self.selIdx
        # check that there is an entry selected, and it isn't the last entry
        if idx not in [-1, len(self.dms) - 1, len(self.dms)]:
            self.moveEntry(idx, idx + 1)

    def delCmd(self, *args):
        """Delete the selected element from the list."""
        idx = self.selIdx
        if idx != len(self.dms):  # check that a valid entry is selected
            del self.dms[idx]
            self.refresh()
            self.event_generate("<<dmOptChg>>")

    def selChgCmd(self, *args):
        """Called when the selection changes."""
        self.selIdx = int(self.dmListDisp.curselection()[0])
        if self.selIdx != len(self.conflict.decisionMakers):
            self.selectedDM = self.conflict.decisionMakers[self.selIdx]
        else:
            self.selectedDM = None
        self.event_generate('<<DMselected>>')

    def editCmd(self, *args):
        """Called when a list entry is selected for editing."""
        self.event_generate('<<EditDM>>')

    def reselect(self, event=None):
        """Return selection focus to a dm after an action is completed."""
        if self.selIdx is not None:
            self.dmListDisp.selection_set(self.selIdx)
            self.dmListDisp.event_generate('<<ListboxSelect>>')
             ('pressed', 'arrowdown-p'), ('active', 'arrowdown-a'), {
                 "border": 1
             })
        }

        # end of theme extract - don't forget to add comma at end when inserting
    })

style.theme_use('yummy')  # 'default'

fr1 = Frame(fr, height=250, width=250)
fr1.grid(column=0, row=11, sticky='nsew')

widg = Scrollbar(fr1, orient="vertical")
widg1 = Scrollbar(fr1, orient="horizontal")
mylist = Listbox(fr1)
for line in range(100):
    mylist.insert('end', "A really long line. " + str(line) + " Line number ")

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

widg.grid(column=1, row=0, sticky='ns')
widg.configure(command=mylist.yview)

widg1.grid(column=0, row=1, sticky='ew')
widg1.configure(command=mylist.xview)
mylist.configure(yscrollcommand=widg.set, xscrollcommand=widg1.set)
run_state(fr, widg, widg1)

root.mainloop()
Пример #26
0
class CadastroCliente:
    '''Classe interface cadastrar cliente'''
    def __init__(self, master=''):
        self.master = master
        self.cliente = Cliente()
        self.dao = ClienteDAO()
        '''
        self.window = Tk()
        self.window.geometry('1500x850+0+0')
        self.window.title('Cadastro de cliente')
        self.window.resizable(0, 0)  # impede de maximizar
        self.window['bg'] = '#c9c9ff'
        '''
        self.heading = Label(self.master,
                             text="Cadastro de Clientes",
                             bg='#c9c9ff',
                             fg='white',
                             font=('Verdana 20 bold'))
        self.heading.place(x=650, y=0)

        # nome =========================================================================
        self.nome = Label(self.master,
                          text="Nome:",
                          bg='#c9c9ff',
                          fg='white',
                          font=('Verdana 15 bold'))
        self.nome.place(x=30, y=70)
        self.nome_entry = Entry(self.master,
                                width=15,
                                font=('Verdana 15 bold'))
        self.nome_entry.place(x=175, y=70)

        # rg =========================================================================
        self.rg = Label(self.master,
                        text="rg:",
                        bg='#c9c9ff',
                        fg='white',
                        font=('Verdana 15 bold'))
        self.rg.place(x=30, y=120)
        self.rg_entry = Entry(self.master, width=15, font=('Verdana 15 bold'))
        self.rg_entry.place(x=175, y=120)

        # cpf =========================================================================
        self.cpf = Label(self.master,
                         text="cpf:",
                         bg='#c9c9ff',
                         fg='white',
                         font=('Verdana 15 bold'))
        self.cpf.place(x=30, y=170)
        self.cpf_entry = Entry(self.master, width=15, font=('Verdana 15 bold'))
        self.cpf_entry.place(x=175, y=170)

        # email =========================================================================
        self.email = Label(self.master,
                           text="email:",
                           bg='#c9c9ff',
                           fg='white',
                           font=('Verdana 15 bold'))
        self.email.place(x=30, y=220)
        self.email_entry = Entry(self.master,
                                 width=15,
                                 font=('Verdana 15 bold'))
        self.email_entry.place(x=175, y=220)
        # self.email_entry.insert(END, datetime.date.today())

        # telefone =========================================================================
        self.telefone = Label(self.master,
                              text="Telefone:",
                              bg='#c9c9ff',
                              fg='white',
                              font=('Verdana 15 bold'))
        self.telefone.place(x=30, y=270)
        self.telefone_entry = Entry(self.master,
                                    width=15,
                                    font=('Verdana 15 bold'))
        self.telefone_entry.place(x=175, y=270)
        self.telefone_entry.insert(END, "litros")

        # nascimento =========================================================================
        self.nascimento = Label(self.master,
                                text="Nascimento:",
                                bg='#c9c9ff',
                                fg='white',
                                font=('Verdana 15 bold'))
        self.nascimento.place(x=30, y=320)
        self.nascimento_entry = Entry(self.master,
                                      width=15,
                                      font=('Verdana 15 bold'))
        self.nascimento_entry.place(x=175, y=320)

        # consumo cidade =========================================================================
        self.estado_civil = Label(self.master,
                                  text="Estado civil:",
                                  bg='#c9c9ff',
                                  fg='white',
                                  font=('Verdana 15 bold'))
        self.estado_civil.place(x=30, y=370)
        self.estado_civil_entry = Entry(self.master,
                                        width=15,
                                        font=('Verdana 15 bold'))
        self.estado_civil_entry.place(x=175, y=370)

        self.estado_civil_entry.insert(END, "l/km")

        self.genero = Label(self.master,
                            text="Gênero:",
                            bg='#c9c9ff',
                            fg='white',
                            font=('Verdana 15 bold'))
        self.genero.place(x=30, y=420)
        self.genero_entry = Entry(self.master,
                                  width=15,
                                  font=('Verdana 15 bold'))
        self.genero_entry.place(x=175, y=420)
        self.genero_entry.insert(END, "l/km")

        # direito ==============================
        self.cep = Label(self.master,
                         text="CEP:",
                         bg='#c9c9ff',
                         fg='white',
                         font=('Verdana 15 bold'))
        self.cep.place(x=550, y=70)
        self.cep_entry = Entry(self.master, width=15, font=('Verdana 15 bold'))
        self.cep_entry.place(x=730, y=70)

        self.estado = Label(self.master,
                            text="Estado:",
                            bg='#c9c9ff',
                            fg='white',
                            font=('Verdana 15 bold'))
        self.estado.place(x=550, y=120)
        self.estado_entry = Entry(self.master,
                                  width=15,
                                  font=('Verdana 15 bold'))
        self.estado_entry.place(x=730, y=120)

        self.logradouro = Label(self.master,
                                text="Logradouro:",
                                bg='#c9c9ff',
                                fg='white',
                                font=('Verdana 15 bold'))
        self.logradouro.place(x=550, y=170)
        self.logradouro_entry = Entry(self.master,
                                      width=15,
                                      font=('Verdana 15 bold'))
        self.logradouro_entry.place(x=730, y=170)

        self.bairro = Label(self.master,
                            text="Bairro:",
                            bg='#c9c9ff',
                            fg='white',
                            font=('Verdana 15 bold'))
        self.bairro.place(x=550, y=220)
        self.bairro_entry = Entry(self.master,
                                  width=15,
                                  font=('Verdana 15 bold'))
        self.bairro_entry.place(x=730, y=220)

        self.numero_logradouro = Label(self.master,
                                       text="Número:",
                                       bg='#c9c9ff',
                                       fg='white',
                                       font=('Verdana 15 bold'))
        self.numero_logradouro.place(x=550, y=270)
        self.numero_logradouro_entry = Entry(self.master,
                                             width=15,
                                             font=('Verdana 15 bold'))
        self.numero_logradouro_entry.place(x=730, y=270)

        self.cidade = Label(self.master,
                            text="Cidade:",
                            bg='#c9c9ff',
                            fg='white',
                            font=('Verdana 15 bold'))
        self.cidade.place(x=550, y=320)
        self.cidade_entry = Entry(self.master,
                                  width=15,
                                  font=('Verdana 15 bold'))
        self.cidade_entry.place(x=730, y=320)

        self.complemento = Label(self.master,
                                 text="Complemento:",
                                 bg='#c9c9ff',
                                 fg='white',
                                 font=('Verdana 15 bold'))
        self.complemento.place(x=550, y=370)
        self.complemento_entry = Entry(self.master,
                                       width=15,
                                       font=('Verdana 15 bold'))
        self.complemento_entry.place(x=730, y=370)

        # TERCEIRO FRAME =============================================
        self.numero_cnh = Label(self.master,
                                text="Numero CNH:",
                                bg='#c9c9ff',
                                fg='white',
                                font=('Verdana 15 bold'))
        self.numero_cnh.place(x=1050, y=70)
        self.numero_cnh_entry = Entry(self.master,
                                      width=15,
                                      font=('Verdana 15 bold'))
        self.numero_cnh_entry.place(x=1250, y=70)

        self.numero_registro_cnh = Label(self.master,
                                         text="RG CNH:",
                                         bg='#c9c9ff',
                                         fg='white',
                                         font=('Verdana 15 bold'))
        self.numero_registro_cnh.place(x=1050, y=120)
        self.numero_registro_cnh_entry = Entry(self.master,
                                               width=15,
                                               font=('Verdana 15 bold'))
        self.numero_registro_cnh_entry.place(x=1250, y=120)

        self.data_validade_cnh = Label(self.master,
                                       text="Validade CNH:",
                                       bg='#c9c9ff',
                                       fg='white',
                                       font=('Verdana 15 bold'))
        self.data_validade_cnh.place(x=1050, y=170)
        self.data_validade_cnh_entry = Entry(self.master,
                                             width=15,
                                             font=('Verdana 15 bold'))
        self.data_validade_cnh_entry.place(x=1250, y=170)

        self.uf_cnh = Label(self.master,
                            text="UF CNH:",
                            bg='#c9c9ff',
                            fg='white',
                            font=('Verdana 15 bold'))
        self.uf_cnh.place(x=1050, y=220)
        self.uf_cnh_entry = Entry(self.master,
                                  width=15,
                                  font=('Verdana 15 bold'))
        self.uf_cnh_entry.place(x=1250, y=220)

        self.contato_emergencial = Label(self.master,
                                         text="Contato 2:",
                                         bg='#c9c9ff',
                                         fg='white',
                                         font=('Verdana 15 bold'))
        self.contato_emergencial.place(x=1050, y=270)
        self.contato_emergencial_entry = Entry(self.master,
                                               width=15,
                                               font=('Verdana 15 bold'))
        self.contato_emergencial_entry.place(x=1250, y=270)

        self.nome_contato_emergencial = Label(self.master,
                                              text="Nome contato:",
                                              bg='#c9c9ff',
                                              fg='white',
                                              font=('Verdana 15 bold'))
        self.nome_contato_emergencial.place(x=1050, y=320)
        self.nome_contato_emergencial_entry = Entry(self.master,
                                                    width=15,
                                                    font=('Verdana 15 bold'))
        self.nome_contato_emergencial_entry.place(x=1250, y=320)

        # BOTAO LIMPAR  =========================================================================
        self.botao_limpar = Button(self.master,
                                   text="Limpar",
                                   width=22,
                                   height=2,
                                   bg='#ffdfba',
                                   fg='black',
                                   font=('Verdana 15 bold'),
                                   command=self.view_command)
        self.botao_limpar.place(x=1170, y=550)

        self.botao_cadastrar = Button(self.master,
                                      text="Cadastrar",
                                      width=22,
                                      height=2,
                                      bg='#baffc9',
                                      fg='black',
                                      font=('Verdana 15 bold'),
                                      command=self.get_items)
        self.botao_cadastrar.place(x=1170, y=650)
        '''
        self.botao_sair = Button(self.master, text="Sair", width=22, height=2, bg='#ffb3ba', fg='black', font=(
        'Verdana 15 bold'), command=self.close)
        self.botao_sair.place(x=1170, y=740)
        '''
        self.lista_clientes = Listbox(self.master,
                                      width=80,
                                      height=10,
                                      font=('Verdana 15 bold'))
        self.lista_clientes.place(x=30, y=550)

        #Associando a Scrollbar com a Listbox...
        self.scrollbar_cliente = Scrollbar(self.master)
        self.lista_clientes.configure(
            yscrollcommand=self.scrollbar_cliente.set)
        self.scrollbar_cliente.configure(command=self.lista_clientes.yview)
        self.scrollbar_cliente.place(x=1155,
                                     y=550,
                                     relheight=0.31,
                                     anchor='ne')

        self.pesquisar_cliente = Label(self.master,
                                       text="Lista de clientes Cadastrados:",
                                       bg='#c9c9ff',
                                       font=('Verdana 15 bold'))
        self.pesquisar_cliente.place(x=30, y=500)
        self.update_list()

    def update_list(self):
        try:
            self.lista_clientes.delete(0, END)
            for item in self.clienteDAO.view():
                self.lista_clientes.insert(END, item)
        except Exception:
            print('Erro na lista clientes.')

    def get_items(self):
        self.cliente.nome = self.nome_entry.get()
        self.cliente.rg = self.rg_entry.get()
        self.cliente.cpf = self.cpf_entry.get()
        self.cliente.email = self.email_entry.get()
        self.cliente.telefone = self.telefone_entry.get()
        self.cliente.nascimento = self.nascimento_entry.get()
        self.cliente.estado_civil = self.estado_civil_entry.get()
        self.cliente.genero = self.genero_entry.get()
        self.cliente.cep = self.cep_entry.get()
        self.cliente.logradouro = self.logradouro_entry.get()
        self.cliente.bairro = self.bairro_entry.get()
        self.cliente.numero_logradouro = self.numero_logradouro_entry.get()
        self.cliente.cidade = self.cidade_entry.get()
        self.cliente.estado = self.estado_entry.get()
        self.cliente.complemento = self.complemento_entry.get()
        self.cliente.numero_cnh = self.numero_cnh_entry.get()
        self.cliente.numero_registro_cnh = self.numero_registro_cnh_entry.get()
        self.cliente.data_validade_cnh = self.data_validade_cnh_entry.get()
        self.cliente.uf_cnh = self.uf_cnh_entry.get()
        self.cliente.contato_emergencial = self.contato_emergencial_entry.get()
        self.cliente.nome_contato_emergencial = self.nome_contato_emergencial_entry.get(
        )

        if (self.cliente.nome == '' or self.cliente.rg == ''
                or self.cliente.cpf == '' or self.cliente.email == ''
                or self.cliente.telefone == '' or self.cliente.nascimento == ''
                or self.cliente.estado_civil == '' or self.cliente.genero == ''
                or self.cliente.cep == '' or self.cliente.logradouro == ''
                or self.cliente.bairro == ''
                or self.cliente.numero_logradouro == ''
                or self.cliente.cidade == '' or self.cliente.estado == ''
                or self.cliente.complemento == ''
                or self.cliente.numero_cnh == ''
                or self.cliente.numero_registro_cnh == ''
                or self.cliente.data_validade_cnh == ''
                or self.cliente.uf_cnh == ''
                or self.cliente.contato_emergencial == ''
                or self.cliente.nome_contato_emergencial == ''):
            tkinter.messagebox.showinfo("Aviso:", "Preencha todos os campos!")
        else:
            try:
                self.cliente.telefone = int(self.cliente.telefone)
            except ValueError:
                tkinter.messagebox.showinfo(
                    'Aviso!',
                    'O campo telefone deve ser preenchido com número!')
            try:
                self.cliente.contato_emergencial = int(
                    self.cliente.contato_emergencial)
            except ValueError:
                tkinter.messagebox.showinfo(
                    'Aviso!',
                    'O campo contato emergencial deve ser preenchidos com número!'
                )
            try:
                self.cliente.cep = int(self.cliente.cep)
            except ValueError:
                tkinter.messagebox.showinfo(
                    'Aviso!', 'O campo cep deve ser preenchido com números!')
            try:
                self.cliente.numero_cnh = int(self.cliente.numero_cnh)
            except ValueError:
                tkinter.messagebox.showinfo(
                    'Aviso!',
                    'O campo numero cnh deve ser preenchido com números!')
            try:
                self.cliente.numero_registro_cnh = int(
                    self.cliente.numero_registro_cnh)
            except ValueError:
                tkinter.messagebox.showinfo(
                    'Aviso!',
                    'O campo rg cnh deve ser preenchido com números!')
            try:
                self.cliente.uf_cnh = int(self.cliente.uf_cnh)
            except ValueError:
                tkinter.messagebox.showinfo(
                    'Aviso!',
                    'O campo uf cnh deve ser preenchido com números!!')
            else:
                try:
                    self.dao.insert(self.cliente)
                except Exception as e:
                    print("erro ao inserir no banco de dados")
                else:
                    tkinter.messagebox.showinfo(
                        'Aviso!', 'Cadastro Realizado com Sucesso!')
                    self.clear_all()
                    self.update_list()

    def clear_all(self):
        self.nome_entry.delete(0, END)
        self.rg_entry.delete(0, END)
        self.cpf_entry.delete(0, END)
        self.email_entry.delete(0, END)
        self.telefone_entry.delete(0, END)
        self.nascimento_entry.delete(0, END)
        self.estado_civil_entry.delete(0, END)
        self.genero_entry.delete(0, END)
        self.cep_entry.delete(0, END)
        self.logradouro_entry.delete(0, END)
        self.bairro.delete(0, END)
        self.numero_logradouro.delete(0, END)
        self.cidade.delete(0, END)
        self.estado.delete(0, END)
        self.complemento.delete(0, END)
        self.numero_cnh.delete(0, END)
        self.numero_registro_cnh.delete(0, END)
        self.data_validade_cnh.delete(0, END)
        self.uf_cnh.delete(0, END)
        self.contato_emergencial.delete(0, END)
        self.nome_contato_emergencial.delete(0, END)

    def view_command(self):
        "método para visualização dos resultados"
        try:
            rows = self.clienteDAO.view()
            self.window.lista_clientes.delete(0, END)
            for r in rows:
                self.window.lista_clientes.insert(END, r)
        except Exception as e:
            print(e)

    def search_command(self):
        "método para buscar registros"
        self.gui.lista_clientes.delete(0, END)
        self.__fill_current_client()
        try:
            rows = self.dao.search(self.currentClient)
            for r in rows:
                self.gui.lista_clientes.insert(END, r)
        except Exception as e:
            print(e)

    def close(self):
        self.dao.close()
        self.tela_inicial.destroy()
        self.executar.abrir()
Пример #27
0
class Tela_bibliotecario(Tela):
    '''Classe que modela a interface grafica da tela do bibliotecario depois de feito o login'''
    def __init__(self):
        super().__init__()
        self.janela.wm_title("bibliotecario - DELIBRARY")

        self.txt_nome_cliente = StringVar()
        self.txt_sobrenome_cliente = StringVar()
        self.txt_cpf_cliente = StringVar()
        self.txt_login_cliente = StringVar()
        self.txt_senha_cliente = StringVar()
        self.txt_email_cliente = StringVar()

        self.txt_id_livro = StringVar()
        self.txt_nome_livro = StringVar()
        self.txt_genero_livro = StringVar()
        self.txt_autor_livro = StringVar()
        self.txt_area_livro = StringVar()
        self.txt_editora_livro = StringVar()
        self.txt_edicao_livro = StringVar()

        self.lbl_janela_cliente = Label(self.janela,
                                        text="ATUALIZAR CADASTRO DE CLIENTE")
        self.lbl_nome_cliente = Label(self.janela, text="Nome")
        self.lbl_sobrenome_cliente = Label(self.janela, text="Sobrenome")
        self.lbl_cpf_cliente = Label(self.janela, text="CPF")
        self.lbl_login_cliente = Label(self.janela, text="Criar login")
        self.lbl_senha_cliente = Label(self.janela, text="Criar senha")
        self.lbl_email_cliente = Label(self.janela, text="Email ")

        self.ent_nome_cliente = Entry(self.janela,
                                      textvariable=self.txt_nome_cliente)
        self.ent_sobrenome_cliente = Entry(
            self.janela, textvariable=self.txt_sobrenome_cliente)
        self.ent_cpf_clienteo = Entry(self.janela,
                                      textvariable=self.txt_cpf_cliente)
        self.ent_login_cliente = Entry(self.janela,
                                       textvariable=self.txt_login_cliente)
        self.ent_senha_cliente = Entry(self.janela,
                                       textvariable=self.txt_senha_cliente)
        self.ent_email_cliente = Entry(self.janela,
                                       textvariable=self.txt_email_cliente)

        self.btn_criar_acesso_cliente = Button(self.janela,
                                               width=15,
                                               text="Criar Acesso")
        self.btn_retirar_acesso_cliente = Button(self.janela,
                                                 width=15,
                                                 text="Retirar Acesso")
        self.btn_ver_todos_cliente = Button(self.janela,
                                            width=15,
                                            text="Ver Todos")
        self.btn_atualizar = Button(self.janela, width=15, text="Atualizar")
        self.btn_realizar_emprestimo_devolucao = Button(
            self.janela, width=15, text="Emprestimo/Devolucao")
        self.btn_fechar = Button(self.janela, width=15, text="Sair")

        self.list = Listbox(self.janela, width=72)
        self.scroll = Scrollbar(self.janela)

        self.lbl_janela_livro = Label(self.janela, text="CADASTRO DE LIVRO")
        self.lbl_id_livro = Label(self.janela, text="ID")
        self.lbl_nome_livro = Label(self.janela, text="Nome")
        self.lbl_genero_livro = Label(self.janela, text="Genero")
        self.lbl_autor_livro = Label(self.janela, text="Autor")
        self.lbl_area_livro = Label(self.janela, text="Area")
        self.lbl_editora_livro = Label(self.janela, text="Editora")
        self.lbl_edicao_livro = Label(self.janela, text="Edicao")

        self.ent_id_livro = Entry(self.janela, textvariable=self.txt_id_livro)
        self.ent_nome_livro = Entry(self.janela,
                                    textvariable=self.txt_nome_livro)
        self.ent_genero_livro = Entry(self.janela,
                                      textvariable=self.txt_genero_livro)
        self.ent_autor_livro = Entry(self.janela,
                                     textvariable=self.txt_autor_livro)
        self.ent_area_livro = Entry(self.janela,
                                    textvariable=self.txt_area_livro)
        self.ent_editora_livro = Entry(self.janela,
                                       textvariable=self.txt_editora_livro)
        self.ent_edicao_livro = Entry(self.janela,
                                      textvariable=self.txt_edicao_livro)

        self.btn_cadastro_livro = Button(self.janela,
                                         width=15,
                                         text="Cadastrar Livro")
        self.btn_retirar_livro = Button(self.janela,
                                        width=15,
                                        text="Retirar Livro")

    def config_layout(self):
        '''Metodo para configurar os widgets da janela'''
        self.lbl_janela_cliente.grid(row=0, column=0)
        self.lbl_nome_cliente.grid(row=1, column=0)
        self.lbl_sobrenome_cliente.grid(row=2, column=0)
        self.lbl_cpf_cliente.grid(row=3, column=0)
        self.lbl_email_cliente.grid(row=4, column=0)
        self.lbl_login_cliente.grid(row=5, column=0)
        self.lbl_senha_cliente.grid(row=6, column=0)
        self.ent_nome_cliente.grid(row=1, column=1)
        self.ent_sobrenome_cliente.grid(row=2, column=1)
        self.ent_cpf_clienteo.grid(row=3, column=1)
        self.ent_login_cliente.grid(row=4, column=1)
        self.ent_senha_cliente.grid(row=5, column=1)
        self.ent_email_cliente.grid(row=6, column=1)
        self.btn_criar_acesso_cliente.grid(row=7, column=0)
        self.btn_retirar_acesso_cliente.grid(row=7, column=1)
        self.btn_ver_todos_cliente.grid(row=8, column=0)
        self.btn_atualizar.grid(row=8, column=1)
        self.list.grid(row=1, column=3, rowspan=16)
        self.scroll.grid(row=1, column=4, rowspan=16)
        self.list.configure(yscrollcommand=self.scroll.set)
        self.scroll.configure(command=self.list.yview)

        self.lbl_janela_livro.grid(row=9, column=0)
        self.lbl_id_livro.grid(row=10, column=0)
        self.lbl_nome_livro.grid(row=11, column=0)
        self.lbl_genero_livro.grid(row=12, column=0)
        self.lbl_autor_livro.grid(row=13, column=0)
        self.lbl_area_livro.grid(row=14, column=0)
        self.lbl_editora_livro.grid(row=15, column=0)
        self.lbl_edicao_livro.grid(row=16, column=0)
        self.ent_id_livro.grid(row=10, column=1)
        self.ent_nome_livro.grid(row=11, column=1)
        self.ent_genero_livro.grid(row=12, column=1)
        self.ent_autor_livro.grid(row=13, column=1)
        self.ent_area_livro.grid(row=14, column=1)
        self.ent_editora_livro.grid(row=15, column=1)
        self.ent_edicao_livro.grid(row=16, column=1)
        self.btn_cadastro_livro.grid(row=17, column=0)
        self.btn_retirar_livro.grid(row=17, column=1)
        self.btn_realizar_emprestimo_devolucao.grid(row=18, column=0)
        self.btn_fechar.grid(row=19, column=0)

    def iniciar(self):
        '''Metodo para desenhar a janela e processar eventos'''
        self.config_layout()
        return super().iniciar()
Пример #28
0
class ClientUI:
    def __init__(self, master, client):
        self.master = master
        self.client = client
        self.user_data = UserData()

        master.title("Chatroom")
        master.geometry("720x350")

        self.messages_list = Listbox(self.master,
                                     height=12,
                                     width=75,
                                     border=1,
                                     font=("Helvetica", 11))
        self.messages_list.grid(row=1, column=0, pady=20)
        self.scrollbar = Scrollbar(self.master)
        self.scrollbar.grid(row=1, column=1, sticky=W)

        self.messages_list.configure(yscrollcommand=self.scrollbar.set)
        self.scrollbar.configure(command=self.messages_list.yview)

        self.message_input = Text(self.master, height=4, width=50)
        self.message_input.grid(row=2, column=0, rowspan=4, padx=40)

        self.send_button = Button(master,
                                  text="Send",
                                  command=self.send_message)
        self.send_button.grid(row=2, column=1, pady=20)

        self.master.protocol("WM_DELETE_WINDOW", self.full_exit)

        master.bind('<Return>', self.return_press)
        PopupWindow(master, self.set_username, client)

        threading.Thread(target=self.update_received, daemon=True).start()

    def update_received(self):
        while True:
            messages = self.client.receive_all()
            for message in messages:
                self.messages_list.insert(
                    END, f"{message['user']} > {message['data']}")
                self.messages_list.yview(END)

    def set_username(self, username):
        self.user_data.set_username(username)

    def return_press(self, event):
        self.send_message()

    def send_message(self):
        if not self.user_data.get_user_name():
            print("Username should be provided")
            exit(-1)
        message = self.message_input.get("1.0", END).rstrip()
        if not message:
            return
        self.messages_list.insert(
            END, f"{self.user_data.get_user_name()} > {message}")
        self.messages_list.yview(END)
        self.message_input.delete('1.0', END)
        self.client.send_message(message)

    def full_exit(self):
        self.master.destroy()
        exit()
Пример #29
0
class CadastroVeiculo:
    '''Classe interface cadastrar veiculo'''
    def __init__(self, master=''):
        self.master = master
        self.veiculo = Veiculo()
        self.dao = VeiculoDAO()
        '''
       self.window = Tk()
       self.window.geometry('1350x850+0+0')
       self.window.title('Cadastro de veículo')
       self.window.resizable(0, 0)  # impede de maximizar
       self.window['bg'] = '#c9c9ff'
       '''
        self.heading = Label(self.master,
                             text="Cadastro de Veiculos",
                             bg='#c9c9ff',
                             fg='white',
                             font=('Verdana 20 bold'))
        self.heading.place(x=650, y=0)

        # marca =========================================================================
        self.marca = Label(self.master,
                           text="Marca do veículo :",
                           bg='#c9c9ff',
                           fg='white',
                           font=('Verdana 15 bold'))
        self.marca.place(x=10, y=70)
        self.marca_entry = Entry(self.master,
                                 width=35,
                                 font=('Verdana 15 bold'))
        self.marca_entry.place(x=300, y=70)

        # modelo =========================================================================
        self.modelo = Label(self.master,
                            text="Modelo:",
                            bg='#c9c9ff',
                            fg='white',
                            font=('Verdana 15 bold'))
        self.modelo.place(x=10, y=120)
        self.modelo_entry = Entry(self.master,
                                  width=35,
                                  font=('Verdana 15 bold'))
        self.modelo_entry.place(x=300, y=120)

        # ano =========================================================================
        self.ano = Label(self.master,
                         text="Ano:",
                         bg='#c9c9ff',
                         fg='white',
                         font=('Verdana 15 bold'))
        self.ano.place(x=10, y=170)
        self.ano_entry = Entry(self.master, width=35, font=('Verdana 15 bold'))
        self.ano_entry.place(x=300, y=170)

        # cor =========================================================================
        self.cor = Label(self.master,
                         text="Cor:",
                         bg='#c9c9ff',
                         fg='white',
                         font=('Verdana 15 bold'))
        self.cor.place(x=10, y=220)
        self.cor_entry = Entry(self.master, width=35, font=('Verdana 15 bold'))
        self.cor_entry.place(x=300, y=220)
        # self.cor_entry.insert(END, datetime.date.today())

        # tanque =========================================================================
        self.tanque = Label(self.master,
                            text="Capacidade do tanque:",
                            bg='#c9c9ff',
                            fg='white',
                            font=('Verdana 15 bold'))
        self.tanque.place(x=10, y=270)
        self.tanque_entry = Entry(self.master,
                                  width=35,
                                  font=('Verdana 15 bold'))
        self.tanque_entry.place(x=300, y=270)
        self.tanque_entry.insert(END, "litros")

        # combustivel =========================================================================
        self.combustivel = Label(self.master,
                                 text="Tipo de Combustível:",
                                 bg='#c9c9ff',
                                 fg='white',
                                 font=('Verdana 15 bold'))
        self.combustivel.place(x=10, y=320)
        self.combustivel_entry = Entry(self.master,
                                       width=35,
                                       font=('Verdana 15 bold'))
        self.combustivel_entry.place(x=300, y=320)

        # consumo cidade =========================================================================
        self.consumo_cidade = Label(self.master,
                                    text="Consumo na cidade:",
                                    bg='#c9c9ff',
                                    fg='white',
                                    font=('Verdana 15 bold'))
        self.consumo_cidade.place(x=10, y=370)
        self.consumo_cidade_entry = Entry(self.master,
                                          width=35,
                                          font=('Verdana 15 bold'))
        self.consumo_cidade_entry.place(x=300, y=370)

        self.consumo_cidade_entry.insert(END, "l/km")

        self.consumo_estrada = Label(self.master,
                                     text="Consumo na estrada:",
                                     bg='#c9c9ff',
                                     fg='white',
                                     font=('Verdana 15 bold'))
        self.consumo_estrada.place(x=10, y=420)
        self.consumo_estrada_entry = Entry(self.master,
                                           width=35,
                                           font=('Verdana 15 bold'))
        self.consumo_estrada_entry.place(x=300, y=420)
        self.consumo_estrada_entry.insert(END, "l/km")

        self.tempo_0_100 = Label(self.master,
                                 text="Tempo de 0km/h a 100km/h:",
                                 bg='#c9c9ff',
                                 fg='white',
                                 font=('Verdana 15 bold'))
        self.tempo_0_100.place(x=10, y=470)
        self.tempo_0_100_entry = Entry(self.master,
                                       width=35,
                                       font=('Verdana 15 bold'))
        self.tempo_0_100_entry.place(x=300, y=470)

        self.chassi = Label(self.master,
                            text="Chassi:",
                            bg='#c9c9ff',
                            fg='white',
                            font=('Verdana 15 bold'))
        self.chassi.place(x=10, y=520)
        self.chassi_entry = Entry(self.master,
                                  width=35,
                                  font=('Verdana 15 bold'))
        self.chassi_entry.place(x=300, y=520)

        self.placa = Label(self.master,
                           text="Placa:",
                           bg='#c9c9ff',
                           fg='white',
                           font=('Verdana 15 bold'))
        self.placa.place(x=10, y=570)
        self.placa_entry = Entry(self.master,
                                 width=35,
                                 font=('Verdana 15 bold'))
        self.placa_entry.place(x=300, y=570)

        self.tamanho_pneu = Label(self.master,
                                  text="Tamanho do pneu:",
                                  bg='#c9c9ff',
                                  fg='white',
                                  font=('Verdana 15 bold'))
        self.tamanho_pneu.place(x=10, y=620)
        self.tamanho_pneu_entry = Entry(self.master,
                                        width=35,
                                        font=('Verdana 15 bold'))
        self.tamanho_pneu_entry.place(x=300, y=620)

        self.som = Label(self.master,
                         text="Som:",
                         bg='#c9c9ff',
                         fg='white',
                         font=('Verdana 15 bold'))
        self.som.place(x=10, y=670)
        self.som_entry = Entry(self.master, width=35, font=('Verdana 15 bold'))
        self.som_entry.place(x=300, y=670)

        self.valor_diaria = Label(self.master,
                                  text="valor da diária:",
                                  bg='#c9c9ff',
                                  fg='white',
                                  font=('Verdana 15 bold'))
        self.valor_diaria.place(x=10, y=720)
        self.valor_diaria_entry = Entry(self.master,
                                        width=35,
                                        font=('Verdana 15 bold'))
        self.valor_diaria_entry.place(x=300, y=720)
        self.valor_diaria_entry.insert(END, 'R$ ')

        # BOTAO LIMPAR  =========================================================================
        self.botao_limpar = Button(self.master,
                                   text="Limpar",
                                   width=18,
                                   height=1,
                                   bg='#ffdfba',
                                   fg='black',
                                   font=('Verdana 15 bold'),
                                   command=self.clear_all)
        self.botao_limpar.place(x=800, y=700)

        self.botao_cadastrar = Button(self.master,
                                      text="Cadastrar",
                                      width=37,
                                      height=1,
                                      bg='#baffc9',
                                      fg='black',
                                      font=('Verdana 15 bold'),
                                      command=self.get_items)
        self.botao_cadastrar.place(x=800, y=650)

        self.botao_sair = Button(self.master,
                                 text="Sair",
                                 width=18,
                                 height=1,
                                 bg='#ffb3ba',
                                 fg='black',
                                 font=('Verdana 15 bold'),
                                 command=self.close)
        self.botao_sair.place(x=1070, y=700)

        self.veiculo_box = Listbox(self.master,
                                   width=38,
                                   height=20,
                                   font=('Verdana 15 bold'))
        self.veiculo_box.place(x=800, y=120)

        self.scrollbar_veiculo = Scrollbar(self.master)
        self.veiculo_box.configure(yscrollcommand=self.scrollbar_veiculo.set)
        self.scrollbar_veiculo.configure(command=self.veiculo_box.yview)
        self.scrollbar_veiculo.place(x=1340,
                                     y=120,
                                     relheight=0.62,
                                     anchor='ne')

        self.pesquisar_veiculo = Label(self.master,
                                       text="Lista de veiculos Cadastrados:",
                                       bg='#c9c9ff',
                                       font=('Verdana 15 bold'))
        self.pesquisar_veiculo.place(x=900, y=75)
        self.update_list()

    def update_list(self):
        try:
            self.veiculo_box.delete(0, END)
            for item in self.dao.view():
                self.veiculo_box.insert(END, item)
        except Exception:
            print('Erro na lista veiculos.')

    def get_items(self):
        self.veiculo.marca = self.marca_entry.get()
        self.veiculo.modelo = self.modelo_entry.get()
        self.veiculo.ano = self.ano_entry.get()
        self.veiculo.cor = self.cor_entry.get()
        self.veiculo.tanque = self.tanque_entry.get()
        self.veiculo.combustivel = self.combustivel_entry.get()
        self.veiculo.consumo_cidade = self.consumo_cidade_entry.get()
        self.veiculo.consumo_estrada = self.consumo_estrada_entry.get()
        self.veiculo.tempo_0_100 = self.tempo_0_100_entry.get()
        self.veiculo.chassi = self.chassi_entry.get()
        self.veiculo.placa = self.placa_entry.get()
        self.veiculo.tamanho_pneu = self.tamanho_pneu_entry.get()
        self.veiculo.som = self.som_entry.get()
        self.veiculo.valor_diaria = self.valor_diaria_entry.get()

        if (self.veiculo.marca == '' or self.veiculo.modelo == ''
                or self.veiculo.ano == '' or self.veiculo.cor == ''
                or self.veiculo.tanque == '' or self.veiculo.combustivel == ''
                or self.veiculo.consumo_cidade == ''
                or self.veiculo.consumo_estrada == ''
                or self.veiculo.tempo_0_100 == '' or self.veiculo.chassi == ''
                or self.veiculo.placa == '' or self.veiculo.tamanho_pneu == ''
                or self.veiculo.som == '' or self.veiculo.valor_diaria == ''):
            tkinter.messagebox.showinfo(
                "Aviso:", "POR FAVOR PREENCHER TODOS OS CAMPOS!")
        else:
            try:
                self.veiculo.tanque = float(self.veiculo.tanque)
                self.veiculo.consumo_cidade = float(
                    self.veiculo.consumo_cidade)
                self.veiculo.consumo_estrada = float(
                    self.veiculo.consumo_estrada)
                self.veiculo.tempo_0_100 = float(self.veiculo.tempo_0_100)
                self.veiculo.valor_diaria = float(self.veiculo.valor_diaria)
            except ValueError:
                tkinter.messagebox.showinfo(
                    'Aviso!',
                    'Os campos tamanho do tanque, Consumo na cidade, consumo ma estrada, tempo_0_100 e valor da diária devem ser preenchidos com números!'
                )
            else:
                try:
                    self.dao.insert(self.veiculo)
                except Exception as e:
                    print(e)
                else:
                    tkinter.messagebox.showinfo(
                        'Aviso!', 'Cadastro Realizado com Sucesso!')
                    self.clear_all()
                    self.update_list()

    def clear_all(self):
        self.marca_entry.delete(0, END)
        self.modelo_entry.delete(0, END)
        self.ano_entry.delete(0, END)
        self.cor_entry.delete(0, END)
        self.tanque_entry.delete(0, END)
        self.tanque_entry.insert(END, "litros")

        self.combustivel_entry.delete(0, END)

        self.consumo_cidade_entry.delete(0, END)
        self.consumo_cidade_entry.insert(END, "l/km")

        self.consumo_estrada_entry.delete(0, END)
        self.consumo_estrada_entry.insert(END, "l/km")

        self.tempo_0_100_entry.delete(0, END)
        self.tempo_0_100_entry.insert(END, "segundos")

        self.chassi_entry.delete(0, END)
        self.placa.delete(0, END)
        self.tamanho_pneu.delete(0, END)
        self.som.delete(0, END)
        self.valor_diaria.delete(0, END)
        self.valor_diaria_entry.insert(END, 'R$ ')

    def close(self):
        self.dao.close()
        self.window.destroy()

    def run(self):
        self.window.mainloop()
Пример #30
0
class Example(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("")
        #self.style = Style()
        #self.style.theme_use("clam")
        #self.pack(fill=BOTH, expand = 1)


        self.quitbutton = Button(self, text="Quit", command= lambda: self.quit())

        self.quitbutton.grid(row=3, column=1, pady=4)

        self.labelErrorPointer = Label(self, text="◀")

        self.labellist = []
        self.entrylist = []
        self.verifylist = []
        self.misclist = []
                
        self.optionCreate = "Create"
        self.optionUpcoming = "Upcoming"
        self.optionPast = "Past"

        self.prevmode = self.optionCreate
        self.curmode = self.optionCreate
        self.optionvar = tkinter.StringVar(self)
        self.optionvar.trace("w",self.permaloop)
        self.optionvar.set(self.optionCreate)
        self.option = OptionMenu(self, self.optionvar, self.optionCreate, self.optionUpcoming, self.optionPast)

        self.optionpostmodevar = tkinter.StringVar(self)
        self.optionpostmodevar.trace("w",self.permaloop)
        self.optionpostmodevar.set('url')
        self.optionpostmode = OptionMenu(self, self.optionpostmodevar, 'url', 'text')

        self.labelText = Label(self, text='Selftext:')
        self.entryText = Text(self)
        self.labelURL = Label(self, text='URL:')
        self.entryURL = Entry(self)
        self.entryURL.configure(width=60)  

        self.sql = sqlite3.connect('sql.db')
        print('Loaded SQL Database')
        self.cur = self.sql.cursor()

        self.cur.execute('CREATE TABLE IF NOT EXISTS upcoming(ID TEXT, SUBREDDIT TEXT, TIME INT, TITLE TEXT, URL TEXT, BODY TEXT)')
        self.cur.execute('CREATE TABLE IF NOT EXISTS past(ID TEXT, SUBREDDIT TEXT, TIME INT, TITLE TEXT, URL TEXT, BODY TEXT, POSTLINK TEXT)')
        self.cur.execute('CREATE TABLE IF NOT EXISTS internal(NAME TEXT, ID INT)')
        print('Loaded Completed table')
        self.cur.execute('SELECT * FROM internal')
        f = self.cur.fetchone()
        if not f:
            print('Database is new. Adding ID counter')
            self.cur.execute('INSERT INTO internal VALUES(?, ?)', ['counter', 1])
            self.idcounter = 1
        else:
            self.idcounter = f[1]
            print('Current ID counter: ' + str(self.idcounter))

        self.sql.commit()
        

        
        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()


        w=853
        h=480
        x = (sw - w) / 2
        y = (sh - h) / 2

        self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y-50))

        self.login()
        

    def login(self):

        try:
            self.quitbutton.grid_forget()
            self.quitbutton.grid(row=9000, column=0, columnspan=20)          

            self.option.grid(row=1,column=0,columnspan=80,pady=8)

            self.updategui(fullclean=True)
        except praw.errors.InvalidUserPass:
            pass
            print('Invalid username or password')
            self.entryPassword.delete(0,200)
            self.labelErrorPointer.grid(row=1, column=2)

    def permaloop(self, *args):
        self.curmode = self.optionvar.get()
        print('Was: ' + self.prevmode + ' | Now: ' + self.curmode)
        if self.curmode != self.prevmode:
            self.prevmode = self.curmode
            self.updategui(fullclean=True)
        else:
            self.updategui(False)

    def getTime(self, bool):
        timeNow = datetime.datetime.now(datetime.timezone.utc)
        timeUnix = timeNow.timestamp()
        if bool is False:
            return timeNow
        else:
            return timeUnix

    def addentrytobase(self, subreddit, title, url="", body="", mode="", ptime=""):
        curtime = round(self.getTime(True))
        try:
            t = self.entryMo.get() + ' ' + self.entryDa.get() + ' ' + self.entryYr.get() + ' ' + self.entryHH.get() + ':' + self.entryMM.get()
            plandate = datetime.datetime.strptime(t, "%B %d %Y %H:%M")
            plandate = plandate.timestamp()
        except ValueError:
            print('Invalid Day')
            return False

        if mode == 'url':
            url = self.entryURL.get()
            body = ""
            if 'http://' not in url and 'https://' not in url:
                print('Please enter a proper URL')
                return False
        if mode == 'text':
            body = self.entryText.get("1.0", "end")
            url = ""

        if plandate < curtime:
            print('Please enter a time in the future')
            return False

        if not all(char in string.ascii_letters+string.digits+'_-' for char in subreddit):
            print('Subreddit contains invalid characters')
            return False

        if len(subreddit) == 0:
            print('You must enter a subreddit')
            return False

        if len(title) == 0:
            print('You must enter a title')
            return False
        if len(title) > 300:
            print('Title is too long. ' + str(len(title)) + '/300 char max')
            return False
        if len(body) > 15000:
            print('Body is too long. ' + str(len(body)) + '/15,000 char max')

        print('Timestamp:', plandate)
        self.cur.execute('INSERT INTO upcoming VALUES(?, ?, ?, ?, ?, ?)', [self.idcounter, subreddit, int(plandate), title, url, body])
        self.idcounter += 1
        self.cur.execute('UPDATE internal SET ID=? WHERE NAME=?', [self.idcounter, 'counter'])
        self.sql.commit()
        print('\nPost Saved!')
        print(self.idcounter, subreddit, self.timestamptoday(int(plandate)))
        print(title)
        print(url, body)
        print()
        self.entryText.delete("1.0", "end")
        self.entryURL.delete(0, 'end')
        self.entryTitle.delete(0, 'end')
        #self.updategui(halfclean=True)

    def timestamptoday(self, timestamp):
        d = datetime.datetime.fromtimestamp(timestamp)
        info = datetime.datetime.strftime(d, "%b %d %H:%M")
        return info


    def dropentryfrombase(self, ID):
        if '-' not in ID:
            try:
                ID = int(ID)
                l = [ID]
            except ValueError:
                print('You must enter a number')
                return
        else:
            if ID.count('-') == 1:
                try:
                    ID = ID.replace(' ', '')
                    ID = ID.split('-')
                    ID[0] = int(ID[0])
                    ID[1] = int(ID[1])
                    if ID[1] > ID[0]:
                        l = list(range(ID[0], ID[1]+1))
                    else:
                        return
                except ValueError:
                    return

        for item in l:
            item = str(item)
            print('Dropping Item ' + item + ' from Upcoming')
            self.cur.execute('DELETE FROM upcoming WHERE ID=?', [item])
            self.sql.commit()
        self.updategui(fullclean=True)

    def printbasetofile(self, db):
        filea = open(db + '.txt', 'w')
        if db == 'past':
            self.cur.execute('SELECT * FROM past')
        if db == 'upcoming':
            self.cur.execute('SELECT * FROM upcoming')
        f = self.cur.fetchall()
        print('Printed ' + db + ' unimpeded to file')
        for item in f:
            i = list(item)
            i[2] = self.timestamptoday(i[2])
            i.remove('')

            print(str(i)[1:-1], file=filea)
        filea.close()

        


    def updategui(self, halfclean=False, fullclean=False):

        if self.curmode == self.optionCreate:
            try:
                print(self.optionpostmodevar.get())

                if self.optionpostmodevar.get() == 'url':
                    self.entryText.delete("1.0", 'end')
                    self.labelText.grid_forget()
                    self.entryText.grid_forget()
    
                    self.labelURL.grid(row=8, column=0, columnspan=30)
                    self.entryURL.grid(row=9, column=0, columnspan=12, pady=10)
    
                if self.optionpostmodevar.get() == 'text':
                    self.entryURL.delete(0, 'end')
                    self.labelURL.grid_forget()
                    self.entryURL.grid_forget()
    
                    self.labelText.grid(row=8, column=0, columnspan=30)
                    self.entryText.configure(width=40, height=8)
                    self.entryText.grid(row=9, column=0, columnspan=12)
            except AttributeError:
                pass

        if fullclean is True:
            print('Cleaning GUI')
            for item in self.labellist:
                item.grid_forget()
            for item in self.entrylist:
                item.grid_forget()
            for item in self.verifylist:
                item.grid_forget()
            for item in self.misclist:
                item.grid_forget()
            self.labellist = []
            self.entrylist = []
            self.verifylist = []
            self.misclist = []

            if self.curmode == self.optionCreate:
                self.newrowindex = 6
                self.labelSubreddit = Label(self, text="Subreddit:    /r/")
                self.labelTitle = Label(self, text="Post title:  ")
                self.entrySubreddit = Entry(self)
                self.entryTitle = Entry(self)


                self.labelHH = Label(self, text="Schedule time (Local timezone):")
                nowlist = datetime.datetime.strftime(datetime.datetime.now(), "%B %d %Y %H %M").split()

                self.entryMo = Spinbox(self, width=9, values=('January', 'February', 'March', 'April', 'May', 'June', 'July', \
                    'August', 'September', 'October', 'November', 'December'))
                self.entryMo.delete(0,'end')
                self.entryMo.insert(0, nowlist[0])


                self.entryDa = Spinbox(self, width=2, from_=1, to=31)
                self.entryDa.delete(0,'end')
                self.entryDa.insert(0, nowlist[1])

                self.entryYr = Spinbox(self, width=4, from_=2014, to=2500)
                self.entryYr.delete(0,'end')
                self.entryYr.insert(0, nowlist[2])

                self.entryHH = Spinbox(self, from_=0, to=23, width=2)
                self.entryHH.delete(0,'end')
                self.entryHH.insert(0, nowlist[3])

                self.entryMM = Spinbox(self, from_=0, to=59, width=2)
                self.entryMM.delete(0,'end')
                self.entryMM.insert(0, nowlist[4])

                self.buttonAddentry = Button(self, text='Save', command=lambda: self.addentrytobase(self.entrySubreddit.get(), self.entryTitle.get(),\
                    mode=self.optionpostmodevar.get()))


                self.misclist.append(self.labelSubreddit)
                self.misclist.append(self.entrySubreddit)
                self.misclist.append(self.labelHH)
                self.misclist.append(self.entryHH)
                self.misclist.append(self.entryMM)
                self.misclist.append(self.entryMo)
                self.misclist.append(self.entryDa)
                self.misclist.append(self.entryYr)
                self.misclist.append(self.labelTitle)
                self.misclist.append(self.entryTitle)
                self.misclist.append(self.buttonAddentry)
                self.misclist.append(self.optionpostmode)
                self.misclist.append(self.labelText)
                self.misclist.append(self.entryText)
                self.misclist.append(self.labelURL)
                self.misclist.append(self.entryURL)

                self.labelSubreddit.grid(row=2, column=0, sticky="e")
                self.labelTitle.grid(row=3, column=0, sticky="e")
                self.entrySubreddit.grid(row=2, column=1, columnspan=3, sticky="w")
                self.entryTitle.grid(row=3, column=1, columnspan=3, sticky="w")
                self.entryMo.grid(row=4, column=1,sticky="e")
                self.entryDa.grid(row=4, column=2)
                self.entryYr.grid(row=4, column=3)
                self.labelHH.grid(row=4, column=0, sticky="se", pady=5)
                self.entryHH.grid(row=5, column=1, sticky="e")
                self.entryMM.grid(row=5, column=2, sticky="w")
                self.optionpostmode.grid(row=6, column=0, columnspan=20, pady=10)
                self.buttonAddentry.grid(row=200, column=0, columnspan=20)

            if self.curmode == self.optionUpcoming:
                self.cur.execute('SELECT * FROM upcoming')
                dobutton = True

            if self.curmode == self.optionPast:
                self.cur.execute('SELECT * FROM past')
                dobutton = False

            if self.curmode == self.optionPast or self.curmode == self.optionUpcoming:

                
                self.listboxId = Listbox(self)
                self.listboxId.configure(width=118, height=20, font=("Courier 8"))
                self.misclist.append(self.listboxId)

                self.listboxScroller = Scrollbar(self, orient='horizontal', command=self.listboxId.xview)
                self.listboxScroller.grid(row=4, column=0, columnspan=900)
                self.listboxId.grid(row=3, column=0, columnspan=10)

                self.listboxId.configure(xscrollcommand=self.listboxScroller.set)
                self.misclist.append(self.listboxScroller)

                self.buttonPrinter = Button(self, text="Print to .txt file")
                if self.curmode == self.optionPast:
                    self.buttonPrinter.configure(command=lambda: self.printbasetofile('past'))
                if self.curmode == self.optionUpcoming:
                    self.buttonPrinter.configure(command=lambda: self.printbasetofile('upcoming'))   

                self.buttonPrinter.grid(row = 6, column=0, columnspan=90)
                self.misclist.append(self.buttonPrinter)

                if dobutton is True:
                    self.entryDelete = Entry(self)
                    self.buttonDelete = Button(self, text="Delete Item: ", command=lambda: self.dropentryfrombase(self.entryDelete.get()))
                    self.buttonDelete.grid(row=5, column=0, sticky='e')
                    self.entryDelete.grid(row=5, column=1, sticky='w')
                    self.misclist.append(self.entryDelete)
                    self.misclist.append(self.buttonDelete)


                fetched = self.cur.fetchall()
                for item in fetched:

                    info = self.timestamptoday(item[2])

                    if item[4] == '':
                        infx = item[5]
                    if item[5] == '':
                        infx = item[4]
                    if self.curmode == self.optionPast:
                        infy = '.' + item[6]
                    else:
                        infy = ''

                    self.listboxId.insert('end', \
                        item[0] + '.'*(6 - len(item[0])) \
                        + item[1][:10] + '.'*(12 - len(item[1][:10])) \
                        + info + '.'*(15 - len(info[:14])) \
                        + item[3][:18] + '.'*(20 - len(item[3][:14])) \
                        + infx[:45] + '.'*(47-len(infx[:45])) \
                        + infy)

                    
                



    def morerows(self, label, columnm, columnn, limit, *args):
        self.redditlabel = Label(self,text=label)
        self.redditlabel.grid(row=self.newrowindex,column=columnm, sticky="e")
        self.labellist.append(self.redditlabel)

        self.redditentry = Entry(self)
        self.redditentry.grid(row=self.newrowindex,column=columnn, columnspan=9)
        self.entrylist.append(self.redditentry)

        self.newrowindex += 1
        if self.newrowindex >= limit:
            self.morerowbutton.grid_forget()
        print(self.newrowindex)
Пример #31
0
class MusicPanel(Frame):
    def __init__(self, parent, musicController: IMusicController):
        super().__init__(parent)
        self.musicController = musicController
        self.musicList: List[Music] = []

        self.selectedMusicPath: str = None

        self.__initView()

    def __initView(self):
        self.grid_columnconfigure(0, weight=1)

        self.musicListBox = Listbox(self)
        self.musicListBox.grid(row=0,
                               column=0,
                               sticky='WE',
                               padx=(10, 0),
                               pady=10)
        self.musicListBox.bind('<Double-1>', self.musicDoubleClicked)
        self.musicListBox.bind("<<ListboxSelect>>", self.musicSelected)

        musicScrollbar = Scrollbar(self, command=self.musicListBox.yview)
        musicScrollbar.grid(row=0,
                            column=1,
                            sticky='NS',
                            padx=(0, 10),
                            pady=10)

        self.musicListBox.configure(yscrollcommand=musicScrollbar.set)

        ################################################################################

        skipLabel = Label(self, text=SKIP_TEXT)
        skipLabel.grid(row=1, column=0)

        self.skipListBox = Listbox(self, exportselection=0)
        self.skipListBox.grid(row=2,
                              column=0,
                              sticky='WE',
                              padx=(10, 0),
                              pady=10)

        skipScrollbar = Scrollbar(self, command=self.skipListBox.yview)
        skipScrollbar.grid(row=2, column=1, sticky='NS', padx=(0, 10), pady=10)

        self.skipListBox.configure(yscrollcommand=skipScrollbar.set)

        self.deleteSkipButton = Button(self,
                                       text=DELETE_SKIP_TEXT,
                                       command=self.onSkipDelete)
        self.deleteSkipButton.grid(row=3, column=0, sticky='W', padx=10)

        ################################################################################

        self.addSkipFrame = Frame(self)
        self.addSkipFrame.grid(row=4, column=0, padx=10, sticky='W')

        self.addSkipLabel = Label(self.addSkipFrame, text=ADD_SKIP_LABEL_TEXT)
        self.addSkipLabel.grid(row=0, column=0)

        self.addSkipStartMinutesTE = Entry(self.addSkipFrame,
                                           width=5,
                                           exportselection=0)
        self.addSkipStartMinutesTE.insert(END, '0')
        self.addSkipStartMinutesTE.grid(row=0, column=1)

        label = Label(self.addSkipFrame, text=':')
        label.grid(row=0, column=2)

        self.addSkipStartSecondsTE = Entry(self.addSkipFrame,
                                           width=5,
                                           exportselection=0)
        self.addSkipStartSecondsTE.insert(END, '0')
        self.addSkipStartSecondsTE.grid(row=0, column=3)

        label = Label(self.addSkipFrame, text=ADD_SKIP_TO_LABEL_TEXT)
        label.grid(row=0, column=4)

        self.addSkipEndMinutesTE = Entry(self.addSkipFrame,
                                         width=5,
                                         exportselection=0)
        self.addSkipEndMinutesTE.insert(END, '0')
        self.addSkipEndMinutesTE.grid(row=0, column=5)

        label = Label(self.addSkipFrame, text=':')
        label.grid(row=0, column=6)

        self.addSkipEndSecondsTE = Entry(self.addSkipFrame,
                                         width=5,
                                         exportselection=0)
        self.addSkipEndSecondsTE.insert(END, '0')
        self.addSkipEndSecondsTE.grid(row=0, column=7)

        self.addSkipButton = Button(self.addSkipFrame,
                                    text=ADD_SKIP_BUTTON_TEXT,
                                    command=self.__addSkip)
        self.addSkipButton.grid(row=0, column=8, padx=2)

    def displayMusic(self, music: List[Music]):
        self.musicList = music

        self.musicListBox.delete(0, 'end')
        for i in range(len(music)):
            m = music[i]
            self.musicListBox.insert(i, m)

        if self.selectedMusicPath is not None:
            selectedIndex = -1
            for i in range(len(self.musicList)):
                if self.musicList[i].path == self.selectedMusicPath:
                    selectedIndex = i
                    break

            if selectedIndex >= 0:
                self.musicListBox.select_set(selectedIndex)
                self.musicListBox.event_generate("<<ListboxSelect>>")

    def musicDoubleClicked(self, event):
        music = self.musicList[self.musicListBox.curselection()[0]]
        self.musicController.onMusicDoubleClicked(music)

    def onSkipDelete(self):
        musicSelection = self.musicListBox.curselection()
        skipSelection = self.skipListBox.curselection()

        if len(skipSelection) <= 0 or len(musicSelection) <= 0:
            messagebox.showwarning('Warning', DELETE_SKIP_SELECT_MUSIC)
            return

        music = self.musicList[musicSelection[0]]
        self.musicController.onSkipDeleteClicked(music.skips[skipSelection[0]])

    def musicSelected(self, event):
        self.skipListBox.delete(0, 'end')

        selection = self.musicListBox.curselection()
        if len(selection) <= 0:
            return

        selectedMusic = self.musicList[selection[0]]
        self.selectedMusicPath = selectedMusic.path

        if selectedMusic.skips is not None:
            for i in range(len(selectedMusic.skips)):
                s = selectedMusic.skips[i]

                startMinute = int(s.start / 60)
                startSecond = s.start % 60
                stopMinute = int(s.end / 60)
                stopSecond = s.end % 60

                text = f'Skip from {startMinute:02d}:{startSecond:02d} to {stopMinute:02d}:{stopSecond:02d}'
                self.skipListBox.insert(i, text)

    def __addSkip(self):
        selection = self.musicListBox.curselection()

        if len(selection) <= 0:
            messagebox.showwarning('Warning', ADD_SKIP_SELECT_MUSIC)
            return

        music = self.musicList[selection[0]]

        try:
            startMinutes = int(self.addSkipStartMinutesTE.get())
            startSeconds = int(self.addSkipStartSecondsTE.get())
            endMinutes = int(self.addSkipEndMinutesTE.get())
            endSeconds = int(self.addSkipEndSecondsTE.get())
        except:
            messagebox.showwarning('Warning', ADD_SKIP_PARSE_ERROR_TEXT)
            return

        start = startMinutes * 60 + startSeconds
        end = endMinutes * 60 + endSeconds

        if end <= start:
            messagebox.showwarning('Warning', ADD_SKIP_END_LOWER_THAN_START)
            return

        self.musicController.onSkipAddClicked(music.path, start, end)
Пример #32
0
# Add  a listbox  to display data from database
# padx and pady method is used to add space (margin) horizontally and vertically
list_bx = Listbox(root,
                  height=16,
                  width=40,
                  font='helvetica 13',
                  bg='light blue')
list_bx.grid(row=3, column=1, columnspan=14, sticky=W + E, pady=40, padx=15)
list_bx.bind('<<ListboxSelect>>', get_selected_row)

#Create a scroll bar
scroll_bar = Scrollbar(root)
scroll_bar.grid(row=1, column=8, rowspan=14, sticky=W)
#Attach the scrollbar into the listbox (yscroll bar for vertical scrollbar)
list_bx.configure(yscrollcommand=scroll_bar.set)
scroll_bar.configure(command=list_bx.yview)

#create a Modify button
modify_btn = Button(root,
                    text="Modify Record",
                    bg='purple',
                    fg="white",
                    font="helvetica 10 bold",
                    command=update_records)
modify_btn.grid(row=15, column=4)

#create a Delete button
delete_btn = Button(root,
                    text="Delete Record",
                    bg='red',
Пример #33
0
def second_window(root, info):
    def next_step():
        idxs = lbox.curselection()
        for blogger in idxs:
            name = bloggers()[blogger]
            if name not in info['bloggers']:
                info['bloggers'].append(name)
        if 'Blogs' in info['platforms']:
            blog_posts(root, info)
        else:
            third_window(root, info)

    def cantfind(info=info):
        idxs = lbox.curselection()
        for blogger in idxs:
            name = bloggers()[blogger]
            if name not in info['bloggers']:
                info['bloggers'].append(name)
        add_blogger(info=info)

    def active_next(*args):
        send.state(['!disabled', 'active'])

    def back():
        idxs = lbox.curselection()
        for blogger in idxs:
            name = bloggers()[blogger]
            if name not in info['bloggers']:
                info['bloggers'].append(name)
        first_window(root, info=info)

    c = ttk.Frame(root, padding=(5, 0, 0, 0))
    c.grid(column=0, row=0, sticky=(N, W, E, S))

    background_image = tkinter.PhotoImage(file='%s/Desktop/natappy/images/moon.gif' % home)
    background_label = tkinter.Label(c, image=background_image)
    background_label.image = background_image
    background_label.place(x=0, y=0, relwidth=1, relheight=1)

    root.grid_columnconfigure(0, weight=3)
    root.grid_rowconfigure(0, weight=3)

    lbox = Listbox(c, selectmode=MULTIPLE)
    lbox.grid(column=0, row=1, rowspan=11, columnspan=7, sticky=(
        N, W, S), padx=(10, 10), pady=(1, 1), ipadx=75)

    yscroll = ttk.Scrollbar(command=lbox.yview, orient=VERTICAL)
    yscroll.grid(row=0, column=0, padx=(0, 10), sticky=(N, W, S))

    lbox.configure(yscrollcommand=yscroll.set)

    for blogger in bloggers():
        lbox.insert(END, blogger)
        lbox.bind("<<ListboxSelect>>")

    lbox.yview_scroll(40, 'units')

    cantfind = ttk.Button(c, text='Add new bloggers', command=cantfind)
    cantfind.grid(column=4, row=1, padx=(10, 0), sticky=(N, S, E, W), pady=(20, 10))

    send = ttk.Button(c, text='Next', command=next_step, default='active', state='disabled')
    send.grid(column=6, row=11, sticky=E, pady=20, padx=(2, 20))

    close = ttk.Button(c, text='Back', command=back, default='active')
    close.grid(column=5, row=11, sticky=S + E, pady=20, padx=2)

    lbox.bind('<<ListboxSelect>>', active_next)

    if info['bloggers']:
        for blogger in info['bloggers']:
            i = bloggers().index(blogger)
            lbox.selection_set(i)
        active_next()

    for i in range(len(bloggers()), 2):
        lbox.itemconfigure(i, background='#f0f0ff')

    c.grid_columnconfigure(0, weight=1)
    c.grid_rowconfigure(5, weight=1)

    root.title('2/5 Select bloggers')
    root.geometry('680x550+300+40')
Пример #34
0
    # Images Frame
    # The first section (Listbox section)
    _img_frame = ttk.LabelFrame(_main_frame, text='Content', padding='9 0 0 0')
    _img_frame.grid(row=1, column=0, sticky=(N, S, E, W))
    _images = StringVar()
    _imgs_listbox = Listbox(_img_frame,
                            listvariable=_images,
                            height=6,
                            width=25)
    _imgs_listbox.grid(row=0, column=0, sticky=(E, W), pady=5)
    _scrollbar = ttk.Scrollbar(_img_frame,
                               orient=VERTICAL,
                               command=_imgs_listbox.yview)
    _scrollbar.grid(row=0, column=1, sticky=(S, N), pady=6)
    _imgs_listbox.configure(yscrollcommand=_scrollbar.set)

    # The second section (Radio buttons section)
    _radio_frame = ttk.Frame(_img_frame)
    _radio_frame.grid(row=0, column=2, sticky=(N, S, W, E))
    _choice_lbl = ttk.Label(_radio_frame, text='Choose how to save images')
    _choice_lbl.grid(row=0, column=0, padx=5, pady=5)

    _save_method = StringVar()
    _save_method.set('img')
    _img_only_radio = ttk.Radiobutton(_radio_frame,
                                      text='As images',
                                      variable=_save_method,
                                      value='img')
    _img_only_radio.grid(row=1, column=0, padx=5, pady=2, sticky=W)
    _img_only_radio.configure(state='normal')
Пример #35
0
class MainAppController(Frame):
    """ Main Application for GUI """
    def __init__(self, parent):
        """ Initialize Main Application """
        Frame.__init__(self, parent)

        # create a style object
        style = Style()
        style.configure('D.TButton', foreground='red3')
        style.configure('R.TButton',
                        foreground='DodgerBlue4',
                        font=("TkTextFont", 9, 'bold'))
        style.configure('B.TButton',
                        foreground='FireBrick4',
                        font=("TkTextFont", 9, 'bold'))

        # Left frame, column 1
        left_frame = Frame(master=self)
        left_frame.grid(row=1, column=1, padx=30, pady=35, rowspan=3)

        # Middle frame (info text, column 2)
        middle_frame = Frame(master=self)
        middle_frame.grid(row=1, column=2, padx=30, pady=35, rowspan=3)

        # Right frame (statistics, column 3)
        right_frame = Frame(master=self)
        right_frame.grid(row=1, column=3, padx=30, pady=35, rowspan=2)

        # LEFT FRAME WIDGET
        Label(left_frame, text="Book ID",
              font=("TkTextFont", 11)).grid(row=1, column=1, columnspan=3)
        self._book_list = Listbox(left_frame,
                                  height=10,
                                  width=10,
                                  font=("TkTextFont", 11),
                                  bg='LightSalmon2')
        self._book_list.grid(row=2, column=1)
        self._book_list.configure(justify="center")

        # Call this on select
        self._book_list.bind("<<ListboxSelect>>", self._update_textbox)

        # MIDDLE FRAME WIDGET
        Label(middle_frame, text="Book Summary",
              font=("TkTextFont", 11)).grid(row=1, column=2, columnspan=7)
        self._info_text = Text(master=middle_frame,
                               height=10,
                               width=45,
                               font=("TkTextFont", 11),
                               bg='plum2')
        self._info_text.grid(row=2, column=2, columnspan=7)
        self._info_text.tag_configure("bold", font=("TkTextFont", 10, "bold"))

        # RIGHT FRAME WIDGET
        Label(right_frame, text="Book Statistics",
              font=("TkTextFont", 11)).grid(row=1, column=1, columnspan=3)
        self._book_stat = Text(master=right_frame,
                               height=10.5,
                               width=30,
                               font=("TkTextFont", 10),
                               bg='LightSalmon2')
        self._book_stat.grid(row=2, column=1, rowspan=3)
        self._book_stat.tag_configure("bold", font=("TkTextFont", 10, "bold"))

        # Drop Down menu to add a book
        self._add_var = StringVar(left_frame)
        choices = ['eBook', 'Textbook']
        OptionMenu(middle_frame, self._add_var, 'Select Type',
                   *choices).grid(row=3, column=2, pady=5, columnspan=4)

        # Drop Down menu to update a book
        self._update_var = StringVar(left_frame)
        choices = ['eBook', 'Textbook']
        OptionMenu(middle_frame, self._update_var, 'Select Type',
                   *choices).grid(row=3, column=3, pady=5, columnspan=7)

        # A couple buttons - using TTK
        Button(left_frame,
               text="Delete Book",
               width=13,
               command=self._delete_book,
               style='D.TButton').grid(row=3, column=1, pady=5)
        Button(left_frame, text="Quit", width=13,
               command=self._quit_callback).grid(row=4, column=1)
        Button(middle_frame, text="Add Book", width=13,
               command=self._add_book).grid(row=4, column=2, columnspan=4)
        Button(middle_frame,
               text="Update Book",
               width=13,
               command=self._update_book).grid(row=4, column=3, columnspan=7)
        Button(right_frame,
               text="Borrow Book",
               width=13,
               command=self._borrow_cb,
               style='B.TButton').grid(row=5, column=1, pady=5)
        Button(right_frame,
               text="Return Book",
               width=13,
               command=self._return_cb,
               style='R.TButton').grid(row=6, column=1)

        # Now update the list and Statistics
        self._update_book_list()

    def _update_textbox(self, *args):
        """ Updates the info text box on the right, based on the current ID selected """
        # This is a list, so we take just the first item (could be multi select...)
        try:
            selected_index = self._book_list.curselection()[0]
        except IndexError:
            return None
        book_id = self._book_list.get(selected_index)

        # Make a GET request
        r = requests.get(
            f"http://localhost:5000/library_manager/book/{book_id}")

        # Clear the text box
        self._info_text.delete(1.0, tk.END)

        # Check the request status code
        if r.status_code != 200:
            self._info_text.insert(tk.END, "Error running the request!")

        # For every item (key, value) in the JSON response, display them:
        for k, v in r.json().items():
            self._info_text.insert(tk.END, f"{k.capitalize()}\t\t", "bold")
            self._info_text.insert(tk.END, f"{v}\n")

        self._update_book_stat()

    def _update_book_list(self):
        """ Update the List of Books """
        r = requests.get("http://localhost:5000/library_manager/all")
        self._book_list.delete(0, tk.END)
        for s in r.json()["ebook"]:
            self._book_list.insert(tk.END, '{:^}'.format(s['book_id']))
            self._book_list.itemconfig(tk.END, {'fg': 'Blue4'})
            if s['is_borrowed']:
                self._book_list.itemconfig(tk.END, {'bg': 'khaki1'})

        for s in r.json()["textbook"]:
            self._book_list.insert(tk.END, '{:^}'.format(s['book_id']))
            self._book_list.itemconfig(tk.END, {'fg': 'Brown4'})
            if s['is_borrowed']:
                self._book_list.itemconfig(tk.END, {'bg': 'khaki1'})
        self._update_book_stat()

    def _update_book_stat(self):
        """ Update the List of Books """
        r = requests.get("http://localhost:5000/library_manager/all/stats")
        self._book_stat.delete(1.0, tk.END)
        for k, v in r.json().items():
            self._book_stat.insert(tk.END, f"{k}\t\t\t", "bold")
            self._book_stat.insert(tk.END, f"{v}\n")

    def _borrow_cb(self):
        """Borrow any book with the selected ID"""
        if not self._book_list.curselection():
            mb.showerror('Error : Item not selected', 'Please select a book.')
        else:
            selected_index = self._book_list.curselection()[0]
            book_id = self._book_list.get(selected_index)
            r = requests.get(
                f"http://127.0.0.1:5000/library_manager/book/{book_id}")
            if r.json()['is_borrowed']:
                mb.showerror('Error : Bad selection',
                             'Book is already borrowed.')
            else:
                response = requests.put(
                    f"http://127.0.0.1:5000/library_manager/{book_id}/borrow")
                if response.status_code == 200:
                    self._update_book_list()

    def _return_cb(self):
        """Return any book with the selected ID to library"""
        if not self._book_list.curselection():
            mb.showerror('Error : Item not selected', 'Please select a book.')
        else:
            selected_index = self._book_list.curselection()[0]
            book_id = self._book_list.get(selected_index)
            r = requests.get(
                f"http://127.0.0.1:5000/library_manager/book/{book_id}")
            if not r.json()['is_borrowed']:
                mb.showerror('Error : Bad selection',
                             'Book is already returned.')
            else:
                response = requests.put(
                    f"http://127.0.0.1:5000/library_manager/{book_id}/return_book"
                )
                if response.status_code == 200:
                    self._update_book_list()

    def _add_ebook(self):
        """ Add eBook Popup """
        self._popup_win = tk.Toplevel()
        self._popup = AddeBookPopup(self._popup_win, self._close_book_cb)

    def _add_textbook(self):
        """ Add Textbook Popup """
        self._popup_win = tk.Toplevel()
        self._popup = AddTextbookPopup(self._popup_win, self._close_book_cb)

    def _add_book(self):
        """Redirect add book based on the type"""
        if self._add_var.get() == 'eBook':
            self._add_ebook()
        elif self._add_var.get() == 'Textbook':
            self._add_textbook()
        else:
            mb.showerror('Error : Type not selected', 'Please select a type.')

    def _update_book(self):
        """Update eBook attributes"""
        if self._update_var.get() == 'eBook':
            self._update_ebook()
        elif self._update_var.get() == 'Textbook':
            self._update_textbook()
        else:
            mb.showerror('Error : Type not selected', 'Please select a type.')

    def _update_ebook(self):
        """Update ebook attributes in the 'Book' database"""
        if not self._book_list.curselection():
            mb.showerror('Error : Book not selected', 'Please select a book.')
        else:
            selected_index = self._book_list.curselection()[0]
            book_id = self._book_list.get(selected_index)
            r = requests.get(
                f"http://localhost:5000/library_manager/book/{book_id}")
            if r.json()['type'] != 'ebook':
                mb.showerror('Error : Invalid selection',
                             'Please select an ebook ID.')
            else:
                self._popup_win = tk.Toplevel()
                self._popup = UpdateeBookPopup(self._popup_win, book_id,
                                               self._close_book_cb)
        self._update_book_list()

    def _update_textbook(self):
        """Update textbook attributes in the 'Book' database"""
        if not self._book_list.curselection():
            mb.showerror('Error : Book not selected', 'Please select a book.')
        else:
            self._popup_win = tk.Toplevel()
            selected_index = self._book_list.curselection()[0]
            book_id = self._book_list.get(selected_index)
            r = requests.get(
                f"http://localhost:5000/library_manager/book/{book_id}")
            if r.json()['type'] != 'textbook':
                mb.showerror('Error : Invalid selection',
                             'Please select a textbook ID.')
            else:
                self._popup = UpdateTextbookPopup(self._popup_win, book_id,
                                                  self._close_book_cb)
        self._update_book_list()

    def _delete_book(self):
        """ Delete book Popup """
        self._popup_win = tk.Toplevel()
        self._popup = DeleteBook(self._popup_win, self._close_book_cb)

    def _close_book_cb(self):
        """ Close Popup """
        self._popup_win.destroy()
        self._update_book_list()

    def _quit_callback(self):
        """ Quit """
        self.quit()
Пример #36
0
details_text = StringVar()
label_5 = Label(app, text='报备事项:', font=(20), pady=20)
label_5.grid(row=2, column=0, sticky=E)
entry_details = Entry(app, textvariable=details_text)
entry_details.grid(row=2, column=1)

#listbox
details_list = Listbox(app, height=8, width=100)
details_list.grid(row=4, column=0, columnspan=4, rowspan=6, pady=20, padx=20)

#scroll
scrollbar = Scrollbar(app)
scrollbar.grid(row=4, column=5)

#set scroll to listbox
details_list.configure(yscrollcommand=scrollbar.set)
scrollbar.configure(command=details_list.yview)

#bind select
details_list.bind('<<ListboxSelect>>', select_item)

#buttons
add_btn = Button(app, text="Add Part", width=12, command=add_item)
add_btn.grid(row=3, column=0, pady=20)

remove_btn = Button(app, text="Remove", width=12, command=remove_item)
remove_btn.grid(row=3, column=1)

update_btn = Button(app, text="Update", width=12, command=update_item)
update_btn.grid(row=3, column=2)
Пример #37
0
class Player(object):

    """Player class"""

    def __init__(self):

        """Initialisation of the Player object"""

        self.cfg = None
        self.db = None
        self.root = Tk()
        self.URL1L = StringVar(master=self.root)
        self.URL2L = StringVar(master=self.root)
        self.URL3L = StringVar(master=self.root)
        self.URL4L = StringVar(master=self.root)
        self.URL5L = StringVar(master=self.root)
        self.files = {}
        self.start()

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

    def start(self):

        """Start the Player"""

        print("*** Starting the Player ***")
        # Configuration
        self.cfg = Config()
        while not self.cfg.readConf() or not self.cfg.checkConf():
            self.displayConfig()
        if self.cfg.readConf() and self.cfg.checkConf():
            # Database
            self.db = Db(self.cfg)
            if self.db.openDb():
                self.display()
                return(True)
            else:
                error("Database not open")
                return(False)
        else:
            error("Cannot read configuration file")
            return(False)

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

    def stop(self):

        """Stop the Player"""

        msg = "Do you want to quit RasPyPlayer ?"
        if messagebox.askokcancel("RasPyPlayer", msg):
            print("*** Stopping the Player ***")
            self.db.closeDb()
            self.root.destroy()

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

    def scanDB(self):

        """Add movies in DB"""

        print("*** Adding movies in database")
        self.db.initDb()
        scanFiles(self.db, self.cfg, self.cfg.PATH)
        self.db.commitDb()
        return(True)

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

    def loadAllMovies(self):

        """Load movies from DB"""

        self.files = self.db.getAllMovies()
        return(True)

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

    def loadSrcMovies(self, src):

        """Load movies matching search pattern"""

        self.files = self.db.getSrcMovies(src)
        return(True)

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

    def play(self, url, file):

        """Play a movie"""

        print("Playing {}".format(file))
        if self.cfg.useOmx():
            if not url:
                sub = file[0:-3] + "srt"
                if isfile(sub):
                    cmd = self.cfg.OMXCMD2.format(self.cfg.OUT, sub, file)
                else:
                    cmd = self.cfg.OMXCMD1.format(self.cfg.OUT, file)
            else:
                cmd = self.cfg.OMXCMD1.format(self.cfg.OUT, file)
        else:
            cmd = self.cfg.MPLRCMD.format(file)
        if DEBUG:
            print(cmd)
        system(cmd)
        return(True)

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

    def displayHelp(self):

        """Display help"""

        messagebox.showinfo("Help...", getHelp())
        return(True)

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

    def displayConfig(self):

        """Display Config Window"""

        self.cfg.display(self)
        self.askToRefreshDataBase()
        return(True)

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

    def playSelection(self):

        """Play selected files"""

        sel = self.ui_files.curselection()
        ps = playScreen()
        for i in sel:
            f = self.ui_files.get(i)
            self.play(False, self.files[f])
        ps.destroy()
        return(True)

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

    def playUrl(self, url):

        """Play selected url"""

        ps = playScreen()
        self.play(True, url)
        ps.destroy()
        return(True)

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

    def display(self):

        """Display the player"""

        self.createGui()
        self.cfg.toggleUrl(self)
        self.askToRefreshDataBase()
        self.root.mainloop()

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

    def askToRefreshDataBase(self):

        """Ask to refresh database"""

        msg = "Do you want to refresh the movies database ?"
        if messagebox.askokcancel("RasPyPlayer", msg):
            self.refreshDataBase()
        else:
            self.refreshFilesList()
        return(True)

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

    def refreshDataBase(self):

        """Refresh the movies database"""

        if isdir(self.cfg.PATH):
            self.scanDB()
            self.refreshFilesList()
            return(True)

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

    def refreshFilesList(self):

        """Refresh the list of files"""

        src = self.ui_srcentry.get()
        # Empty variables :
        self.files = {}
        if self.ui_files.size() > 0:
            self.ui_files.delete(0, END)
        # Get files in DB :
        if src == "" or src == "*":
            if DEBUG:
                print("Get ALL")
            self.loadAllMovies()
        else:
            if DEBUG:
                print("Get '{}'".format(src))
            self.loadSrcMovies(('%'+src+'%',))
        # Sort results :
        liste = list()
        for f, p in self.files.items():
            liste.append(f)
        liste.sort(key=str.lower)
        # Display result :
        for file in liste:
            self.ui_files.insert(END, file)
        return(True)

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

    def playUrl1(self):

        """Play URL 1"""

        self.playUrl(self.cfg.URL1)

    def playUrl2(self):

        """Play URL 2"""

        self.playUrl(self.cfg.URL2)

    def playUrl3(self):

        """Play URL 3"""

        self.playUrl(self.cfg.URL3)

    def playUrl4(self):

        """Play URL 4"""

        self.playUrl(self.cfg.URL4)

    def playUrl5(self):

        """Play URL 5"""

        self.playUrl(self.cfg.URL5)

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

    def evtPlay(self, evt):
        self.playSelection()

    def evtRefresh(self, evt):
        self.refreshFilesList()

    def evtScan(self, evt):
        self.askToRefreshDataBase()

    def evtCfg(self, cfg):
        self.displayConfig()

    def evtHelp(self, evt):
        self.displayHelp()

    def evtQuit(self, evt):
        self.stop()

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

    def createGui(self):

        """Create the GUI for Player"""

        print("*** Creating GUI ***")
        self.root.title("RasPyPlayer v{}".format(VERSION))
        font = Font(self.root, size=20, family='Sans')
        self.root.attributes('-fullscreen', True)

        # Top Frame (search group)
        self.ui_topframe = Frame(self.root, borderwidth=2)
        self.ui_topframe.pack({"side": "top"})
        # Label search
        self.ui_srclabel = Label(self.ui_topframe, text="Search:",
            font=font)
        self.ui_srclabel.grid(row=1, column=0, padx=2, pady=2)
        # Entry search
        self.ui_srcentry = Entry(self.ui_topframe, font=font)
        self.ui_srcentry.grid(row=1, column=1, padx=2, pady=2)
        self.ui_srcentry.bind("<Return>", self.evtRefresh)
        # Button search
        self.ui_srcexec = Button(self.ui_topframe, text="Search",
            command=self.refreshFilesList, font=font)
        self.ui_srcexec.grid(row=1, column=2, padx=2, pady=2)

        # Frame (contain Middle and Url frames)
        self.ui_frame = Frame(self.root, borderwidth=2)
        self.ui_frame.pack(fill=BOTH, expand=1)

        # Middle Frame (files group)
        self.ui_midframe = Frame(self.ui_frame, borderwidth=2)
        self.ui_midframe.pack({"side": "left"}, fill=BOTH, expand=1)
        # Files liste and scrollbar
        self.ui_files = Listbox(self.ui_midframe,
            selectmode=EXTENDED, font=font)
        self.ui_files.pack(side=LEFT, fill=BOTH, expand=1)
        self.ui_files.bind("<Return>", self.evtPlay)
        self.ui_filesscroll = Scrollbar(self.ui_midframe,
            command=self.ui_files.yview)
        self.ui_files.configure(yscrollcommand=self.ui_filesscroll.set)
        self.ui_filesscroll.pack(side=RIGHT, fill=Y)

        # Url Frame (url group)
        self.ui_urlframe = Frame(self.ui_frame, borderwidth=2)
        self.ui_urlframe.pack({"side": "right"})
        # Button Url 1
        self.ui_buturl1 = Button(self.ui_urlframe, textvariable=self.URL1L,
            command=self.playUrl1, font=font)
        self.ui_buturl1.grid(row=1, column=0, padx=2, pady=2)
        # Button Url 2
        self.ui_buturl2 = Button(self.ui_urlframe, textvariable=self.URL2L,
            command=self.playUrl2, font=font)
        self.ui_buturl2.grid(row=2, column=0, padx=2, pady=2)
        # Button Url 3
        self.ui_buturl3 = Button(self.ui_urlframe, textvariable=self.URL3L,
            command=self.playUrl3, font=font)
        self.ui_buturl3.grid(row=3, column=0, padx=2, pady=2)
        # Button Url 4
        self.ui_buturl4 = Button(self.ui_urlframe, textvariable=self.URL4L,
            command=self.playUrl4, font=font)
        self.ui_buturl4.grid(row=4, column=0, padx=2, pady=2)
        # Button Url 5
        self.ui_buturl5 = Button(self.ui_urlframe, textvariable=self.URL5L,
            command=self.playUrl5, font=font)
        self.ui_buturl5.grid(row=5, column=0, padx=2, pady=2)

        # Bottom Frame (buttons group)
        self.ui_botframe = Frame(self.root, borderwidth=2)
        self.ui_botframe.pack({"side": "left"})
        # Button Play
        self.ui_butplay = Button(self.ui_botframe, text="Play",
            command=self.playSelection, font=font)
        self.ui_butplay.grid(row=1, column=0, padx=2, pady=2)
        # Button Refresh
        self.ui_butscan = Button(self.ui_botframe, text="Scan",
            command=self.askToRefreshDataBase, font=font)
        self.ui_butscan.grid(row=1, column=1, padx=2, pady=2)
        # Button Config
        self.ui_butconf = Button(self.ui_botframe, text="Config",
            command=lambda : self.cfg.display(self), font=font)
        self.ui_butconf.grid(row=1, column=2, padx=2, pady=2)
        # Button Help
        self.ui_buthelp = Button(self.ui_botframe, text="Help",
            command=self.displayHelp, font=font)
        self.ui_buthelp.grid(row=1, column=3, padx=2, pady=2)
        # Button Quit
        self.ui_butquit = Button(self.ui_botframe, text="Quit",
            command=self.stop, font=font)
        self.ui_butquit.grid(row=1, column=4, padx=2, pady=2)

        # General bindings
        self.root.bind("<F1>", self.evtHelp)
        self.root.bind("<F2>", self.evtCfg)
        self.root.bind("<F3>", self.evtRefresh)
        self.root.bind("<F5>", self.evtScan)
        self.root.bind("<F12>", self.evtQuit)
        return(True)
Пример #38
0
class GUI(object):
    '''Stellt die Oberflaeche dar.
    
    Alle steuerden Taetigkeiten werden (sollten) vom
    Controller Objekt uebernommen werden.
    '''


    def __init__(self):
        '''
        Constructor
        '''
        self.root = Tk()
        
        self.root.title("DinnerLog")
        self.root.minsize(800, 600)
        self.root.grid_columnconfigure(0, weight=1)
        self.root.grid_rowconfigure(0, weight=1)
        self.root.grid_rowconfigure(1, weight=3)
        
        # Ein Frame für alles, das mit Zutaten zu tun hat
        self.fr_zutaten = Labelframe(self.root, borderwidth=2, relief=GROOVE, text="Zutaten")
        self.fr_zutaten.grid_columnconfigure(0, weight=1)
        self.fr_zutaten.grid_rowconfigure(0, weight=1)
        self.fr_zutaten.grid(row=0, column=0, sticky="NSWE")
        

        self.lb_zutaten = Listbox(self.fr_zutaten)
        sb_zutaten = Scrollbar(self.lb_zutaten, orient=VERTICAL)
        self.lb_zutaten.configure(yscrollcommand=sb_zutaten.set)
        sb_zutaten.config(command=self.lb_zutaten.yview)
        sb_zutaten.pack(side="right", fill="both")
        self.lb_zutaten.grid(row=0, column=0, sticky="NSEW")
        
        self._addNeueZutatFrame()    

        # Ein Frame in den alles, das mit Mahlzeiten zu tun hat, kommt
        self.fr_mahlzeit = Labelframe(self.root, borderwidth=2, relief=GROOVE, text="Mahlzeiten")
        self.fr_mahlzeit.grid_columnconfigure(0, weight=1)
        self.fr_mahlzeit.grid_rowconfigure(0, weight=1)
        self.fr_mahlzeit.grid(row=1, column=0, sticky="NSWE")
        
        self._addNeueMahlzeitFrame()
        

        self.lb_mahlzeiten = Listbox(self.fr_mahlzeit, selectmode=SINGLE)
        sb_mahlzeiten = Scrollbar(self.lb_mahlzeiten, orient=VERTICAL)
        sb_mahlzeiten.configure(command=self.lb_mahlzeiten.yview)
        self.lb_mahlzeiten.configure(yscrollcommand=sb_mahlzeiten.set)
        sb_mahlzeiten.pack(side="right", fill="both")
        self.lb_mahlzeiten.grid(row=0, column=0, sticky="NSEW")
        
        fr_neu_ok = Frame(self.fr_mahlzeit)
        fr_neu_ok.grid(row=1, column=0, columnspan=2, sticky="E")
    
        self.btn_neu = Button(fr_neu_ok, text="Neu")
        self.btn_neu.pack(side="left")
        
        self.btn_mahlzeit_als_zt = Button(fr_neu_ok, text="Als Zutat")
        self.btn_mahlzeit_als_zt.pack(anchor=E, side="right")
        
        self.btn_insert = Button(fr_neu_ok, text="Hinzufuegen")
        self.btn_insert.pack(anchor=E, side="right")
        
        self.btn_update = Button(fr_neu_ok, text="Update")
        self.btn_update.pack(anchor=E, side="right")
        
        self.btn_delete = Button(fr_neu_ok, text="Loeschen")
        self.btn_delete.pack(anchor=E, side="right")
        
        # Ein Frame der Statistiken darstellt
        self.fr_stats = Labelframe(self.root, borderwidth=2, relief=GROOVE, text="Statistik")
        self.fr_stats.grid(row=3, column=0, sticky="NSWE")

        #self.cv_stats = Canvas(self.fr_stats, height=80, width=600)
        #self.cv_stats.create_line(2,5,598,5, fill="#bbb")
        
    def _addNeueMahlzeitFrame(self):
        self.fr_neue_mz = Frame(self.fr_mahlzeit)
        self.fr_neue_mz.grid_rowconfigure(2, weight=1)
        self.fr_neue_mz.grid(row=0, column=1, sticky="WSNE")
        
        lbl_name = Label(self.fr_neue_mz, text="Name:")
        lbl_name.grid(row=0, column=0, sticky="NW")
        
        self.en_name = Entry(self.fr_neue_mz)
        self.en_name.grid(row=0, column=1, columnspan=2, sticky="WNE")
        
        lbl_zutat = Label(self.fr_neue_mz, text="Zutaten:")
        lbl_zutat.grid(row=1, column=0, sticky="NW")
        

        self.lb_zutat = Listbox(self.fr_neue_mz)
        sb_zutat = Scrollbar(self.lb_zutat, orient=VERTICAL)
        self.lb_zutat.configure(yscrollcommand=sb_zutat.set)
        sb_zutat.configure(command=self.lb_zutat.yview)
        sb_zutat.pack(side="right", fill="both")
        self.lb_zutat.grid(row=2, column=0, columnspan=3, sticky="NWSE")
        
        self.var_zutat = StringVar(self.fr_neue_mz)
        
        self.opt_zutat = OptionMenu(self.fr_neue_mz, self.var_zutat, "Auswahl")
        self.opt_zutat.grid(row=3, column=0)
        
        self.en_menge = Entry(self.fr_neue_mz)
        self.en_menge.grid(row=3, column=1)
        
        self.btn_mahlzeit_hinzu = Button(self.fr_neue_mz, text="Hinzu")
        self.btn_mahlzeit_hinzu.grid(row=3, column=2, sticky="E")
        
    def _addNeueZutatFrame(self):
        fr_neue_zt = Frame(self.fr_zutaten)
        fr_neue_zt.grid(row=0, column=2,sticky="NWSE")
        
        lbl_name = Label(fr_neue_zt, text="Name:")
        lbl_name.grid(row=0, column=0, sticky="W")
        
        self.en_name_zt = Entry(fr_neue_zt)
        self.en_name_zt.grid(row=0, column=1, columnspan=2, sticky="WE")
        
        lbl_fett = Label(fr_neue_zt, text="Fett:")
        lbl_fett.grid(row=1, column=0, sticky="W")        
        
        self.en_fett = Entry(fr_neue_zt)
        self.en_fett.grid(row=1, column=1, columnspan=2)
        
        lbl_eiweiss = Label(fr_neue_zt, text="Eiweiss:")
        lbl_eiweiss.grid(row=2, column=0, sticky="W")        
        
        self.en_eiweiss = Entry(fr_neue_zt)
        self.en_eiweiss.grid(row=2, column=1, columnspan=2)
        
        lbl_kh = Label(fr_neue_zt, text="Kohlenhy.:")
        lbl_kh.grid(row=3, column=0, sticky="W")        
        
        self.en_kh = Entry(fr_neue_zt)
        self.en_kh.grid(row=3, column=1, columnspan=2)
        
        self.btn_zutat_insert = Button(fr_neue_zt, text="Hinzu")
        self.btn_zutat_insert.grid(row=4, column=1, sticky="E")
        
        self.btn_zutat_update = Button(fr_neue_zt, text="Update")
        self.btn_zutat_update.grid(row=5, column=1, sticky="E")
        
        self.btn_zutat_delete = Button(fr_neue_zt, text="Loeschen")
        self.btn_zutat_delete.grid(row=6, column=1, sticky="E")