コード例 #1
0
class CustomSpinbox(Frame):
    def __init__(self,
                 master,
                 *args,
                 label="",
                 minimum=0,
                 maximum=9999,
                 **kwargs):
        super(CustomSpinbox, self).__init__(master, *args, **kwargs)
        self.minimum = minimum
        self.maximum = maximum if maximum > minimum else minimum + 1
        self.create_spinbox(label)
        self.register_filter()

    def create_spinbox(self, label):
        from tkinter import Label

        self.label = Label(self, text=label, width=LABEL_WIDTH)
        self.spinbox = Spinbox(self, from_=self.minimum, to=self.maximum)

        self.label.pack(side="left")
        self.spinbox.pack(side="left", fill="x", expand=True)

    def register_filter(self):
        tk = self.get_instance_tk(self)
        if tk:
            new_register = tk.register(self.filter_spinbox)
            self.spinbox.config(validate="key",
                                validatecommand=(new_register, "%P"))

    def filter_spinbox(self, value):
        if value.isdigit() and int(value) in range(self.minimum,
                                                   self.maximum + 1):
            return True
        if value == "":
            return True
        return False

    def get_instance_tk(self, widget):
        from tkinter import Tk

        if isinstance(widget, Tk):
            return widget
        else:
            master = self.get_instance_tk(widget.master)
            return master

    def set_label(self, label):
        self.label.config(text=label)

    def get_value(self):
        return int(self.spinbox.get())

    def set_value(self, value):
        if value in range(self.minimum, self.maximum + 1):
            self.spinbox.delete(0, "end")
            self.spinbox.insert("end", str(value))
コード例 #2
0
ファイル: sorter.py プロジェクト: Cryden13/AnimeSorter
    def fillInfo(self, curRow: int, path: Path, name: str = None) -> None:
        rowLbl = zerofrmt(curRow)
        bg = self.litBg if (curRow % 2) else self.defBg
        # create container
        frm = Frame(master=self.scrFrm,
                    bg=bg,
                    relief='sunken',
                    bd=1)
        frm.columnconfigure(1, weight=1)
        frm.grid(column=0,
                 row=curRow,
                 sticky='ew')
        # create spinbox
        sbox = Spinbox(master=frm,
                       width=3,
                       bg=bg,
                       format=(f'%0{rndto}d' if rndto > 1 else ''),
                       takefocus=False,
                       from_=1,
                       to=self.lblRow,
                       increment=-1,
                       repeatdelay=(10**5),
                       validate='key',
                       validatecommand=self.checkValid)
        sbox.grid(column=0,
                  row=0)

        def btnpress(f=frm, s=sbox): self.updateList(f, s, True)
        def commit(_, f=frm, s=sbox): self.updateList(f, s)
        def cancel(_, f=frm, s=sbox): self.cancelChange(f, s)

        sbox.configure(command=btnpress)
        sbox.delete(0, 'end')
        if name:
            sbox.insert(0, rowLbl)
        else:
            name = path.name
        sbox.bind('<Return>', commit)
        sbox.bind('<Escape>', cancel)
        # create name label
        lbl = Label(master=frm,
                    text=name,
                    bg=bg)
        lbl.grid(column=1,
                 row=0,
                 sticky='w')
        # save to data dict
        self.data[rowLbl] = dict(frm=frm,
                                 sbox=sbox,
                                 lbl=lbl,
                                 path=path,
                                 name=name)
コード例 #3
0
class TimeChooser(Frame):
    '''
    classdocs
    '''
    def __init__(self, parent, initialTime=None):
        super().__init__(parent)

        if initialTime is None:
            initialTime = datetime.now().time()

        self.hour = Spinbox(self, from_=1, to=12, width=3)
        self.hour.grid(column=0, row=0)
        Label(self, text=":").grid(column=1, row=0)
        self.minute = Spinbox(self, from_=00, to=59, format="%02.0f", width=3)
        self.minute.grid(column=2, row=0)
        self.ampm = Spinbox(self, values=("AM", "PM"), width=4)
        self.ampm.grid(column=3, row=0)

        # set AM/PM
        self.ampm.delete(0, "end")
        self.ampm.insert(0, "AM" if initialTime.hour < 12 else "PM")

        # set hour, 12-hour display
        self.hour.delete(0, "end")
        if initialTime.hour == 0:
            self.hour.insert(0, "12")
        elif initialTime.hour <= 12:
            self.hour.insert(0, str(initialTime.hour))
        else:
            self.hour.insert(0, str(initialTime.hour - 12))

        # set minute
        self.minute.delete(0, "end")
        self.minute.insert(0, "{:0>2d}".format(initialTime.minute))

        # readonly the entry widgets
        self.hour.config(state="readonly")
        self.minute.config(state="readonly")
        self.ampm.config(state="readonly")

    def getTime(self):
        hour = int(self.hour.get())
        if self.ampm.get() == "AM":
            hour %= 12
        elif hour < 12:
            hour += 12

        return time(hour=int(hour), minute=int(self.minute.get()))
コード例 #4
0
ファイル: sorter.py プロジェクト: Cryden13/AnimeSorter
 def updateList(self, frm: Frame, sbox: Spinbox, btn: bool = False) -> None:
     # get data
     start = frm.grid_info()['row']
     oldInfo = self.data.pop(zerofrmt(start))
     # get spinbox value
     moveToLbl = str(sbox.get())
     if moveToLbl == zerofrmt(start):
         return
     elif not moveToLbl:
         if start < self.lblRow:
             start = (self.lblRow + 1)
             moveToLbl = zerofrmt(self.lastRow)
             self.focus_set()
         else:
             return
     elif btn and int(moveToLbl) == self.lblRow:
         sbox.delete(0, 'end')
         start = (self.lblRow + 1)
         moveToLbl = zerofrmt(self.lastRow)
         self.after(0, self.focus_set)
     elif btn and abs(start - int(moveToLbl)) > 1:
         self.moveInterim(start, zerofrmt(self.lblRow + 1), True)
         start = 0
         moveToLbl = zerofrmt(self.maxRow)
         sbox.delete(0, 'end')
         sbox.insert(0, moveToLbl)
     elif not btn:
         if len(moveToLbl) != rndto:
             moveToLbl = zerofrmt(moveToLbl)
             sbox.delete(0, 'end')
             sbox.insert(0, moveToLbl)
         if start == self.lastRow:
             self.moveInterim(start, zerofrmt(self.lblRow + 1), True)
     sbox.selection_range(0, 'end')
     if moveToLbl == zerofrmt(start):
         return
     if moveToLbl in self.data:
         self.moveInterim(start, moveToLbl, False)
     moveToRow = int(moveToLbl)
     bg = self.litBg if (moveToRow % 2) else self.defBg
     frm.grid(row=moveToRow)
     frm.configure(bg=bg)
     sbox.configure(bg=bg)
     oldInfo['lbl'].configure(bg=bg)
     self.data[moveToLbl] = oldInfo
コード例 #5
0
    def add_reminder(self, date=None):
        def remove():
            self.alarms.remove((when, what))
            rem.destroy()

        rem = Frame(self.frame_alarms)
        frame_when = Frame(rem, style='txt.TFrame', relief='sunken', border=1)
        when = Spinbox(frame_when,
                       from_=0,
                       to=59,
                       width=3,
                       justify='center',
                       relief='flat',
                       highlightthickness=0,
                       validate='key',
                       validatecommand=(self._only_nb, '%P'))
        when.pack()
        when.delete(0, 'end')
        what = Combobox(rem,
                        width=8,
                        state='readonly',
                        values=(_('minutes'), _('hours'), _('days')))

        if date:
            hour = int(self.start_hour.get())
            minute = int(self.start_min.get())
            dt = datetime.combine(self.start_entry.get_date(),
                                  time(hour=hour, minute=minute)) - date
            if dt.days > 0:
                when.insert(0, str(dt.days))
                what.set(_('days'))
            else:
                h, m, s = str(dt).split(':')
                if h != "0":
                    when.insert(0, h)
                    what.set(_('hours'))
                else:
                    when.insert(0, str(int(m)))
                    what.set(_('minutes'))
        else:
            when.insert(0, '15')
            what.set(_('minutes'))

        self.alarms.append((when, what))

        Label(rem, text=_('Reminder:')).pack(side='left', padx=4, pady=4)
        frame_when.pack(side='left', pady=4, padx=4)
        what.pack(side='left', pady=4, padx=4)
        Button(rem, image=self.img_moins, padding=0,
               command=remove).pack(side='left', padx=4, pady=4)
        rem.pack()
コード例 #6
0
class CompetitorRegistrationWindow(Toplevel):
    def __init__(self, parent, db, *args, **kwargs):
        Toplevel.__init__(self, *args, **kwargs)
        self.parent = parent
        self.db = db
        self.title('Register new competitor...')
        self.hr1 = Frame(self, height=1, width=500, bg="gray")  # creates a gray line under the registration

        self.fnameLabel = Label(self, text='First:')
        self.lnameLabel = Label(self, text='Last:')
        self.levelLabel = Label(self, text='Level:')
        self.sexLabel = Label(self, text='Sex:')
        self.ageLabel = Label(self, text='Age:')

        self.sexValue = StringVar()
        self.sexValue.set('M')

        self.levelValues = ('Beginner', 'Intermediate', 'Advanced', 'Open')

        self.fnameEntry = EntryWithPlaceholder(self, placeholder='John', width=30)
        self.lnameEntry = EntryWithPlaceholder(self, placeholder='Doe', width=30)
        self.levelEntry = Spinbox(self, values=self.levelValues)
        self.sexEntryM = Radiobutton(self, text='M', variable=self.sexValue, value='M')
        self.sexEntryF = Radiobutton(self, text='F', variable=self.sexValue, value='F')
        self.ageEntry = Spinbox(self, from_=1, to=100, width=6)
        self.registerButton = Button(self, text='Register', command=self.register_competitor)

        self.ageEntry.delete('0', 'end')
        self.ageEntry.insert(0, 20)

        self.fnameEntry.bind('<Return>', self.register_competitor)  # these bind all the entries to <return>
        self.lnameEntry.bind('<Return>', self.register_competitor)  # meaning that hitting enter while within any of
        self.levelEntry.bind('<Return>', self.register_competitor)  # of them will submit the form to the
        self.sexEntryF.bind('<Return>', self.register_competitor)  # register_competitor function
        self.sexEntryM.bind('<Return>', self.register_competitor)
        self.ageEntry.bind('<Return>', self.register_competitor)
        self.registerButton.bind('<Return>', self.register_competitor)

        self.fnameLabel.grid(row=1, column=0)
        self.fnameEntry.grid(row=1, column=1, columnspan=4)
        self.lnameLabel.grid(row=1, column=5)
        self.lnameEntry.grid(row=1, column=6, columnspan=4)
        self.levelLabel.grid(row=2, column=0)
        self.levelEntry.grid(row=2, column=1, columnspan=2)
        self.sexLabel.grid(row=2, column=3)
        self.sexEntryM.grid(row=2, column=4)
        self.sexEntryF.grid(row=2, column=5)
        self.ageLabel.grid(row=2, column=6)
        self.ageEntry.grid(row=2, column=7)
        self.registerButton.grid(row=2, column=8)

    def register_competitor(self, *args):
        self.db.insert_row((self.fnameEntry.get(),
                            self.lnameEntry.get(),
                            self.levelEntry.get(),
                            self.sexValue.get(),
                            self.ageEntry.get(),
                            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))
        self.clear_registration()
        self.fnameEntry.focus_set()

    def clear_registration(self):
        self.fnameEntry.replace_placeholder()
        self.lnameEntry.replace_placeholder()
        self.levelEntry.setvar(self.levelValues[0], value='1')
        self.sexValue.set('M')
        self.ageEntry.delete(0, 'end')
        self.ageEntry.insert(0, 20)
コード例 #7
0
class Editor:

    # Info Defaults
    LOG_FILE = 'editor.log'

    devices = []
    vidPK = []
    vidPATH = []
    vidNAME = []
    uuid = []
    uuidFK = []

    def __init__(self, master, soundGenerator, rfidScanner):
        self.environment = Environment()
        self.soundProvider = SoundProvider(soundGenerator)
        self.configureScannerProvider(rfidScanner)
        self.load()
        frame = Frame(master)
        frame.pack()
        self.activeCardNumber = StringVar()
        self.usbSpin = StringVar()
        self.usbSpin.set(self.environment.Usb)
        Label(frame, text='RFID Card').grid(row=0, column=0)
        Label(frame, text='Video').grid(row=0, column=2)
        self.ee = Entry(frame, textvariable=self.activeCardNumber,
                        state=DISABLED, disabledforeground='black')
        self.ee.grid(row=1, column=0)
        self.r = Button(frame, text='Read Card', command=self.startCardProcess)
        self.r.grid(row=1, column=1)
        self.box = Listbox(frame)
        for entry in self.vidNAME:
            self.box.insert(END, entry)
        self.box.bind("<<ListboxSelect>>", self.newselection)
        self.box.grid(row=1, rowspan=5, column=2, columnspan=2)
        self.scroll = Scrollbar(self.box, orient=VERTICAL)
        self.box.config(yscrollcommand=self.scroll.set)
        self.scroll.config(command=self.box.yview)
        Button(frame, text='Assign Kill Code',
               command=self.createKiller).grid(row=2, column=0)
        Label(frame, text='Source USB').grid(row=4, column=0)
        self.spin = Spinbox(frame, values=self.devices)
        self.spin.delete(0, END)
        self.spin.insert(0, self.environment.Usb)
        self.spin.grid(row=5, column=0)
        self.status = Button(frame, text='Update Device Repository',
                             command=self.updateDevice, disabledforeground='blue')
        self.status.grid(row=6, column=0)
        Button(frame, text='Save', command=self.save).grid(row=6, column=2)
        Button(frame, text='Quit', command=self.closeWithSavePrompt).grid(
            row=6, column=3)
    
    def configureScannerProvider(self, rfidScanner):
        provider = RFIDScannerProvider(rfidScanner)
        self.RFIDScannerProvider = provider.PN532(
            int(self.environment.CHIP_SELECT_PIN),
            int(self.environment.MASTER_OUTPUT_SLAVE_INPUT_PIN),
            int(self.environment.MASTER_INPUT_SLAVE_OUTPUT_PIN),
            int(self.environment.SERIAL_CLOCK_PIN))

    def closeWithSavePrompt(self):
        ans = messagebox.askquestion(
            'Save And Quit', 'Would you like to save your changes?')
        if ans == 'yes':
            self.save()
        sys.exit(0)

    def startCardProcess(self):
        # Disable button to prevent event stacking
        self.r.config(state=DISABLED)
        self.processCard()
        self.r.config(state=NORMAL)

    def processCard(self):
        # Scans RFID cards and sets them to text box
        try:
            self.processCardUnchecked()
        except Exception as e:
            self.displayScanError(e)

    def processCardUnchecked(self):
        cardScan = CardScanWrapper(self.soundS, self.RFIDScannerProvider)
        cardScan.runScan()
        self.processResult(cardScan.getFormattedResult())

    def processResult(self, scanResult):
        if scanResult == None:
            return
        self.activeCardNumber.set(scanResult)     # Populate text box
        self.deselectActiveListboxItems()
        self.linkCardWithListbox(scanResult)

    def deselectActiveListboxItems(self):
        # De-select any active items in listbox
        self.box.selection_clear(0, END)

    def linkCardWithListbox(self, scanResult):
        index = self.verifyCard(scanResult)
        if str(self.uuidFK[index]) == self.environment.KillCommand:
            messagebox.showinfo(
                'Kill Card', 'This card is currently assigned to kill the application.')
            return
        self.highlightItemInListbox(index)

    def highlightItemInListbox(self, index):
        try:
            i = self.vidPK.index(self.uuidFK[index])
        except:
            messagebox.showinfo('Card Unassigned',
                                'Card is not currently assigned to a video')
        else:
            self.box.see(i)
            self.box.selection_clear(0, END)
            self.box.selection_set(i)
            self.box.activate(i)

    def verifyCard(self, uidt):
        try:
            uuidIndex = self.uuid.index(uidt)
        except:
            uuidIndex = self.addNewCard(uidt)
        return uuidIndex

    def addNewCard(self, uidt):
        self.uuid.append(uidt)
        self.uuidFK.append(-1)
        newIndex = len(self.uuid) - 1
        return newIndex

    def displayScanError(self, e):
        messagebox.showerror('Error Occurred', 'Error: ' + str(e))
        logging.error('Scan Failed: ' + str(e))

    def save(self):
        toSaveList = self.makePairedList(
            self.vidPK, self.vidNAME, self.vidPATH)
        self.safeSaveToFile(self.environment.VideoList, toSaveList)
        toSaveList = self.makePairedList(self.uuid, self.uuidFK)
        self.safeSaveToFile(self.environment.UuidTable, toSaveList)

    def makePairedList(self, *itemLists):
        stop = len(itemLists)
        subList = []
        listAll = []
        for listIndex in range(len(itemLists[0])):
            del subList[:]
            for indice in range(stop):
                subList.append(itemLists[indice][listIndex])
            listAll.append(list(subList))
        return listAll

    def safeSaveToFile(self, fileName, pairList):
        try:
            self.writePairedListToTempFile(fileName, pairList)
        except Exception as e:
            logging.error('Failed to create video list: ' + str(e))
        else:
            self.replaceOriginalFileWithItsTemp(fileName)

    def replaceOriginalFileWithItsTemp(self, fileName):
        try:
            if os.path.isfile(fileName):
                os.remove(fileName)
            os.rename(fileName + '.temp', fileName)
        except Exception as e:
            logging.error('Failed to replace old video list: ' + str(e))

    def writePairedListToTempFile(self, fileName, pairedList):
        f = open(fileName + '.temp', 'w')
        self.writePairedListGivenFile(f, pairedList)
        f.close()

    def writePairedListGivenFile(self, f, pairedList):
        i = 0
        while(i < len(pairedList) - 1):
            self.writeSingleLineOfPairedListToOpenFile(f, pairedList, i)
            f.write('\n')
            i = i+1
        self.writeSingleLineOfPairedListToOpenFile(f, pairedList, i)

    def writeSingleLineOfPairedListToOpenFile(self, f, pairedList, itemIndex):
        fLine = ""
        for item in range(len(pairedList[itemIndex])):
            fLine = fLine + str(pairedList[itemIndex][item]) + ','
        f.write(fLine[:-1])

    def updateDevice(self):
        scan = self.safeScan()
        if scan != None:
            self.safeProcessScan(scan)
        self.status.config(text='Update Device Repository', state=NORMAL)
        self.status.update_idletasks()

    def safeScan(self):
        scan = None
        try:
            scan = self.runScannerWithNotification()
        except Exception as e:
            self.showScanErrorMessage(e)
        return scan

    def runScannerWithNotification(self):
        self.status.config(text='Scanning...', state=DISABLED)
        self.status.update_idletasks()
        scan = ScriptedFileSearch(subprocess)
        scan.scan("scanner.sh")
        return scan

    def showScanErrorMessage(self, e):
        messagebox.showerror('Scan Failed', 'Scan error: ' + str(e))
        logging.error(str(e))

    def safeProcessScan(self, scan):
        try:
            self.processScan(scan)
        except Exception as e:
            self.showErrorMessage(e)

    def showErrorMessage(self, e):
        messagebox.showerror('Error', 'Error: ' + str(e))
        logging.error(str(e))

    def refreshListBox(self):
        self.box.delete(0, END)
        for entry in self.vidNAME:
            self.box.insert(END, entry)

    def processScan(self, scan):
        # Check if a scan turned up any results
        if self.scanIsEmpty(scan):
            self.showAbortScanMessage()
            return
        self.verifyUSB()
        self.processScanFiles(scan)
        self.refreshListBox()

    def showAbortScanMessage(self):
        messagebox.showwarning(
            'No Files Found', 'A scan failed to find any files.')
        logging.warning('Empty Scan occurred when attempting a merge')

    def scanIsEmpty(self, scan):
        return len(scan.NAME) == 0

    def verifyUSB(self):
        if self.environment.Usb != self.spin.get():
            self.Usb = self.spin.get()
            self.environment.update()

    def processScanFiles(self, scan):
        i = 0
        j = 0
        newPK = []
        newName = []
        newPath = []
        self.status.config(text='Reading Files...')
        self.status.update_idletasks()
        # Iterate through list
        while i < len(scan.NAME):
            # Verifiy File
            try:
                if scan.PATH[i].find(self.environment.Usb) >= 0:
                    # File resides on repository - update FK
                    try:
                        # Locate matching entry
                        fkk = self.vidNAME.index(scan.NAME[i])
                    except Exception as e:
                        # No matching entry
                        logging.info('New file found in repository: ' + str(e))
                        pass
                    else:
                        # Update FK on uuid table
                        for uu in self.uuidFK:
                            if uu == self.vidPK[fkk]:
                                uu = scan.PK[i]
                    # Store entry in new Tables
                    newPK.append(scan.PK[i])
                    newName.append(scan.NAME[i])
                    newPath.append(scan.PATH[i])
                else:
                    # Video resides on updating device - check if file already copied
                    found = False
                    while j < len(scan.NAME):
                        if str(scan.NAME[i]) == str(scan.NAME[j]) and scan.PATH[j].find(self.environment.Usb) >= 0:
                            found = True
                            break
                        j = j + 1
                    if not found:
                        # Copy file and append
                        try:
                            # Get device name
                            device = scan.PATH[i].replace('/media/pi/', '')
                            device = device[0:device.find('/')]
                            # Copy
                            self.status.config(
                                text='Copying ' + scan.NAME[i] + '...')
                            self.status.update_idletasks()
                            shutil.copyfile(
                                scan.PATH[i], scan.PATH[i].replace(device, self.environment.Usb))
                        except Exception as e:
                            logging.error('Failed to copy' +
                                          scan.NAME[i] + ': ' + str(e))
                        else:
                            # Add to new array
                            newPK.append(scan.PK[i])
                            newName.append(scan.NAME[i])
                            newPath.append(
                                scan.PATH[i].replace(device, self.environment.Usb))
            except Exception as e:
                logging.error(str(e))
            i = i+1
        del self.vidNAME[:]
        del self.vidPATH[:]
        del self.vidPK[:]
        self.vidNAME = newName
        self.vidPATH = newPath
        self.vidPK = newPK

    def newselection(self, event):
        # Fires when a new item is selected in the listbox
        selection = event.widget.curselection()
        try:
            txt = self.ee.get()
            if txt == '':
                return
            i = self.uuid.index(txt)
            self.uuidFK[i] = self.vidPK[selection[0]]
        except Exception as e:
            messagebox.showerror('Error During Set', 'Error: ' + str(e))
            logging.error(str(e))

    def createKiller(self):
        try:
            self.assignCurrentCardAsKiller()
            self.box.selection_clear(0, END)
        except Exception as e:
            self.handleCardNotScannedError(e)

    def assignCurrentCardAsKiller(self):
        i = self.uuid.index(self.ee.get())
        self.uuidFK[i] = int(self.environment.KillCommand)

    def handleCardNotScannedError(self, e):
        messagebox.showinfo(
            'Card Not Scanned', 'Please scan a card to assign it a [Kill Application] code.' + str(e))
        logging.error(str(e))

    def load(self):
        # Generate Log
        logging.basicConfig(filename=self.LOG_FILE, level=logging.INFO)
        # Load Sound file
        self.soundProvider.init()
        self.soundProvider.mixer.pre_init(44100, -16, 12, 512)
        # pygame.init() IS this only for linux distribution?
        self.soundS = self.soundProvider.mixer.Sound(self.environment.SCAN_SOUND)
        self.soundS.set_volume(1)
        # Create an instance of the PN532 class.
        self.RFIDScannerProvider.begin())
        # Configure PN532 to communicate with MiFare cards.
        self.RFIDScannerProvider.SAM_configuration()
        self.loadFiles()
        self.locateDevices()
        self.loadDevice()

    def loadFiles(self):
        self.readCSV(self.environment.VideoList, (int, self.vidPK),
                     (str, self.vidNAME), (str, self.vidPATH))
        self.readCSV(self.environment.UuidTable,
                     (str, self.uuid), (int, self.uuidFK))
コード例 #8
0
ファイル: objRenderer.py プロジェクト: AronZajic/ObjRenderer
    for i in range(len(v)):
        v[i] = multiply(
            mat4([[1, 0, 0, float(tx.get())], [0, 1, 0,
                                               float(ty.get())],
                  [0, 0, 1, float(tz.get())], [0, 0, 0, 1]]), v[i])

    for f in faces:
        f.drawFace()


trasnlate = Button(root, text="Trasnlate", command=trasnlate)
trasnlate.place(x=windowX + 5, y=160)

sx = Spinbox(root, from_=0, to=2, increment=0.1, width=3)
sx.insert(1, "1")
sx.place(x=windowX + 85, y=85)
sy = Spinbox(root, from_=0, to=2, increment=0.1, width=3)
sy.insert(1, "1")
sy.place(x=windowX + 130, y=85)
sz = Spinbox(root, from_=0, to=2, increment=0.1, width=3)
sz.insert(1, "1")
sz.place(x=windowX + 175, y=85)


def scale():

    canvas.delete("all")
    canvas.create_rectangle(windowX,
                            0,
                            windowX + 250,
コード例 #9
0
class CompetitorInfoFrame(Frame):
    def __init__(self, parent, db, *args, **kwargs):
        Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        self.db = db

        self.titleFont = ['Arial', -0.03, 'bold']
        self.infoFont = ['Arial', -0.02, 'bold']
        self.routesAndAttemptsFont = ['Din', -0.05, 'bold']
        self.routesAndAttemptsSeparatorFont = ['Din', -0.03]
        self.titleFont[1] = round(self.titleFont[1] * self.parent.parent.SCREEN_HEIGHT)
        self.infoFont[1] = round(self.infoFont[1] * self.parent.parent.SCREEN_HEIGHT)
        self.routesAndAttemptsFont[1] = round(self.routesAndAttemptsFont[1] * self.parent.parent.SCREEN_HEIGHT)
        self.routesAndAttemptsSeparatorFont[1] = round(self.routesAndAttemptsSeparatorFont[1] * self.parent.parent.SCREEN_HEIGHT)

        self.labelbg = LBLUE
        self.labelfg = 'white'
        self.entrybg = LLBLUE
        self.entryfg = 'black'
        self.entrydisabledbg = LBLUE

        self.sexValue = StringVar()
        self.idValue = IntVar()
        self.levelValues = ('Beginner', 'Intermediate', 'Advanced', 'Open')

        self.routeListingFrame = Frame(self, bg=self.labelbg)
        self.ageAndSexFrame = Frame(self, bg=self.labelbg)

        self.idValueLabel = Label(self, textvariable=self.idValue, bg=self.labelbg, fg=self.labelfg, font=self.infoFont, anchor='w', bd=1, relief='sunken')
        self.idLabel = Label(self, text='ID: ', bg=self.labelbg, fg=self.labelfg, font=self.infoFont, anchor='w')
        self.frameTitleLabel = Label(self, text="COMPETITOR INFO", bg=self.labelbg, fg=self.labelfg, font=self.titleFont)
        self.fnameLabel = Label(self, text='FIRST:', bg=self.labelbg, fg=self.labelfg, font=self.infoFont, anchor='w')
        self.lnameLabel = Label(self, text='LAST:', bg=self.labelbg, fg=self.labelfg, font=self.infoFont, anchor='w')
        self.levelLabel = Label(self, text='LEVEL:', bg=self.labelbg, fg=self.labelfg, font=self.infoFont, anchor='w')
        self.sexLabel = Label(self.ageAndSexFrame, text='SEX:', bg=self.labelbg, fg=self.labelfg, font=self.infoFont, anchor='w')
        self.ageLabel = Label(self.ageAndSexFrame, text='AGE:', bg=self.labelbg, fg=self.labelfg, font=self.infoFont, anchor='w')
        self.routesLabel = Label(self.routeListingFrame, text='ROUTES:', bg=self.labelbg, fg=self.labelfg, font=self.infoFont, anchor='w')
        self.attemptsLabel = Label(self.routeListingFrame, text='ATTEMPTS:', bg=self.labelbg, fg=self.labelfg, font=self.infoFont, anchor='w')

        self.fnameEntry = Entry(self, width=30, fg=self.entryfg, bg=self.entrybg, disabledbackground=self.entrydisabledbg, font=self.infoFont)
        self.lnameEntry = Entry(self, width=30, fg=self.entryfg, bg=self.entrybg, disabledbackground=self.entrydisabledbg, font=self.infoFont)
        self.levelEntry = Spinbox(self, values=self.levelValues, width=28, fg=self.entryfg, bg=self.entrybg, disabledbackground=self.entrydisabledbg, font=self.infoFont)
        self.sexEntryM = Radiobutton(self.ageAndSexFrame, text='M', variable=self.sexValue, value='M', fg=self.entryfg, bg=self.labelbg, font=self.infoFont)
        self.sexEntryF = Radiobutton(self.ageAndSexFrame, text='F', variable=self.sexValue, value='F', fg=self.entryfg, bg=self.labelbg, font=self.infoFont)
        self.ageEntry = Spinbox(self.ageAndSexFrame, from_=1, to=100, width=10, fg=self.entryfg, bg=self.entrybg, disabledbackground=self.entrydisabledbg, font=self.infoFont)
        self.routeEntries = [Entry(self.routeListingFrame, width=3, fg=self.entryfg, bg=self.entrybg, disabledbackground=self.entrydisabledbg, font=self.routesAndAttemptsFont) for _ in range(5)]
        self.attemptEntries = [Entry(self.routeListingFrame, width=3, fg=self.entryfg, bg=self.entrybg, disabledbackground=self.entrydisabledbg, font=self.routesAndAttemptsFont) for _ in range(5)]

        self.updateButton = Button(self, text='Update Competitor', command=self.update_competitor, bg=DBLUE, fg='white', font=self.infoFont)

        self.frameTitleLabel.grid(sticky='nsew', row=0, column=0, columnspan=2)
        self.idLabel.grid(sticky='nsew', row=1, column=0, padx=10)
        self.idValueLabel.grid(sticky='nsew', row=1, column=1, padx=10)
        self.fnameLabel.grid(sticky='nsew', row=2, column=0, padx=10)
        self.fnameEntry.grid(sticky='nsew', row=2, column=1, padx=10)
        self.lnameLabel.grid(sticky='nsew', row=3, column=0, padx=10)
        self.lnameEntry.grid(sticky='nsew', row=3, column=1, padx=10)
        self.levelLabel.grid(sticky='nsew', row=4, column=0, padx=10)
        self.levelEntry.grid(sticky='nsew', row=4, column=1, padx=10)

        self.ageAndSexFrame.grid(sticky='nsew', row=5, column=1)
        self.sexLabel.grid(sticky='nsew', row=0, column=0)
        self.sexEntryM.grid(sticky='nsew', row=0, column=1)
        self.sexEntryF.grid(sticky='nsew', row=0, column=2)
        self.ageLabel.grid(sticky='nsew', row=0, column=3)
        self.ageEntry.grid(sticky='nsew', row=0, column=4, padx=10)

        self.routeListingFrame.grid(sticky='nsew', row=6, column=0, columnspan=2, padx=10)
        self.routesLabel.grid(sticky='nsew', row=0, column=0)
        for i, entry in enumerate(self.routeEntries):
            lb = Label(self.routeListingFrame, text=i+1, fg='white', bg=DDBLUE, font=self.routesAndAttemptsSeparatorFont)
            lb.grid(column=2*i+1, row=0, rowspan=2, sticky='nsew')
            entry.grid(sticky='nsew', row=0, column=2*i+2)
            entry.bind('<FocusOut>', self.update_to_route_buttons)
            self.routeListingFrame.columnconfigure(2*i+1, weight=1)
            self.routeListingFrame.columnconfigure(2*i+2, weight=3)
        self.attemptsLabel.grid(sticky='nsew', row=1, column=0)
        for i, entry in enumerate(self.attemptEntries):
            entry.grid(sticky='nsew', row=1, column=2*i+2)
            entry.bind('<FocusOut>', self.update_to_route_buttons)

        self.updateButton.grid(row=7, column=0, columnspan=2, sticky='nsew', pady=10, padx=10)

        self.rowconfigure(0, weight=2)  # title
        self.rowconfigure(1, weight=1)  # id entry
        self.rowconfigure(2, weight=1)  # fname entry
        self.rowconfigure(3, weight=1)  # lname entry
        self.rowconfigure(4, weight=1)  # level entry
        self.rowconfigure(5, weight=1)  # age and sex entry
        self.rowconfigure(6, weight=3)  # route and attempt entry frame
        self.rowconfigure(7, weight=1)  # update button
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=4)

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

        for i in range(0, 5):
            self.ageAndSexFrame.columnconfigure(i, weight=1)
        self.ageAndSexFrame.rowconfigure(0, weight=1)

        taborder = []
        for i in range(0, 5):
            taborder.append(self.routeEntries[i])
            taborder.append(self.attemptEntries[i])

        for widget in taborder:
            widget.lift()

        disable_frame(self.parent)

    def fill_competitor(self, id):
        row = self.db.get_row(id)  # get_row
        self.clear_competitor()
        self.idValue.set(id)
        self.fnameEntry.insert(0, row[1])
        self.lnameEntry.insert(0, row[2])
        self.levelEntry.insert(0, row[3])
        self.sexValue.set(row[4])
        self.ageEntry.insert(0, row[5])
        # need score thing here for row[6]?
        for i in range(0, 5):
            if row[i+7] != 0:  # checks if is there a route in the database row
                self.routeEntries[i].insert(0, row[i+7])
                self.attemptEntries[i].insert(0, row[i+12])
                self.parent.routeAttemptsEntryFrame.routes[row[i+7] - 1].attemptsAmt.set(row[i+12])
                self.parent.routeAttemptsEntryFrame.routes[row[i+7] - 1].activate()

    def clear_competitor(self):
        self.idValue.set(0)
        self.fnameEntry.delete(0, 'end')
        self.lnameEntry.delete(0, 'end')
        self.levelEntry.delete(0, 'end')
        self.ageEntry.delete(0, 'end')
        for entry in self.routeEntries:
            entry.delete(0, 'end')
        for entry in self.attemptEntries:
            entry.delete(0, 'end')

    def validate_entries(self):
        for i in range(0, 5):
            if not(range(1, 51).__contains__(mk_int(self.routeEntries[i].get()))):
                self.routeEntries[i].delete(0, 'end')
                self.attemptEntries[i].delete(0, 'end')
            else:
                for widget in self.routeEntries[0:i]:
                    if widget.get() == self.routeEntries[i].get():
                        self.routeEntries[i].delete(0, 'end')
                        self.attemptEntries[i].delete(0, 'end')

            if not(range(1, 101).__contains__(mk_int(self.attemptEntries[i].get()))):
                # self.routeEntries[i].delete(0, 'end')
                self.attemptEntries[i].delete(0, 'end')

    def get_entered_values(self):
        self.validate_entries()
        entered = [0 for _ in range(0, 10)]  # Route id's take first five spots, attempts take next 5
        for i in range(0, 5):
            entered[i] = mk_int(self.routeEntries[i].get())
            entered[i+5] = mk_int(self.attemptEntries[i].get())
        return entered

    def update_to_route_buttons(self, *args):
        entered = self.get_entered_values()
        self.parent.routeAttemptsEntryFrame.update_from_info_entries(entered)

    def update_from_route_buttons(self):
        selected = self.parent.routeAttemptsEntryFrame.get_selected_routes()
        for i in range(0, 5):
            self.routeEntries[i].delete(0, 'end')
            self.attemptEntries[i].delete(0, 'end')
        for i, route in enumerate(selected):
            self.routeEntries[i].insert(0, route.num)
            self.attemptEntries[i].insert(0, route.attemptsAmt.get())

    def update_competitor(self):
        routevalues = []
        attemptvalues = []
        for entry in self.routeEntries:
            if entry.get() == '':
                routevalues.append(0)
            else:
                routevalues.append(entry.get())
        for entry in self.attemptEntries:
            if entry.get() == '':
                attemptvalues.append(0)
            else:
                attemptvalues.append(entry.get())  # these two for loops prevent passing empty strings to the database
        
        row = (self.fnameEntry.get(), self.lnameEntry.get(), self.levelEntry.get(), self.sexValue.get(),
               self.ageEntry.get(), self.calc_score(), routevalues[0], routevalues[1], routevalues[2],
               routevalues[3], routevalues[4], attemptvalues[0], attemptvalues[1], attemptvalues[2],
               attemptvalues[3], attemptvalues[4])
        self.db.update_row(self.idValue.get(), row)  # loads info to database
        self.clear_competitor()  # clears competitor info in entries
        self.parent.routeAttemptsEntryFrame.reset()  # resets route entries back to gray state with no values
        disable_frame(self)  # disables competitorInfoFrame
        disable_frame(self.parent.routeAttemptsEntryFrame)  # disables routeAttemptsEntryFrame
        self.parent.parent.competitorTab.competitorFrame.competitorSearchBar.clear()

    def calc_score(self):
        score = 0

        for entry in self.routeEntries:
            if entry.get() != '':
                score += int(entry.get()) * 100
            else:
                break
        return score
コード例 #10
0
ファイル: main.py プロジェクト: Mike-Tew/password-generator
title_label = Label(
    root,
    width=23,
    height=2,
    text="Password Generator",
    font=("Helvetica 16 bold"),
    bg="#bfbfbf",
)
title_label.grid(row=0, column=0, columnspan=3, pady=[0, 30])

length_label = Label(root, text="Length:", font={"Helvetica 25"})
length_label.grid(row=1, column=0, sticky="e")

length_input = Spinbox(root, width=3, from_=1, to=15, font=("Helvetica", 20))
length_input.insert(1, 0)
length_input.grid(row=1, column=1)

generate_button = Button(root,
                         text="Generate",
                         font=("Helvetica 12"),
                         command=generate_password)
generate_button.grid(row=1, column=2, sticky="w")

password_display = Entry(root,
                         width=15,
                         font=("Helvetica 20"),
                         bd=0,
                         bg="systembuttonface",
                         justify="center")
password_display.grid(row=2, column=0, columnspan=3, pady=[30, 0])
コード例 #11
0
class Settings(Frame):
    def __init__(self, master, widget, items, modifying=False):
        super().__init__(master, bg="#435661")

        self.widget = widget
        self.modifying = modifying
        self.record = {}
        self.index = 0
        self.spin_relx = None
        self.spin_rely = None
        self.spin_relw = None
        self.spin_relh = None
        self.label_arguments = None
        self.entry_arguments = None
        self.listbox = None
        self.entry_name = None
        self.set_layout()
        self.set_bindings()
        self.set_listbox(items)
        self.set_spinboxes()

    def set_layout(self):
        # self-explanatory
        Label(self, background='#435661', text='relx:', foreground='#defffc') \
            .place(relx=0.145, rely=0.0125, relwidth=0.1625, relheight=0.025, anchor='nw')

        Label(self, background='#435661', foreground='#defffc', text='rely:') \
            .place(relx=0.6845, rely=0.0135, relwidth=0.155, relheight=0.0225, anchor='nw')

        Label(self, background='#435661', text='relwidth:', foreground='#defffc') \
            .place(relx=0.044, rely=0.089, relwidth=0.37, relheight=0.02125, anchor='nw')

        Label(self, background='#435661', foreground='#defffc', text='relheight:') \
            .place(relx=0.667, rely=0.0875, relwidth=0.195, relheight=0.02375, anchor='nw')

        self.spin_relx = Spinbox(self,
                                 readonlybackground='#defffc',
                                 highlightthickness=0,
                                 foreground='#435661',
                                 from_=0,
                                 command=self.mod_relx,
                                 to_=1,
                                 increment=0.001,
                                 justify='center')
        self.spin_relx.place(relx=0.085,
                             rely=0.0425,
                             relwidth=0.295,
                             relheight=0.03375,
                             anchor='nw')

        self.spin_rely = Spinbox(self,
                                 readonlybackground='#defffc',
                                 foreground='#435661',
                                 justify='center',
                                 highlightthickness=0,
                                 command=self.mod_rely,
                                 from_=0,
                                 to_=1,
                                 increment=0.001)
        self.spin_rely.place(relx=0.6135,
                             rely=0.0425,
                             relwidth=0.3005,
                             relheight=0.03375,
                             anchor='nw')

        self.spin_relw = Spinbox(self,
                                 readonlybackground='#defffc',
                                 foreground='#435661',
                                 justify='center',
                                 highlightthickness=0,
                                 command=self.mod_relwidth,
                                 from_=0,
                                 to_=1,
                                 increment=0.001)
        self.spin_relw.place(relx=0.084,
                             rely=0.1175,
                             relwidth=0.295,
                             relheight=0.035,
                             anchor='nw')

        self.spin_relh = Spinbox(self,
                                 readonlybackground='#defffc',
                                 foreground='#435661',
                                 justify='center',
                                 highlightthickness=0,
                                 command=self.mod_relheight,
                                 from_=0,
                                 to_=1,
                                 increment=0.001)
        self.spin_relh.place(relx=0.6115,
                             rely=0.1177,
                             relwidth=0.304,
                             relheight=0.035,
                             anchor='nw')

        self.label_arguments = Label(self,
                                     background='#557282',
                                     foreground='#defffc')
        self.label_arguments.place(relx=0.086,
                                   rely=0.1832,
                                   relwidth=0.8305,
                                   relheight=0.06125,
                                   anchor='nw')

        self.entry_arguments = Entry(self,
                                     background='#defffc',
                                     foreground='#435661',
                                     justify='center')
        self.entry_arguments.place(relx=0.22,
                                   rely=0.2625,
                                   relwidth=0.545,
                                   relheight=0.04375,
                                   anchor='nw')

        self.listbox = Listbox(self,
                               background='#557282',
                               foreground='#defffc',
                               borderwidth=0)
        self.listbox.place(relx=0.085,
                           rely=0.3275,
                           relwidth=0.83,
                           relheight=0.4062,
                           anchor='nw')

        myButton(self, command=lambda *a: self.set_value(), text='OK') \
            .place(relx=0.8245, rely=0.2672, relwidth=0.13, relheight=0.0355, anchor='nw')

        Label(self, background='#435661', foreground='#defffc', text='Name:', anchor='w') \
            .place(relx=0.083, rely=0.766, relwidth=0.1205, relheight=0.035, anchor='nw')

        self.entry_name = Entry(self,
                                background='#defffc',
                                foreground='#435661',
                                justify='center')
        self.entry_name.place(relx=0.245,
                              rely=0.7662,
                              relwidth=0.5225,
                              relheight=0.035,
                              anchor='nw')

        self.entry_name.bind("<Return>", lambda *a: self.confirm())

        myButton(self, command=lambda *a: self.confirm(), text='CONFIRM') \
            .place(relx=0.201, rely=0.8575, relwidth=0.6155, relheight=0.0825, anchor='nw')

    def set_bindings(self):
        # self-explanatory
        self.entry_arguments.bind("<Return>", lambda *a: self.set_value())
        self.listbox.bind("<ButtonRelease-1>",
                          lambda *a: self.listbox_clicked())

        self.master.root.bind("<Left>",
                              lambda event: self.pressed_left_right(-1))
        self.master.root.bind("<Right>",
                              lambda event: self.pressed_left_right(1))

        self.master.root.bind("<Up>", lambda event: self.pressed_up_down(-1))
        self.master.root.bind("<Down>", lambda event: self.pressed_up_down(1))

    def set_spinboxes(self):
        # self-explanatory
        self.spin_relx.delete(0, "end")
        self.spin_rely.delete(0, "end")
        self.spin_relw.delete(0, "end")
        self.spin_relh.delete(0, "end")

        self.spin_relx.insert("end", self.widget.place_info()["relx"])
        self.spin_rely.insert("end", self.widget.place_info()["rely"])
        self.spin_relw.insert("end", self.widget.place_info()["relwidth"])
        self.spin_relh.insert("end", self.widget.place_info()["relheight"])

        self.spin_relx.configure(state="readonly")
        self.spin_rely.configure(state="readonly")
        self.spin_relw.configure(state="readonly")
        self.spin_relh.configure(state="readonly")

    def mod_relx(self):
        # Changes widget's relx parameter accordingly
        value = float(self.spin_relx.get())
        self.widget.place_configure(relx=value)

    def mod_rely(self):
        # Changes widget's rely parameter accordingly
        value = float(self.spin_rely.get())
        self.widget.place_configure(rely=value)

    def mod_relwidth(self):
        # Changes widget's relwidth parameter accordingly
        value = float(self.spin_relw.get())
        self.widget.place_configure(relwidth=value)

    def mod_relheight(self):
        # Changes widget's relheight parameter accordingly
        value = float(self.spin_relh.get())
        self.widget.place_configure(relheight=value)

    def pressed_left_right(self, factor):
        value = float(self.spin_relx.get())
        self.spin_relx.configure(state="normal")
        self.spin_relx.delete(0, "end")
        self.spin_relx.insert("end", value + factor * 0.001)
        self.spin_relx.configure(state="readonly")
        self.widget.place_configure(relx=value + factor * 0.001)

    def pressed_up_down(self, factor):
        value = float(self.spin_rely.get())
        self.spin_rely.configure(state="normal")
        self.spin_rely.delete(0, "end")
        self.spin_rely.insert("end", value + factor * 0.001)
        self.spin_rely.configure(state="readonly")
        self.widget.place_configure(rely=value + factor * 0.001)

    def set_listbox(self, items):
        for item in items:
            self.listbox.insert("end", item)
            self.record[item] = self.widget.cget(item)

    def listbox_clicked(self):
        # Changes entry_arguments's text and label_arguments's text, sets focus on entry_name
        self.index = self.listbox.curselection()[0]
        parameter = list(self.record.keys())[self.index]
        value = self.record[parameter]
        self.entry_arguments.delete(0, "end")
        self.entry_arguments.insert("end", value)
        self.label_arguments.configure(text=f"{parameter} = {value}")
        self.entry_arguments.focus_set()

    def set_value(self):
        # Sets entry_arguments's value as widget's argument, it needs to be evaluated first to avoid errors
        parameter = list(self.record.keys())[self.index]
        value = self.entry_arguments.get()

        try:
            evaluated_value = eval(value)
            self.record[parameter] = evaluated_value
        except:
            evaluated_value = value
            self.record[parameter] = f"{evaluated_value}"

        self.widget.configure({parameter: evaluated_value})

        self.label_arguments.configure(text=f"{parameter} = {value}")

    def confirm(self):
        # Checks if entry_name isn't empty or already used and then sends it to the master.Writer
        # After that it quits with .destroy()
        name = self.entry_name.get().replace(" ", "")
        if not self.modifying:
            if name and name not in self.master.record_of_names:
                self.master.record_of_names[name] = self.widget
                widget_cls = self.widget.winfo_class()

                self.master.writer.define_widget(name, widget_cls,
                                                 self.widget.place_info())
                self.master.writer.begin_configure(name)
                for key, value in self.record.items():
                    if value:
                        self.master.writer.write_configure(
                            name, key, f"'{value}'")
                self.master.writer.end_configure(name)

                self.master.root.unbind("<Down>")
                self.master.root.unbind("<Up>")
                self.master.root.unbind("<Left>")
                self.master.root.unbind("<Right>")

                self.destroy()
        else:
            widget_cls = self.widget.winfo_class()

            try:
                self.master.writer.define_widget(name, widget_cls,
                                                 self.widget.place_info(),
                                                 True)
                self.master.writer.begin_configure(name)
            except KeyError:
                self.entry_name.delete(0, "end")
                self.entry_name.insert("end", "NOME SBAGLIATO")
                return None

            for key, value in self.record.items():
                if value:
                    self.master.writer.write_configure(name, key, f"'{value}'")
            self.master.writer.end_configure(name)

            self.master.root.unbind("<Down>")
            self.master.root.unbind("<Up>")
            self.master.root.unbind("<Left>")
            self.master.root.unbind("<Right>")

            self.destroy()
コード例 #12
0
ファイル: sorter.py プロジェクト: Cryden13/AnimeSorter
 def cancelChange(self, frm: Frame, sbox: Spinbox) -> None:
     self.focus_set()
     oldRow = zerofrmt(frm.grid_info()['row'])
     if oldRow != sbox.get():
         sbox.delete(0, 'end')
         sbox.insert(0, oldRow)
コード例 #13
0
ファイル: client.py プロジェクト: KittyMcSnuggles/reddit
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.labelU = Label(self, text="U:")
        self.labelP = Label(self, text="P:")

        self.mailrecipient = 'GoldenSights'
        
        self.entryUsername = Entry(self)
        self.entryUsername.focus_set()
        self.entryUsername.bind('<Return>', lambda event: self.entryPassword.focus_set())

        self.entryPassword = Entry(self)
        self.entryPassword.config(show='•')
        self.entryPassword.bind('<Return>', lambda event: self.login(self.entryUsername.get(), self.entryPassword.get()))

        self.newbutton = Button(self, text="Login", command= lambda: self.login(self.entryUsername.get(), self.entryPassword.get()))
        self.newbutton.bind('<Return>', lambda event: self.login(self.entryUsername.get(), self.entryPassword.get()))
        self.newbutton.config(width=6)
        self.quitbutton = Button(self, text="Quit", command= lambda: self.quit())
        self.quitbutton.config(width=6)
    
        self.labelU.grid(row=0, column=0,padx=0)
        self.entryUsername.grid(row=0, column=1)
        self.labelP.grid(row=1, column=0)
        self.entryPassword.grid(row=1, column=1, pady=4)
        self.newbutton.grid(row=2, column=1)
        self.quitbutton.grid(row=3, column=1, pady=4)

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

        self.indicatorGreen = PhotoImage(file="indicatorGreen.gif")
        self.indicatorRed = PhotoImage(file="indicatorRed.gif")
        self.indicatorBlue = PhotoImage(file="indicatorBlue.gif")
        self.indicatorBlack = PhotoImage(file="indicatorBlack.gif")
        

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


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

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

    def login(self, username, password):
        print('U: ' + username)
        self.username = username
        if username == '' or not all(char in string.ascii_letters+string.digits+'_-' for char in username):
            print('Please enter a username')
            self.entryUsername.focus_set()
            self.labelErrorPointer.grid(row=0, column=2)
        elif password == '':
            print('Please enter a password')
            self.entryPassword.focus_set()
            self.labelErrorPointer.grid(row=1, column=2)
            
        else:
            self.labelErrorPointer.grid_forget()
            print('Attempting login for ' + username)
            try:
                self.USERAGENT = username + ' practices Tkinter+PRAW mixing with utility by /u/GoldenSights.'
                self.r = praw.Reddit(self.USERAGENT)
                #self.r.login(username, password)
                print('Success')
                self.labelU.grid_forget()
                self.labelP.grid_forget()
                self.entryUsername.grid_forget()
                self.entryPassword.grid_forget()
                self.newbutton.grid_forget()
                self.quitbutton.grid_forget()
                self.usernamelabel = Label(self, text=username + ', Sending to /u/' + self.mailrecipient)
                self.usernamelabel.grid(row=0, column=0, columnspan=8)
                self.quitbutton.grid(row=900, column=0)


                self.labellist = []
                self.entrylist = []
                self.verifylist = []
                self.misclist = []
                
                self.optionDiscuss = "Discussion Flair + Crossposting"
                self.optionRegister = "Register a new Candidate"

                self.prevmode = self.optionDiscuss
                self.curmode = self.optionDiscuss
                self.optionvar = tkinter.StringVar(self)
                self.optionvar.trace("w",self.permaloop)
                self.optionvar.set(self.optionDiscuss)
                self.option = OptionMenu(self, self.optionvar, self.optionDiscuss, self.optionRegister, "three", "four")
                self.newbutton.unbind("<Return>")
                self.entryUsername.unbind("<Return>")
                self.entryPassword.unbind("<Return>")
                self.option.grid(row=1,column=0,columnspan=8,pady=8)
                self.updategui(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(True)

    def updategui(self, *args):
        if args[0] == 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.optionDiscuss:
                self.newrowindex = 4
                self.labelPermalink = Label(self, text="Thread Permalink:")
                self.entryPermalink = Entry(self)
                self.rowconfigure(2,weight=2)
                self.labelPermalink.grid(row=2,column=0)
                self.entryPermalink.grid(row=2,column=1)
                self.labelcrossposting = Label(self,text="Crosspost to:")
                self.labelcrossposting.grid(row=3,column=0,columnspan=2,sticky="w")

                for m in range(5):
                    self.redditlabel = Label(self,text="/r/")
                    self.redditlabel.grid(row=self.newrowindex,column=0, sticky="e")
                    self.labellist.append(self.redditlabel)

                    self.redditentry = Entry(self)
                    self.redditentry.grid(row=self.newrowindex,column=1)
                    self.entrylist.append(self.redditentry)

                    self.newrowindex +=1

                self.morerowbutton = Button(self,text="+row",command=lambda: self.morerows('/r/', 0, 1, 20))
                self.morerowbutton.grid(row=898,column=0,columnspan=2)

                self.verifybutton = Button(self,text="Verify",command= lambda: self.updategui(False))
                self.verifybutton.grid(row=899,column=0,columnspan=2)

                self.newrowindex += 2

                self.misclist.append(self.labelPermalink)
                self.misclist.append(self.labelcrossposting)
                self.misclist.append(self.entryPermalink)
                self.misclist.append(self.morerowbutton)
                self.misclist.append(self.verifybutton)

            if self.curmode == self.optionRegister:
                self.newrowindex = 6
                self.labelCanUsername = Label(self, text="Candidate's Username:  /u/")
                self.entryCanUsername = Entry(self)
                self.labelCanRealname = Label(self, text="Candidate's Realname:")
                self.entryCanRealname = Entry(self)
                self.labelCanFlair = Label(self, text="Candidate's Flair:")
                self.entryCanFlair = Entry(self)
                self.entryMo = Spinbox(self, width=9, values=('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'))
                self.entryDa = Spinbox(self, width=2, from_=1, to=31)
                self.entryYr = Spinbox(self, width=4, from_=2014, to=2500)
                self.labelHH = Label(self, text="Schedule time UTC:")
                self.entryHH = Spinbox(self, from_=0, to=23, width=2)
                self.entryMM = Spinbox(self, from_=0, to=59, width=2)
                self.entryYr.delete(0,'end')
                self.entryYr.insert(0,2014)

                self.morerowbutton = Button(self,text="+question",command=lambda: self.morerows('Q:', 0, 1, 25))
                self.morerowbutton.grid(row=898,column=0,columnspan=8)

                self.verifybutton = Button(self,text="Verify",command= lambda: self.updategui(False))
                self.verifybutton.grid(row=899,column=0,columnspan=8)

                self.misclist.append(self.labelCanUsername)
                self.misclist.append(self.labelCanRealname)
                self.misclist.append(self.entryCanUsername)
                self.misclist.append(self.entryCanRealname)
                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.labelCanUsername.grid(row=2, column=0, sticky="e")
                self.labelCanRealname.grid(row=3, column=0, sticky="e")
                self.entryCanUsername.grid(row=2, column=1, columnspan=3)
                self.entryCanRealname.grid(row=3, column=1, columnspan=3)
                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")
        else:
            if self.curmode == self.optionDiscuss:

                verifies = []

                i = self.entryPermalink.get()
                if len(i) == 6:
                    pid = i
                else:
                    if 'www.reddit.com/r/' in i and '/comments/' in i:
                        pid = i.split('/comments/')[1].split('/')[0]
                    if 'http://redd.it/' in i:
                        pid = i.split('redd.it/')[1]

                for flag in self.verifylist:
                    flag.grid_forget()
                    self.verifylist.remove(flag)

                try:
                    print('Fetching Submission ' + pid)
                    self.r.get_info(thing_id="t3_" + pid).title + 'Check'
                    self.redditlabel = Label(self, image=self.indicatorGreen)
                    self.redditlabel.grid(row=2,column=2)
                    self.verifylist.append(self.redditlabel)
                    verifies.append(True)
                    print('\tSuccess')
                except:
                    print('Failed. Make sure to include the http://. Copy and paste straight from your browser for best result')
                    self.redditlabel = Label(self, image=self.indicatorRed)
                    self.redditlabel.grid(row=2,column=2)
                    self.verifylist.append(self.redditlabel)
                    verifies.append(False)

                for entry in self.entrylist:
                    i = entry.get()
                    if i != '':
                        print('Fetching /r/' + i)
                        if all(char in string.ascii_letters+string.digits+'_-' for char in i):
                            try:
                                sub = self.r.get_subreddit(i,fetch=True)
                                self.redditlabel = Label(self, image=self.indicatorGreen)
                                self.redditlabel.grid(row=entry.grid_info()['row'],column=2)
                                self.verifylist.append(self.redditlabel)
                                verifies.append(True)
                                print('\tSuccess')
                            except:
                                self.redditlabel = Label(self, image=self.indicatorRed)
                                self.redditlabel.grid(row=entry.grid_info()['row'],column=2)
                                self.verifylist.append(self.redditlabel)
                                verifies.append(False)
                                print('\tFailed')
                            time.sleep(2)
                        else:
                            self.redditlabel = Label(self, image=self.indicatorRed)
                            self.redditlabel.grid(row=entry.grid_info()['row'],column=2)
                            self.verifylist.append(self.redditlabel)
                            verifies.append(False)
                            print('\tFailed')

                print(verifies)


            if self.curmode == self.optionRegister:

                verifies = []
                u=self.entryCanUsername.get()
                print('Fetching /u/' + u)
                if not all(char in string.ascii_letters+string.digits+'_-' for char in u):
                    self.redditlabel = Label(self, image=self.indicatorRed)
                    self.redditlabel.grid(row=2, column=4)
                    self.verifylist.append(self.redditlabel)
                    verifies.append(False)
                    print('\tBad characterage')
                else:
                    try:
                        u = self.r.get_redditor(u)
                        print(u)
                        self.redditlabel = Label(self, image=self.indicatorGreen)
                        self.redditlabel.grid(row=2,column=4)
                        self.verifylist.append(self.redditlabel)
                        verifies.append(True)
                        print('\tSuccess')
                    except:
                        self.redditlabel = Label(self, image=self.indicatorRed)
                        self.redditlabel.grid(row=2,column=4)
                        self.verifylist.append(self.redditlabel)
                        verifies.append(False)
                        print('\tFailed')

                try:
                    print('Checking Time')
                    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 = datetime.datetime.utcfromtimestamp(plandate.timestamp())
                    print('\t' + str(plandate.timestamp()))

                    self.redditlabel = Label(self, image=self.indicatorGreen)
                    self.redditlabel.grid(row=5,column=3)
                    self.verifylist.append(self.redditlabel)
                    verifies.append(True)
                except:
                    print('\tFailed')
                    self.redditlabel = Label(self, image=self.indicatorRed)
                    self.redditlabel.grid(row=5,column=3)
                    self.verifylist.append(self.redditlabel)
                    verifies.append(False)

                print(verifies)


    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=8)
        self.entrylist.append(self.redditentry)

        self.newrowindex += 1
        if self.newrowindex >= limit:
            self.morerowbutton.grid_forget()
        print(self.newrowindex)
コード例 #14
0
class Form(Toplevel):
    def __init__(self, master, event, new=False):
        Toplevel.__init__(self, master)
        self.minsize(410, 402)
        if master.winfo_ismapped():
            self.transient(master)
        self.protocol('WM_DELETE_WINDOW', self.cancel)

        self._only_nb = self.register(only_nb)

        self.event = event
        if new:
            self.title(_('New Event'))
        else:
            self.title(_('Edit Event'))
        self._new = new
        self._task = BooleanVar(self, bool(event['Task']))
        self._whole_day = BooleanVar(self, event['WholeDay'])

        # --- style
        style = Style(self)
        active_bg = style.lookup('TEntry', 'selectbackground', ('focus', ))

        self.alarms = []

        notebook = Notebook(self)
        notebook.pack(fill='both', expand=True)
        Button(self, text=_('Ok'), command=self.ok).pack(pady=(10, 6), padx=4)

        # --- event settings
        frame_event = Frame(notebook)
        notebook.add(frame_event, text=_('Event'), sticky='eswn', padding=4)
        frame_event.columnconfigure(1, weight=1)
        frame_event.rowconfigure(5, weight=1)

        self.img_moins = PhotoImage(master=self, file=IM_DEL)
        self.img_bell = PhotoImage(master=self, file=IM_BELL)
        Label(frame_event, text=_('Summary')).grid(row=0,
                                                   column=0,
                                                   padx=4,
                                                   pady=6,
                                                   sticky='e')
        Label(frame_event, text=_('Place')).grid(row=1,
                                                 column=0,
                                                 padx=4,
                                                 pady=6,
                                                 sticky='e')
        Label(frame_event, text=_('Start')).grid(row=2,
                                                 column=0,
                                                 padx=4,
                                                 pady=6,
                                                 sticky='e')
        self._end_label = Label(frame_event, text=_('End'))
        self._end_label.grid(row=3, column=0, padx=4, pady=6, sticky='e')
        frame_task = Frame(frame_event)
        frame_task.grid(row=4, column=1, padx=4, pady=6, sticky='w')
        Label(frame_event, text=_('Description')).grid(row=5,
                                                       column=0,
                                                       padx=4,
                                                       pady=6,
                                                       sticky='e')
        Label(frame_event, text=_('Category')).grid(row=6,
                                                    column=0,
                                                    padx=4,
                                                    pady=6,
                                                    sticky='e')
        Button(frame_event,
               image=self.img_bell,
               command=self.add_reminder,
               padding=0).grid(row=7, column=0, padx=4, pady=6, sticky='en')

        self.summary = Entry(frame_event, width=35)
        self.summary.insert(0, self.event['Summary'])
        self.summary.grid(row=0, column=1, padx=4, pady=6, sticky='ew')
        self.place = Entry(frame_event, width=35)
        self.place.insert(0, self.event['Place'])
        self.place.grid(row=1, column=1, padx=4, pady=6, sticky='ew')
        frame_start = Frame(frame_event)
        frame_start.grid(row=2, column=1, padx=4, pady=6, sticky='w')
        frame_end = Frame(frame_event)
        frame_end.grid(row=3, column=1, padx=4, pady=6, sticky='w')
        txt_frame = Frame(frame_event,
                          style='txt.TFrame',
                          border=1,
                          relief='sunken')
        self.desc = Text(txt_frame,
                         width=35,
                         height=4,
                         highlightthickness=0,
                         relief='flat',
                         selectbackground=active_bg)
        self.desc.insert('1.0', self.event['Description'])
        self.desc.pack(fill='both', expand=True)
        txt_frame.grid(row=5, column=1, padx=4, pady=6, sticky='ewsn')
        cats = list(CONFIG.options('Categories'))
        width = max([len(cat) for cat in cats])
        self.category = Combobox(frame_event,
                                 width=width + 2,
                                 values=cats,
                                 state='readonly')
        self.category.set(event['Category'])
        self.category.grid(row=6, column=1, padx=4, pady=6, sticky='w')
        self.frame_alarms = Frame(frame_event)
        self.frame_alarms.grid(row=7, column=1, sticky='w')

        # --- *--- task
        Checkbutton(frame_task,
                    text=_('Task'),
                    command=self._change_label,
                    variable=self._task).pack(side='left')

        self.task_progress = Combobox(frame_task,
                                      state='readonly',
                                      width=9,
                                      values=(_('Pending'), _('In Progress'),
                                              _('Completed'), _('Cancelled')))
        self.task_progress.pack(side='left', padx=(8, 4))
        self.in_progress = Combobox(
            frame_task,
            state='readonly',
            width=5,
            values=['{}%'.format(i) for i in range(0, 110, 10)])
        self.in_progress.pack(side='left', padx=4)
        if not event['Task']:
            self.task_progress.set(_('Pending'))
            self.in_progress.set('0%')
        elif '%' in event['Task']:
            self.task_progress.set(_('In Progress'))
            self.in_progress.set(event['Task'])
        else:
            self.task_progress.set(_(event['Task']))
            self.in_progress.set('0%')

        # calendar settings
        prop = {
            op: CONFIG.get('Calendar', op)
            for op in CONFIG.options('Calendar')
        }
        prop['font'] = "Liberation\ Sans 9"
        prop.update(selectforeground='white', selectbackground=active_bg)
        locale = CONFIG.get('General', 'locale')

        # --- *--- start date
        self.start_date = self.event['Start']
        self.start_entry = DateEntry(frame_start,
                                     locale=locale,
                                     width=10,
                                     justify='center',
                                     year=self.start_date.year,
                                     month=self.start_date.month,
                                     day=self.start_date.day,
                                     **prop)

        self.start_hour = Combobox(frame_start,
                                   width=3,
                                   justify='center',
                                   state='readonly',
                                   exportselection=False,
                                   values=['%02d' % i for i in range(24)])
        self.start_hour.set('%02d' % self.start_date.hour)
        self.start_min = Combobox(frame_start,
                                  width=3,
                                  justify='center',
                                  state='readonly',
                                  exportselection=False,
                                  values=['%02d' % i for i in range(0, 60, 5)])
        self.start_min.set('%02d' % self.start_date.minute)
        self.start_entry.pack(side='left', padx=(0, 18))
        self.start_hour.pack(side='left', padx=(4, 0))
        self.start_date = self.start_date.date()
        Label(frame_start, text=':').pack(side='left')
        self.start_min.pack(side='left', padx=(0, 4))
        Checkbutton(frame_start,
                    text=_("whole day"),
                    variable=self._whole_day,
                    command=self._toggle_whole_day).pack(side='left', padx=4)

        # --- *--- end date
        self.end_date = self.event['End']
        self.end_entry = DateEntry(frame_end,
                                   justify='center',
                                   locale=locale,
                                   width=10,
                                   year=self.end_date.year,
                                   month=self.end_date.month,
                                   day=self.end_date.day,
                                   **prop)

        self.end_hour = Combobox(frame_end,
                                 width=3,
                                 justify='center',
                                 state='readonly',
                                 exportselection=False,
                                 values=['%02d' % i for i in range(24)])
        self.end_hour.set('%02d' % self.end_date.hour)
        self.end_min = Combobox(frame_end,
                                width=3,
                                justify='center',
                                state='readonly',
                                exportselection=False,
                                values=['%02d' % i for i in range(0, 60, 5)])
        self.end_min.set('%02d' % self.end_date.minute)
        self.end_entry.pack(side='left', padx=(0, 18))

        self.end_hour.pack(side='left', padx=(4, 0))
        Label(frame_end, text=':').pack(side='left')
        self.end_min.pack(side='left', padx=(0, 4))
        self.end_date = self.end_date.date()

        for date in self.event['Reminders'].values():
            self.add_reminder(date)

        self._toggle_whole_day()

        # --- repetition settings
        frame_rep = Frame(notebook)
        notebook.add(frame_rep, text=_('Repetition'), padding=4, sticky='eswn')
        frame_rep.columnconfigure(0, weight=1)
        frame_rep.columnconfigure(1, weight=1)
        frame_rep.rowconfigure(1, weight=1)
        self._repeat = BooleanVar(self, bool(self.event['Repeat']))
        repeat = {
            'Frequency': 'year',
            'Limit': 'always',
            'NbTimes': 1,
            'EndDate': (datetime.now() + timedelta(days=1)).date(),
            'WeekDays': [self.start_date.isocalendar()[2] - 1]
        }
        repeat.update(self.event['Repeat'])

        self._repeat_freq = StringVar(self, repeat['Frequency'])
        Checkbutton(frame_rep,
                    text=_('Repeat event'),
                    variable=self._repeat,
                    command=self._toggle_rep).grid(row=0,
                                                   column=0,
                                                   columnspan=2,
                                                   padx=4,
                                                   pady=6,
                                                   sticky='w')
        # --- *--- Frequency
        frame_freq = LabelFrame(frame_rep, text=_('Frequency'))
        frame_freq.grid(row=1, column=0, sticky='eswn', padx=(0, 3))
        self._lfreq = Label(frame_freq, text=_('Every:'))
        self._lfreq.grid(row=0, column=0, padx=4, pady=2, sticky='e')

        self._freqs = []
        for i, val in enumerate(['Year', 'Month', 'Week']):
            r = Radiobutton(frame_freq,
                            text=_(val),
                            variable=self._repeat_freq,
                            value=val.lower(),
                            command=self._toggle_wd)
            r.grid(row=i, column=1, padx=4, pady=2, sticky='nw')
            self._freqs.append(r)

        frame_days = Frame(frame_freq)
        frame_days.grid(row=2, column=2, padx=4, pady=2, sticky='nw')
        self._week_days = []
        days = get_day_names("wide", locale=locale)
        days = [days[i] for i in range(7)]
        for day in days:
            ch = Checkbutton(frame_days, text=day)
            ch.pack(anchor='w')
            self._week_days.append(ch)

        for d in repeat['WeekDays']:
            self._week_days[int(d)].state(('selected', ))

        # --- *--- Limit
        frame_lim = LabelFrame(frame_rep, text=_('Limit'))
        frame_lim.grid(row=1, column=1, sticky='eswn', padx=(3, 0))
        frame_lim.grid(row=1, column=1, sticky='eswn', padx=(3, 0))
        self._repeat_lim = StringVar(self, repeat['Limit'])

        # always
        r1 = Radiobutton(frame_lim,
                         text=_('Always'),
                         value='always',
                         variable=self._repeat_lim,
                         command=self._toggle_lim)
        r1.grid(row=0, column=0, sticky='w')
        # until
        r2 = Radiobutton(frame_lim,
                         text=_('Until'),
                         value='until',
                         variable=self._repeat_lim,
                         command=self._toggle_lim)
        r2.grid(row=1, column=0, sticky='w')
        until_date = repeat['EndDate']
        self.until_entry = DateEntry(frame_lim,
                                     width=10,
                                     justify='center',
                                     locale=locale,
                                     year=until_date.year,
                                     month=until_date.month,
                                     day=until_date.day,
                                     **prop)

        self.until_entry.grid(row=1,
                              column=1,
                              columnspan=2,
                              sticky='w',
                              padx=(4, 10),
                              pady=2)

        # after
        r3 = Radiobutton(frame_lim,
                         text=_('After'),
                         value='after',
                         variable=self._repeat_lim,
                         command=self._toggle_lim)
        r3.grid(row=2, column=0, sticky='w')
        frame_after = Frame(frame_lim,
                            style='txt.TFrame',
                            relief='sunken',
                            border=1)
        self.s_after = Spinbox(frame_after,
                               from_=0,
                               to=100,
                               width=3,
                               justify='center',
                               relief='flat',
                               highlightthickness=0,
                               validate='key',
                               validatecommand=(self._only_nb, '%P'),
                               disabledbackground='white')
        self.s_after.pack()
        self.s_after.delete(0, 'end')
        self.s_after.insert(0, str(repeat['NbTimes']))
        frame_after.grid(row=2, column=1, padx=4, pady=2, sticky='w')
        self._llim = Label(frame_lim, text=_('times'))
        self._llim.grid(row=2, column=2, padx=0, pady=2, sticky='w')

        self._rb_lim = [r1, r2, r3]

        self._toggle_rep()
        self._change_label()

        # --- bindings
        self.bind('<Configure>')
        self.task_progress.bind('<<ComboboxSelected>>',
                                self._toggle_in_progress)
        self.start_entry.bind('<<DateEntrySelected>>', self._select_start)
        self.end_entry.bind('<<DateEntrySelected>>', self._select_end)
        self.start_hour.bind("<<ComboboxSelected>>", self._select_start_hour)
        self.start_min.bind("<<ComboboxSelected>>", self._select_start_min)
        self.end_min.bind("<<ComboboxSelected>>", self._select_end_time)
        self.end_hour.bind("<<ComboboxSelected>>", self._select_end_time)
        self.bind_class("TCombobox",
                        "<<ComboboxSelected>>",
                        self.__clear_selection,
                        add=True)

        # self.wait_visibility(self)
        # self.grab_set()
        self.summary.focus_set()

    def _toggle_lim(self, val=True):
        if val:
            val = self._repeat_lim.get()

        if val == 'until':
            self.s_after.configure(state='disabled')
            self._llim.state(('disabled', ))
            self.until_entry.state(('!disabled', ))
        elif val == 'after':
            self._llim.state(('!disabled', ))
            self.s_after.configure(state='normal')
            self.until_entry.state(('disabled', ))
        else:
            self.s_after.configure(state='disabled')
            self._llim.state(('disabled', ))
            self.until_entry.state(('disabled', ))

    def _toggle_rep(self):
        rep = self._repeat.get()
        state = state = '!' * int(rep) + "disabled"
        for r in self._freqs:
            r.state((state, ))
        for r in self._rb_lim:
            r.state((state, ))
        self._lfreq.state((state, ))
        self._toggle_wd(rep)
        self._toggle_lim(rep)

    def _toggle_wd(self, val=True):
        if val:
            val = self._repeat_freq.get()
        state = '!' * int(val == 'week') + "disabled"
        for ch in self._week_days:
            ch.state((state, ))

    def _toggle_whole_day(self):
        if self._whole_day.get():
            self.start_min.set('00')
            self.start_hour.set('00')
            self.end_min.set('59')
            self.end_hour.set('23')
            self.start_min.state(("disabled", ))
            self.start_hour.state(("disabled", ))
            self.end_min.state(("disabled", ))
            self.end_hour.state(("disabled", ))
        else:
            self.start_min.state(("!disabled", ))
            self.start_hour.state(("!disabled", ))
            self.end_min.state(("!disabled", ))
            self.end_hour.state(("!disabled", ))

    def _toggle_in_progress(self, event=None):
        if self.task_progress.get() == _('In Progress'):
            self.in_progress.state(('!disabled', ))
        else:
            if self.task_progress.get() == _('Completed'):
                self.in_progress.set('100%')
            self.in_progress.state(('disabled', ))

    def _change_label(self):
        if self._task.get():
            self.task_progress.state(('!disabled', ))
            self._toggle_in_progress()
            self._end_label.configure(text=_('Deadline'))
        else:
            self.task_progress.state(('disabled', ))
            self.in_progress.state(('disabled', ))
            self._end_label.configure(text=_('End'))

    def _on_move(self, event):
        self.start_cal.withdraw()
        self.end_cal.withdraw()
        self.until_cal.withdraw()

    @staticmethod
    def __clear_selection(event):
        combo = event.widget
        combo.selection_clear()

    def _select_start(self, event=None):
        dt = self.start_entry.get_date() - self.start_date
        self.end_date = self.end_date + dt
        self.end_entry.set_date(self.end_date)
        self.start_date = self.start_entry.get_date()

    def _select_end(self, event=None):
        self.end_date = self.end_entry.get_date()
        start = self.start_entry.get_date()
        if start >= self.end_date:
            self.start_date = self.end_date
            self.start_entry.set_date(self.end_date)
            start_time = time(int(self.start_hour.get()),
                              int(self.start_min.get()))
            end_time = time(int(self.start_hour.get()),
                            int(self.end_min.get()))
            if start_time > end_time:
                self.start_hour.set(self.end_hour.get())
                self.start_min.set(self.end_min.get())

    def _select_start_hour(self, event):
        h = int(self.start_hour.get())
        self.end_hour.set('%02d' % ((h + 1) % 24))

    def _select_start_min(self, event):
        m = int(self.start_min.get())
        self.end_min.set('%02d' % m)

    def _select_end_time(self, event):
        if self.start_entry.get() == self.end_entry.get():
            start_time = time(int(self.start_hour.get()),
                              int(self.start_min.get()))
            end_time = time(int(self.end_hour.get()), int(self.end_min.get()))
            if start_time > end_time:
                self.start_hour.set(self.end_hour.get())
                self.start_min.set(self.end_min.get())

    def add_reminder(self, date=None):
        def remove():
            self.alarms.remove((when, what))
            rem.destroy()

        rem = Frame(self.frame_alarms)
        frame_when = Frame(rem, style='txt.TFrame', relief='sunken', border=1)
        when = Spinbox(frame_when,
                       from_=0,
                       to=59,
                       width=3,
                       justify='center',
                       relief='flat',
                       highlightthickness=0,
                       validate='key',
                       validatecommand=(self._only_nb, '%P'))
        when.pack()
        when.delete(0, 'end')
        what = Combobox(rem,
                        width=8,
                        state='readonly',
                        values=(_('minutes'), _('hours'), _('days')))

        if date:
            hour = int(self.start_hour.get())
            minute = int(self.start_min.get())
            dt = datetime.combine(self.start_entry.get_date(),
                                  time(hour=hour, minute=minute)) - date
            if dt.days > 0:
                when.insert(0, str(dt.days))
                what.set(_('days'))
            else:
                h, m, s = str(dt).split(':')
                if h != "0":
                    when.insert(0, h)
                    what.set(_('hours'))
                else:
                    when.insert(0, str(int(m)))
                    what.set(_('minutes'))
        else:
            when.insert(0, '15')
            what.set(_('minutes'))

        self.alarms.append((when, what))

        Label(rem, text=_('Reminder:')).pack(side='left', padx=4, pady=4)
        frame_when.pack(side='left', pady=4, padx=4)
        what.pack(side='left', pady=4, padx=4)
        Button(rem, image=self.img_moins, padding=0,
               command=remove).pack(side='left', padx=4, pady=4)
        rem.pack()

    def ok(self):
        summary = self.summary.get()
        if not summary:
            showerror(_("Error"),
                      _("The field 'Summary' cannot be empty."),
                      parent=self)
            return

        self.event['Summary'] = summary
        self.event['Place'] = self.place.get()
        self.event['Start'] = "%s %s:%s" % (
            self.start_entry.get_date().strftime("%Y-%m-%d"),
            self.start_hour.get(), self.start_min.get())
        self.event['End'] = "%s %s:%s" % (self.end_entry.get_date().strftime(
            "%Y-%m-%d"), self.end_hour.get(), self.end_min.get())
        self.event['Description'] = self.desc.get('1.0', 'end')
        self.event['Category'] = self.category.get()
        if not self._task.get():
            self.event['Task'] = False
        else:
            prog = self.task_progress.get()
            if prog == _('In Progress'):
                self.event['Task'] = self.in_progress.get()
            else:
                self.event['Task'] = TASK_REV_TRANSLATION[prog]

        self.event["WholeDay"] = self._whole_day.get()

        if not self._repeat.get():
            self.event['Repeat'] = {}
        else:
            days = []
            for i in range(7):
                if "selected" in self._week_days[i].state():
                    days.append(i)
            repeat = {
                'Frequency': self._repeat_freq.get(),
                'Limit': self._repeat_lim.get(),
                'NbTimes': int(self.s_after.get()),
                'EndDate': self.until_entry.get_date(),
                'WeekDays': days
            }
            self.event['Repeat'] = repeat

        self.event.reminder_remove_all()
        for when, what in self.alarms:
            dt = int(when.get())
            unit = FREQ_REV_TRANSLATION[what.get()]
            date = self.event['Start'] - timedelta(**{unit: dt})
            self.event.reminder_add(date)

        if self._new:
            self.master.event_add(self.event)
        else:
            self.master.event_configure(self.event.iid)
        self.destroy()

    def cancel(self):
        if not self._new:
            self.master.widgets['Calendar'].add_event(self.event)
        self.destroy()
コード例 #15
0
 def __createUSBSpinBox(self, frame, deviceList, activeUSB):
     spin = Spinbox(frame, values=deviceList)
     spin.delete(0, END)
     spin.insert(0, activeUSB)
     spin.grid(row=5, column=0)
     return spin
コード例 #16
0
ファイル: NIC.py プロジェクト: CSEMN/NIC
bigLable.pack()

#Configuration frame
#contains input count and creat input table
configFrame = LabelFrame(main_window, text="Configuration", font=("Arial", 12))
inputcountLable = Label(configFrame, text="input count", font=("Arial", 10))
inputcountLable.grid(row=0, column=0, padx=5)
inputcountEnrty = Spinbox(configFrame,
                          from_=2,
                          to=10,
                          width=3,
                          justify=CENTER,
                          validate='focusout',
                          validatecommand=numValidate)
inputcountEnrty.delete(0)
inputcountEnrty.insert(END, "4")
inputcountEnrty.grid(row=0, column=1, padx=5)
inputcountButton = Button(configFrame,
                          text="create table !",
                          command=createInputTable,
                          font=('Arial', 10, "bold"))
inputcountButton.grid(row=0, column=2, padx=5)
configFrame.pack()
#End of configuration frame

#input table frame
#contains values of X and f(x) entered by user
inputTableFrame = LabelFrame(main_window,
                             text="Input table",
                             font=("Arial", 12))
inputTableValues = []
コード例 #17
0
ファイル: master.py プロジェクト: og3niuz/BotSim
def send_command(command):
    global s
    commands = [
        "Execute", "Brute Force", "Report Address", "Fingerprint OS",
        "Commit Suicide", "Send Email", "Slow Loris", "Reconnect",
        "Download File", "Profile Computer", "Scan Host", "Scan Network"
    ]
    output("Preparing to send command '" + commands[command] + "'")
    global child
    child = Toplevel(root)
    verbose = BooleanVar()
    verbose_label = Label(child, text="Verbose")
    verbose_box = Checkbutton(child, variable=verbose)
    if command is 0:
        com_label = Label(child, text="Command to Execute")
        com_label.grid(row=0, column=0)
        com_entry = Entry(child)
        com_entry.grid(row=0, column=1)
        verbose_label.grid(row=1, column=0)
        verbose_box.grid(row=1, column=1)
        submit = Button(
            child,
            width=35,
            text="Begin",
            command=lambda: s.send(
                ("PRIVMSG " + channel_entry.get(
                ) + " :COMMAND EXECUTE <<<" + com_entry.get() + ">>> " +
                 ("VERBOSE" if verbose else "") + "\r\n").encode("UTF8")))
        submit.grid(row=2, column=0, columnspan=2, sticky="NESW")
    elif command is 1:
        pass
    elif command is 2:
        verbose_label.grid(row=0, column=0)
        verbose_box.grid(row=0, column=1)
        submit = Button(
            child,
            width=35,
            text="Begin",
            command=lambda: s.send(
                ("PRIVMSG " + channel_entry.get() + " :COMMAND ADDRESS " +
                 ("VERBOSE" if verbose else "") + "\r\n").encode("UTF8")))
        submit.grid(row=2, column=0, columnspan=2, sticky="NESW")
    elif command is 3:
        verbose_label.grid(row=0, column=0)
        verbose_box.grid(row=0, column=1)
        submit = Button(
            child,
            width=35,
            text="Begin",
            command=lambda: s.send(
                ("PRIVMSG " + channel_entry.get() + " :COMMAND FINGERPRINT " +
                 ("VERBOSE" if verbose else "") + "\r\n").encode("UTF8")))
        submit.grid(row=2, column=0, columnspan=2, sticky="NESW")
    elif command is 4:
        verbose_label.grid(row=0, column=0)
        verbose_box.grid(row=0, column=1)
        submit = Button(
            child,
            width=35,
            text="Begin",
            command=lambda: s.send(
                ("PRIVMSG " + channel_entry.get() + " :COMMAND KILL " +
                 ("VERBOSE" if verbose else "") + "\r\n").encode("UTF8")))
        submit.grid(row=2, column=0, columnspan=2, sticky="NESW")
    elif command is 5:
        sender_label = Label(child, text="Sender Email")
        sender_label.grid(row=0, column=0)
        sender_entry = Entry(child)
        sender_entry.grid(row=0, column=1)
        sender_password_label = Label(child, text="Sender Password")
        sender_password_label.grid(row=1, column=0)
        sender_password_entry = Entry(child, show="*")
        sender_password_entry.grid(row=1, column=1)
        recipient_label = Label(child, text="Recipient Email")
        recipient_label.grid(row=2, column=0)
        recipient_entry = Entry(child)
        recipient_entry.grid(row=2, column=1)
        subject_label = Label(child, text="Email Subject")
        subject_label.grid(row=3, column=0)
        subject_entry = Entry(child)
        subject_entry.grid(row=3, column=1)
        msg_label = Label(child, text="Email Contents", justify="center")
        msg_label.grid(row=4, column=0, columnspan=2, sticky="NESW")
        msg_entry = Text(child)
        msg_entry.grid(row=5, column=0, columnspan=2, sticky="NESW")
        verbose_label.grid(row=6, column=0)
        verbose_box.grid(row=6, column=1)
        submit = Button(
            child,
            width=35,
            text="Begin",
            command=lambda: s.send(
                ("PRIVMSG " + channel_entry.get() + " :COMMAND EMAIL " +
                 sender_entry.get() + " " + sender_password_entry.
                 get() + " " + recipient_entry.get() + " " + subject_entry.get(
                 ) + " <<<" + msg_entry.get("1.0", "end") + ">>> " +
                 ("VERBOSE" if verbose else "") + "\r\n").encode("UTF8")))
        submit.grid(row=7, column=0, columnspan=2, sticky="NESW")
    elif command is 6:
        host_label = Label(child, text="Host or Domain")
        host_entry = Entry(child)
        host_label.grid(row=0, column=0)
        host_entry.grid(row=0, column=1)
        loris_port_label = Label(child, text="Port")
        loris_port_spin = Spinbox(child, from_=0, to=65535, width=5)
        loris_port_spin.insert(0, 8)
        loris_port_label.grid(row=1, column=0)
        loris_port_spin.grid(row=1, column=1)
        randua_label = Label(child, text="Random User Agents")
        randua = BooleanVar()
        randua_box = Checkbutton(child, variable=randua)
        randua_label.grid(row=2, column=0)
        randua_box.grid(row=2, column=1)
        https = BooleanVar()
        https_label = Label(child, text="Use HTTPS")
        https_box = Checkbutton(child, variable=https)
        https_label.grid(row=3, column=0)
        https_box.grid(row=3, column=1)
        sock_count = IntVar()
        sockets_label = Label(child, text="Number of sockets")
        sockets_scale = Scale(child,
                              variable=sock_count,
                              orient="horizontal",
                              from_=1,
                              to=500)
        sockets_label.grid(row=4, column=0)
        sockets_scale.grid(row=4, column=1)
        verbose_label.grid(row=5, column=0)
        verbose_box.grid(row=5, column=1)
        submit = Button(
            child,
            width=35,
            text="Begin",
            command=lambda: s.send(
                ("PRIVMSG " + channel_entry.get() + " :COMMAND SLOWLORIS " +
                 host_entry.get() + " " + str(loris_port_spin.get()) + " " +
                 ("TRUE" if randua else "FALSE") + " " +
                 ("TRUE"
                  if https else "FALSE") + " " + str(sock_count.get()) + " " +
                 ("VERBOSE" if verbose else "") + "\r\n").encode("UTF8")))
        submit.grid(row=6, column=0, columnspan=2, sticky="NESW")
    elif command is 7:
        verbose_label.grid(row=0, column=0)
        verbose_box.grid(row=0, column=1)
        submit = Button(
            child,
            width=35,
            text="Begin",
            command=lambda: s.send(
                ("PRIVMSG " + channel_entry.get() + " :COMMAND RECONNECT " +
                 ("VERBOSE" if verbose else "") + "\r\n").encode("UTF8")))
        submit.grid(row=1, column=0, columnspan=2, sticky="NESW")
    elif command is 8:
        url_label = Label(child, text="Source URL")
        url_label.grid(row=0, column=0)
        url_entry = Entry(child)
        url_entry.grid(row=0, column=1)
        filename_label = Label(child, text="Filename")
        filename_label.grid(row=1, column=0)
        filename_entry = Entry(child)
        filename_entry.grid(row=1, column=1)
        verbose_label.grid(row=2, column=0)
        verbose_box.grid(row=2, column=1)
        submit = Button(
            child,
            width=35,
            text="Begin",
            command=lambda: s.send(
                ("PRIVMSG " + channel_entry.get() + " :COMMAND DOWNLOAD " +
                 url_entry.get() + " " + filename_entry.get() + " " +
                 ("VERBOSE" if verbose else "") + "\r\n").encode("UTF8")))
        submit.grid(row=3, column=0, columnspan=2, sticky="NESW")
    elif command is 9:
        verbose_label.grid(row=0, column=0)
        verbose_box.grid(row=0, column=1)
        submit = Button(
            child,
            width=35,
            text="Begin",
            command=lambda: s.send(
                ("PRIVMSG " + channel_entry.get() + " :COMMAND PROFILE " +
                 ("VERBOSE" if verbose else "") + "\r\n").encode("UTF8")))
        submit.grid(row=1, column=0, columnspan=2, sticky="NESW")
    elif command is 10:
        pass
    elif command is 11:
        pass
コード例 #18
0
class Application(Frame):
    def __init__(self, master=None):
        """ Main GUI."""
        Frame.__init__(self, master)
        Frame.grid(self, padx=(40, 40), pady=(10, 10))

        self.path1 = StringVar()
        path1_lbl = ttk.Label(self, text='Path:')
        path1_lbl.grid(column=1, columnspan=4, row=1, sticky=W)
        path1_entry = ttk.Entry(self, width=30, textvariable=self.path1)
        path1_entry.grid(column=1, columnspan=4, row=2, sticky=(W, E))
        path1_btn = ttk.Button(self, text="Browse", command=self.open1)
        path1_btn.grid(column=1, row=3, sticky=W, padx=(0, 0))

        self.graph1_btn = ttk.Button(self,
                                     text="Graph",
                                     state=DISABLED,
                                     command=lambda: self.graph1(self.C, 1))
        self.graph1_btn.grid(column=2, row=3, sticky=W)

        self.info1_lbl = ttk.Label(self, text='Scan Info/Comments:')
        self.info1_lbl.grid(column=1,
                            columnspan=4,
                            row=5,
                            sticky=W,
                            pady=(10, 0))
        self.info1_Entry = Text(self, width=30, height=12)
        self.info1_Entry.grid(column=1, columnspan=4, row=6, sticky=(N, W, E))

        in_C = StringVar()
        self.input_entry = ttk.Entry(self, width=10, textvariable=in_C)
        self.input_entry.grid(column=4, row=3, sticky=(W, E))
        self.int_btn = ttk.Button(self,
                                  text="Input Array",
                                  command=lambda: self.Input_C())
        self.int_btn.grid(column=4, row=5, sticky=W)

        self.int_lbl = ttk.Label(self,
                                 text="Inverse Distance "
                                 "Weighting Interpolation",
                                 font='bold')
        self.int_lbl.grid(column=1,
                          columnspan=4,
                          row=7,
                          sticky=W,
                          pady=(10, 2))

        self.int_btn = ttk.Button(self,
                                  text="Interpolate",
                                  state=DISABLED,
                                  command=lambda: self.interpolation(self.C))
        self.int_btn.grid(column=1, row=8, sticky=W)

        self.NP1 = IntVar()
        self.NP1.set(5)
        n_lbl = ttk.Label(self, text='No. pts')
        n_lbl.grid(column=1, row=9, sticky=(N, W))
        self.n_box = Spinbox(self,
                             format='%.0f',
                             from_=0,
                             to=self.NP1.get(),
                             width=5,
                             increment=1)  #1E10
        self.n_box.grid(column=1, row=10, sticky=(N, W))
        self.n_box.insert(1, 5)

        p_lbl = ttk.Label(self, text='Power')
        p_lbl.grid(column=2, row=9, sticky=(N, W))
        self.p_box = Spinbox(self,
                             format='%.0f',
                             from_=0,
                             to=1E10,
                             width=5,
                             increment=1)
        self.p_box.grid(column=2, row=10, sticky=(N, W))
        self.p_box.insert(1, 2)

        self.transpose_chk = IntVar()
        self.trans_btn = Checkbutton(self,
                                     text="Tranpose",
                                     variable=self.transpose_chk,
                                     state=DISABLED,
                                     command=lambda: self.check_tr(self.C))
        self.trans_btn.grid(column=3, row=10, sticky=(N, W))

        self.Refl_x = IntVar()
        self.Refl_x.set(1)
        self.Refl_x_btn = Checkbutton(self,
                                      text="Reflect_x",
                                      variable=self.Refl_x,
                                      state=DISABLED,
                                      command=lambda: self.check_tr(self.C))
        self.Refl_x_btn.grid(column=3, row=9, sticky=(N, W))
        self.info1_Entry.insert(END, "Reflect x = %s" % (self.Refl_x.get()))
        self.N_out_btn = ttk.Button(self,
                                    text="Save-Grid",
                                    state=DISABLED,
                                    command=lambda: self.N_out(self.N))
        self.N_out_btn.grid(column=1, row=12, sticky=W)
        self.M_out_btn = ttk.Button(self,
                                    text="Save-xyz",
                                    state=DISABLED,
                                    command=lambda: self.N_out(self.M))
        self.M_out_btn.grid(column=2, row=12, sticky=W)
        self.plot_btn = ttk.Button(self,
                                   text="Plot",
                                   state=DISABLED,
                                   command=lambda: self.plot(self.C, self.N))
        self.plot_btn.grid(column=3, row=12, sticky=(N, W))

        # Default values for the interpolated grid
        self.x01_ = StringVar()
        self.y01_ = StringVar()
        self.x01_.set(0.600001)  #default
        self.y01_.set(0.600001)  #default

        self.dx1_ = DoubleVar()  # from file
        self.dy1_ = DoubleVar()  # from file

        self.y02_ = StringVar()
        self.x02_ = StringVar()
        self.x02_.set(0.60)  #default
        self.y02_.set(0.60)  #default

        self.dx2_ = StringVar()
        self.dy2_ = StringVar()
        self.dx2_.set(0.5)  #default
        self.dy2_.set(0.5)  #default

        self.np_x2_ = StringVar()
        self.np_y2_ = StringVar()
        self.np_x2_.set(13)  #default
        self.np_y2_.set(13)  #default

        self.grid2_lbl = ttk.Label(self, text="Interpolated Grid")
        self.grid2_lbl.grid(column=1,
                            columnspan=4,
                            row=22,
                            sticky=(W, E),
                            pady=(5, 2))

        x01_entry = ttk.Entry(self, width=6, textvariable=self.x01_)
        x01_entry.grid(column=2, row=17, sticky=W)
        x01_lbl = ttk.Label(self, text='x0')
        x01_lbl.grid(column=1, row=17, sticky=(N, W), padx=(40, 0))

        y01_entry = ttk.Entry(self, width=6, textvariable=self.y01_)
        y01_entry.grid(column=4, row=17, sticky=W)
        y01_lbl = ttk.Label(self, text='y0')
        y01_lbl.grid(column=3, row=17, sticky=(N, W), padx=(40, 0))

        dx1_entry = ttk.Entry(self, width=6, textvariable=self.dx1_)
        dx1_entry.grid(column=2, row=18, sticky=W)
        dx1_lbl = ttk.Label(self, text='dx1')
        dx1_lbl.grid(column=1, row=18, sticky=(N, W), padx=(40, 0))

        dy1_entry = ttk.Entry(self, width=6, textvariable=self.dy1_)
        dy1_entry.grid(column=4, row=18, sticky=W)
        dy1_lbl = ttk.Label(self, text='dy1')
        dy1_lbl.grid(column=3, row=18, sticky=(N, W), padx=(40, 0))

        x02_entry = ttk.Entry(self, width=6, textvariable=self.x02_)
        x02_entry.grid(column=2, row=23, sticky=W)
        x02_lbl = ttk.Label(self, text='x0 (Int)')
        x02_lbl.grid(column=1, row=23, sticky=(N, W), padx=(40, 0))

        y02_entry = ttk.Entry(self, width=6, textvariable=self.y02_)
        y02_entry.grid(column=4, row=23, sticky=W)
        y02_lbl = ttk.Label(self, text='y0 (Int)')
        y02_lbl.grid(column=3, row=23, sticky=(N, W), padx=(40, 0))

        dx2_entry = ttk.Entry(self, width=6, textvariable=self.dx2_)
        dx2_entry.grid(column=2, row=24, sticky=W)
        dx2_lbl = ttk.Label(self, text='dx2')
        dx2_lbl.grid(column=1, row=24, sticky=(N, W), padx=(40, 0))

        dy2_entry = ttk.Entry(self, width=6, textvariable=self.dy2_)
        dy2_entry.grid(column=4, row=24, sticky=W)
        dy2_lbl = ttk.Label(self, text='dy2')
        dy2_lbl.grid(column=3, row=24, sticky=(N, W), padx=(40, 0))

        np_x2_entry = ttk.Entry(self, width=6, textvariable=self.np_x2_)
        np_x2_entry.grid(column=2, row=25, sticky=W)
        np_x2_lbl = ttk.Label(self, text='np_x2')
        np_x2_lbl.grid(column=1, row=25, sticky=(N, W), padx=(40, 0))

        np_y2_entry = ttk.Entry(self, width=6, textvariable=self.np_y2_)
        np_y2_entry.grid(column=4, row=25, sticky=W)
        np_y2_lbl = ttk.Label(self, text='np_y2')
        np_y2_lbl.grid(column=3, row=25, sticky=(N, W), padx=(40, 0))

        self.tipwf = DoubleVar()
        self.tipwf.set(4220)
        self.tip = IntVar()
        self.tip_btn = Checkbutton(self,
                                   text="Tip correction (mV)",
                                   variable=self.tip,
                                   state=DISABLED,
                                   command=lambda: self.workfunction(self.C))
        self.tip_btn.grid(column=3,
                          columnspan=2,
                          row=26,
                          sticky=(N, W),
                          pady=(15, 0))

        self.tip_entry = ttk.Entry(self, width=6, textvariable=self.tipwf)
        self.tip_entry.grid(column=2, row=26, sticky=E, pady=(15, 0))

        minmax_lbl = ttk.Label(self, text='Min and Max x/y')
        minmax_lbl.grid(column=2, columnspan=3, row=19, sticky=(N, W))

        self.xi = IntVar()
        self.xi.set(0)
        self.xf = IntVar()
        self.xf.set(0)
        xdata_lbl = ttk.Label(self, text='x-data_subset')
        xdata_lbl.grid(column=1, row=20, sticky=(N, W))
        self.xidata_box = Spinbox(self,
                                  format='%.0f',
                                  from_=0,
                                  to=self.xf.get(),
                                  width=5,
                                  increment=1)
        self.xidata_box.grid(column=2, row=20, sticky=(N, W), padx=(15, 0))
        self.xidata_box.insert(1, 0)
        self.xfdata_box = Spinbox(self,
                                  format='%.0f',
                                  from_=0,
                                  to=self.xf.get(),
                                  width=5,
                                  increment=1)
        self.xfdata_box.grid(column=3, row=20, sticky=(N, W))
        self.xfdata_box.insert(1, 0)

        self.yi = IntVar()
        self.yi.set(0)
        self.yf = IntVar()
        self.yf.set(0)
        ydata_lbl = ttk.Label(self, text='y-data_subset')
        ydata_lbl.grid(column=1, row=21, sticky=(N, W))
        self.yidata_box = Spinbox(self,
                                  format='%.0f',
                                  from_=0,
                                  to=self.yf.get(),
                                  width=5,
                                  increment=1)
        self.yidata_box.grid(column=2, row=21, sticky=(N, W), padx=(15, 0))
        self.yidata_box.insert(1, 0)
        self.yfdata_box = Spinbox(self,
                                  format='%.0f',
                                  from_=0,
                                  to=self.yf.get(),
                                  width=5,
                                  increment=1)
        self.yfdata_box.grid(column=3, row=21, sticky=(N, W))
        self.yfdata_box.insert(1, 0)

    def enable_btn(self):
        self.graph1_btn.config(state='ENABLED')
        self.int_btn.config(state='ENABLED')
        self.trans_btn.config(state='normal')
        self.Refl_x_btn.config(state='normal')
        self.N_out_btn.config(state='ENABLED')
        self.M_out_btn.config(state='ENABLED')
        self.tip_btn.config(state='normal')

    def Input_C(self):
        """"Loads tab-delimited data from the corresponding text-box"""
        A = self.input_entry.get()
        self.info1_Entry.delete(1.0, END)

        B = []
        reader = csv.reader(A.split('\n'), delimiter='\t')
        for row in reader:
            row = row[:]
            B.append(row)
        B = B[0:len(B) - 1][0:len(B[0])]
        for i in range(0, len(B)):
            for j in range(0, len(B[i])):
                B[i][j] = float(B[i][j])
        B = asarray(B)
        print(B)
        self.dx1_.set(0.18)
        self.dy1_.set(0.18)
        self.NP1.set(len(B[0]) * len(B) - 1)
        self.n_box.config(to=self.NP1.get())

        self.xf.set(len(B[0]))
        self.xfdata_box.delete(0, "end")
        self.xfdata_box.insert(1, self.xf.get())
        self.xidata_box.config(to=self.xf.get())
        self.xfdata_box.config(to=self.xf.get())

        self.yf.set(len(B))
        self.yfdata_box.delete(0, "end")
        self.yfdata_box.insert(1, self.yf.get())
        self.yidata_box.config(to=self.yf.get())
        self.yfdata_box.config(to=self.yf.get())

        self.C = B
        self.enable_btn()
        self.graph1(B, 1)
        return self.C

    def open1(self):
        """"Loads data from file and displays footer information"""
        fileName = filedialog.askopenfilename(title="Open CPD file")
        try:
            f = open(fileName, 'r')
        except IOError:
            pass

        i = f.readline().strip()
        if i == "Work Function data":
            pass
        else:
            i = messagebox.askyesno(title="Open file?",
                                    message="CPD file header not present!\n"
                                    "Proceed to open file?",
                                    default='no')
            if i == 1:
                pass
            else:
                pass
        self.path1.set(fileName)
        g = f.read()
        f.close()

        # Only CPD data is loaded but there are other measurements
        Tracking = g.find('Tracking')
        Grad = g.find('Grad')
        # Time = g.find('Time')
        # User = g.find('User')
        Footer = g.find('/') - 2
        # Footer = Footer - 2

        CPD_data = g[0:Tracking]
        # Tracking_data = g[Tracking:Grad]
        # Grad_data = g[Grad:Time]
        # Time_data = g[Time:User]
        # User_data = g[User:Footer]
        Footer_data = g[Footer:]

        a = Footer_data.split("\n")
        Date = a[0]
        Grad = [int(i) for i in a[-10].split() if i.isdigit()]
        DAS_Averages = [int(i) for i in a[-18].split() if i.isdigit()]
        WF_Averages = [int(i) for i in a[-14].split() if i.isdigit()]
        Xpoints = [int(i) for i in a[-5].split() if i.isdigit()]
        Ypoints = [int(i) for i in a[-4].split() if i.isdigit()]
        Xsteps = [int(i) for i in a[-3].split() if i.isdigit()]
        Ysteps = [int(i) for i in a[-2].split() if i.isdigit()]
        Xstepscm = Xsteps[0] * 0.0015  #xyscale
        Ystepscm = Ysteps[0] * 0.0015

        # C is the array used for the raw data
        C = []
        reader = csv.reader(CPD_data.split('\n'), delimiter=',')
        for row in reader:
            row = row[:-1]
            C.append(row)
        C = C[0:len(C) - 1][0:len(C[0])]
        for i in range(0, len(C)):
            for j in range(0, len(C[i])):
                C[i][j] = float(C[i][j])
        C = asarray(C)

        # Clear the textbox before putting in data for new file
        self.info1_Entry.delete(1.0, END)
        info_0 = "%s\n%s\n" % (fileName, Date)
        info_1 = ("Xpoints = %s\nYpoints = %s\nXsteps = %s (%s cm)\n"
                  "Ysteps= %s (%s cm)" \
            % (Xpoints[0], Ypoints[0], Xsteps[0], Xstepscm, Ysteps[0],
               Ystepscm))
        info_2 = "\nDAS_Aves = %s\nWF_Averages = %s\nGrad = %s"\
            % (DAS_Averages[0],WF_Averages[0],Grad[0])
        self.info1_Entry.insert(END, info_0)
        self.info1_Entry.insert(END, info_1)
        self.info1_Entry.insert(END, info_2)
        if self.Refl_x.get() == 1:
            info_3 = "\nReflect x = %s" % (self.Refl_x.get())
            self.info1_Entry.insert(END, info_3)

        if self.transpose_chk.get() == 1:
            info_4 = "\nTranspose = %s" % (self.transpose_chk.get())
            self.info1_Entry.insert(END, info_4)

        self.enable_btn()

        # To prevent divide by 0 issue 1E-8 is added
        if Xpoints[0] == len(C[0]):
            self.dx1_.set(Xstepscm + 1E-8)
            self.dy1_.set(Ystepscm + 1E-8)
        else:
            self.dy1_.set(Xstepscm + 1E-8)
            self.dx1_.set(Ystepscm + 1E-8)

        self.NP1.set(len(C[0]) * len(C) - 1)
        self.n_box.config(to=self.NP1.get())

        self.xf.set(len(C[0]))
        self.xfdata_box.delete(0, "end")
        self.xfdata_box.insert(1, self.xf.get())
        self.xidata_box.config(to=self.xf.get())
        self.xfdata_box.config(to=self.xf.get())

        self.yf.set(len(C))
        self.yfdata_box.delete(0, "end")
        self.yfdata_box.insert(1, self.yf.get())
        self.yidata_box.config(to=self.yf.get())
        self.yfdata_box.config(to=self.yf.get())

        self.tip.set(0)

        self.C = C
        self.Cr = C
        return self.C, self.Cr

    def graph1(self, data, row_a):
        """Graphs the raw CPD data"""
        plt.close()
        plt.figure(figsize=(3.5, 3.5), dpi=100, frameon=False)
        im = plt.imshow(data, cmap='jet')
        plt.colorbar(im, orientation='vertical', fraction=0.046, pad=0.05)

        plt.tight_layout()
        plt.savefig(path.join(tmpdir, im_name1), dpi=100, bbox_inches='tight')

        c = Canvas(self, width=350, height=350, bg='white')
        c.grid(row=row_a,
               column=5,
               columnspan=2,
               rowspan=50,
               sticky=(W, N),
               padx=50)
        c.background = PhotoImage(file=path.join(tmpdir, im_name1))
        c.create_image(1, 20, image=c.background, anchor=NW)

    def interpolation(self, C):
        """Performs inverse distance interpolation"""
        temp = []
        for j in range(int(self.yidata_box.get()), int(self.yfdata_box.get())):
            temp.append([])
            for i in range(int(self.xidata_box.get()),
                           int(self.xfdata_box.get())):
                temp[j - int(self.yidata_box.get())].append(C[j, i])
        # Sub-array of raw data defined by the min and max x/y value
        C = temp
        C = asarray(C)

        n = self.n_box.get()
        n = int(n)

        p = self.p_box.get()
        p = int(p)

        x01 = float(self.x01_.get())
        y01 = float(self.y01_.get())

        dx1 = float(self.dx1_.get())
        dy1 = float(self.dy1_.get())

        y02 = float(self.y02_.get())
        x02 = float(self.x02_.get())

        dx2 = float(self.dx2_.get())
        dy2 = float(self.dy2_.get())

        np_x2 = int(self.np_x2_.get())
        np_y2 = int(self.np_y2_.get())

        if self.transpose_chk.get() == 1:
            C = transpose(C)

        # Define the dimensions of the raw data grid
        np_x1 = len(C[0])
        np_y1 = len(C)

        NP1 = np_x1 * np_y1

        x1 = ones(np_x1)
        for i in range(0, np_x1):
            x1[i] = x01 + dx1 * i

        y1 = ones(np_y1)
        for i in range(0, np_y1):
            y1[i] = y01 + dy1 * i

        if self.Refl_x.get() == 1:
            x1_ = ones(np_x1)
            for i in range(0, len(x1)):
                x1_[i] = x1[-1 - i]
            x1 = x1_

        data_1d = C.flatten()

        # Define the dimensions of interpolated data grid
        NP2 = np_x2 * np_y2

        x2 = ones(np_x2)
        for i in range(0, np_x2):
            x2[i] = x02 + dx2 * i

        y2 = ones(np_y2)
        for i in range(0, np_y2):
            y2[i] = y02 + dy2 * i

        # Intperolation calculation
        k2 = 0
        int_data = ones(NP2)
        dist = [0] * (NP1)
        index = [0] * (NP1)
        for j2 in range(0, np_y2):
            for i2 in range(0, np_x2):
                dist_2d = []
                dist_1d = []
                for j in range(0, np_y1):
                    dist_2d.append([])
                    for i in range(0, np_x1):
                        dist_2d[j].append(
                            sqrt((x2[i2] - x1[i])**2 + (y2[j2] - y1[j])**2))
                        dist_1d.append(
                            sqrt((x2[i2] - x1[i])**2 + (y2[j2] - y1[j])**2))

                index = sorted(range(len(dist_1d)), key=lambda x: dist_1d[x])
                dist = sorted(dist_1d)
                up = min(n, NP1)
                temp = 0
                lamb = ones(up)
                if dist[0] > 0:
                    for i in range(0, up):
                        lamb[i] = (1/(dist[i]**p))\
                            /sum(ones(up)/power_(dist[0:up],p))
                        temp = temp + data_1d[index[i]] * lamb[i]
                else:
                    temp = data_1d[index[i]]
                int_data[k2] = temp
                k2 = k2 + 1

        M1 = []
        N = []
        k2 = 0
        for j2 in range(0, np_y2):
            N.append([])
            for i2 in range(0, np_x2):
                M1.append([x02 + i2 * dx2, y02 + j2 * dy2, int_data[k2]])
                N[j2].append(int_data[k2])
                k2 = k2 + 1
        M1 = asarray(M1)
        N = asarray(N)

        # Generate a xyz equivalent array
        if np_x2 == np_y2:
            Mt = []
            for j2 in range(0, np_y2):
                for i2 in range(0, np_x2):
                    Mt.append([y02 + j2 * dy2, x02 + i2 * dx2, N[i2, j2]])
                    k2 = k2 + 1
            M = append(Mt, M1, axis=1)
        else:
            M = M1

        self.N = N
        self.M1 = M1
        self.M = M

        self.graph1(self.N, 8)

        self.plot_btn.config(state='ENABLED')
        return (self.N, self.M1, self.M)

    def check_tr(self, C):
        self.info1_Entry.delete(10.0, END)
        if self.Refl_x.get() == 1:
            info_3 = "\nReflect x = %s" % (self.Refl_x.get())
            self.info1_Entry.insert(END, info_3)

        if self.transpose_chk.get() == 1:
            info_4 = "\nTranspose = %s" % (self.transpose_chk.get())
            self.info1_Entry.insert(END, info_4)
        self.interpolation(C)

    def plot(self, C, N):
        """Produces images of the raw and interpolated data plots"""
        plt.close('all')
        fig_ext = plt.figure(dpi=200)
        ax1 = fig_ext.add_subplot(121)
        ax1_im = plt.imshow(C,
                            vmin=amin([amin(C), amin(N)]),
                            vmax=amax([amax(C), amax(N)]),
                            cmap='jet')

        cbar = plt.colorbar(ax1_im,
                            orientation='vertical',
                            fraction=0.046,
                            pad=0.05)  # aspect='auto')
        if self.tip.get() == 1:
            cbar.set_label('Work Function (meV)')
        else:
            cbar.set_label('CPD (mV)')
        plt.xlabel('x-axis')
        plt.ylabel('y-axis')

        ax2 = fig_ext.add_subplot(122)
        ax2_im = plt.imshow(N,
                            vmin=amin([amin(C), amin(N)]),
                            vmax=amax([amax(C), amax(N)]),
                            cmap='jet')
        cbar = plt.colorbar(ax2_im,
                            orientation='vertical',
                            fraction=0.046,
                            pad=0.05)  #, aspect='auto')
        if self.tip.get() == 1:
            cbar.set_label('Work Function (meV)')
        else:
            cbar.set_label('CPD (mV)')
        plt.xlabel('x-axis')
        plt.ylabel('y-axis')

        plt.tight_layout()
        fig_ext = plt.gcf()
        plt.show()

    def N_out(self, N):
        """Exports the data as a csv file via dialogue box"""
        file_opt = options = {}
        options['filetypes'] = [('all files', '.*'),
                                ('CSV (Comma Delimited)', '.csv')]
        options['initialfile'] = '.csv'
        options['title'] = 'Save Array as CSV'

        try:
            fo1 = filedialog.asksaveasfile(mode='wb', **file_opt)
            savetxt(fo1,
                    N,
                    delimiter=',',
                    footer=self.info1_Entry.get(1.0, END))
            fo1.close()
        except IOError:
            messagebox.showinfo(title="Output file",
                                message="Output file issue")

    def workfunction(self, C):
        """Applies linear offset to CPD, useful for correcing 
        for the tip's workfunction and converting CPD into 
        workfunction"""
        if self.tip.get() == 1:
            self.C = C + float(self.tipwf.get())
            self.tip_entry.config(state='disabled')
        else:
            self.C = (C - float(self.tipwf.get()))
            self.tip_entry.config(state="normal")
        self.graph1(self.C, 1)
        return self.C
コード例 #19
0
ファイル: UI.py プロジェクト: llzhao1997/NURBS-UI
                        width=4,
                        command=updateAll)
radio2D = ttk.Radiobutton(master=sideFrame,
                          text='2D',
                          variable=ui.dim2d3d,
                          value='2D',
                          command=changeDim)
radio3D = ttk.Radiobutton(master=sideFrame,
                          text='3D',
                          variable=ui.dim2d3d,
                          value='3D',
                          command=changeDim)

# INITIAL VALUES
spinboxDegree.delete(0, END)
spinboxDegree.insert(0, ui.ndeg)
# spinboxDegree.bind("<Increment>", updateAll)

labelSeg = ttk.Label(master=sideFrame, text="Segmentos:")
spinboxSeg = Spinbox(master=sideFrame,
                     from_=1,
                     to=5000,
                     textvariable=ui.nseg,
                     width=7,
                     command=updateAll)

spinboxDegree.bind('<Return>', updateAll)
spinboxSeg.bind('<Return>', updateAll)
# INITIAL VALUES
spinboxSeg.delete(0, END)
spinboxSeg.insert(0, ui.nseg)
コード例 #20
0
class NewPosterizeWindow(Toplevel):
    def __init__(self, name, master=None):
        super().__init__(master=master)
        self.set_basic(name)

        self.master.image.posterize(2)

        self.bind('<Configure>', lambda e: self.place_buttons())

    def set_basic(self, name):
        self.overrideredirect(1)
        self.set_geometry()
        self.set_spinbox()
        self.set_save_closeButtons()
        self.title("Redukcja poziomów szarości {}".format(name))

    def set_geometry(self):
        self.height = 30
        parentX = self.master.winfo_rootx()
        parentY = self.master.winfo_rooty()
        parentHeight = self.master.winfo_height()
        parentWidth = self.master.winfo_width()
        self.geometry(
            '%dx%d+%d+%d' %
            (parentWidth, self.height, parentX, parentY + parentHeight + 2))

    def set_spinbox(self):
        self.spinBox = Spinbox(self,
                               command=lambda: self.update_preview(),
                               from_=2,
                               to=255,
                               width=3,
                               font=("Helvetica", 15),
                               justify=LEFT)
        self.spinBox.place(relx=0.375, relwidth=0.25)
        self.spinBox.delete(0, "end")
        self.spinBox.insert(0, 2)

    def set_save_closeButtons(self):
        self.saveButton = Button(self,
                                 image=saveIcon,
                                 command=self.update_image)
        self.cancelButton = Button(self, image=closeIcon, command=self.cancel)
        self.saveButton.place(relx=1 -
                              ((2 * self.height) / self.master.winfo_width()),
                              relheight=1)
        self.cancelButton.place(relx=1 -
                                (self.height / self.master.winfo_width()),
                                relheight=1)

    def place_buttons(self):
        self.saveButton.place(relx=1 -
                              ((2 * self.height) / self.master.winfo_width()),
                              relheight=1,
                              width=self.height)
        self.cancelButton.place(relx=1 -
                                (self.height / self.master.winfo_width()),
                                relheight=1,
                                width=self.height)

    def update_preview(self):
        self.master.image.posterize(int(self.spinBox.get()))
        self.master.update_visible_image()

    def update_image(self):
        self.master.update_visible_image()
        self.master.image.copy = copy.deepcopy(self.master.image.cv2Image)
        self.master.image.fill_histogram()
        self.master.update_child_windows()
        self.master.manager.new_state(self.master.image.cv2Image)
        self.master.posterizeWindow = None
        self.destroy()

    def cancel(self):
        self.master.image.cv2Image = copy.deepcopy(self.master.image.copy)
        self.master.update_visible_image()
        self.master.image.fill_histogram()
        self.master.update_child_windows()
        self.master.posterizeWindow = None
        self.destroy()
コード例 #21
0
ファイル: webpgui.py プロジェクト: BenRGH/webpgui
    fileslistbox.delete(1.0,END)
    fileslistbox.insert(END, sysout)

 
window = Tk()

window.title("webpgui")
window.geometry('570x220')
window.resizable(False, False)

lbl = Label(window, text="Convert to webp", font=("Arial Bold", 20))
lbl.grid(column=0, row=0, padx=(100, 10))

fileslistbox = scrolledtext.ScrolledText(window, width=50, height=9, wrap=WORD)
fileslistbox.grid(column=0, row=1, padx=(10, 10))

selectBtn = Button(window, text="Select", command=select, height=9, width=6, bg="lightblue")
selectBtn.grid(column=1, row=1, padx=(0,10))

convertBtn = Button(window, text="Convert", command=convert, height=9, width=6, bg="lightgreen")
convertBtn.grid(column=2, row=1)

qlbl = Label(window, text="Quality %:", font=("Arial Bold", 10), width=10)
qlbl.grid(column=0, row=2)

quality = Spinbox(window, from_=0, to=100, width=6, font=("Arial Bold", 10))
quality.delete(0,END)
quality.insert(0,qualityValue)
quality.grid(column=1, row=2)

window.mainloop()
コード例 #22
0
ファイル: scheduleclient.py プロジェクト: Vindora/reddit
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)
コード例 #23
0
ファイル: 3.07.py プロジェクト: joyfish/Programas
class DrumMachine:
    def __init__(self, root):
        self.root = root
        self.root.title(PROGRAM_NAME)
        self.all_patterns = [None] * MAX_NUMBER_OF_PATTERNS
        self.beats_per_minute = INITIAL_BEATS_PER_MINUTE
        self.current_pattern_index = 0
        self.loop = True
        self.now_playing = False
        self.drum_load_entry_widget = [None] * MAX_NUMBER_OF_DRUM_SAMPLES
        self.init_all_patterns()
        self.init_gui()

    def on_open_file_button_clicked(self, drum_index):
        def event_handler():
            file_path = filedialog.askopenfilename(defaultextension=".wav",
                                                   filetypes=[
                                                       ("Wave Files", "*.wav"),
                                                       ("OGG Files", "*.ogg")
                                                   ])
            if not file_path:
                return
            self.set_drum_file_path(drum_index, file_path)
            self.display_all_drum_file_names()

        return event_handler

    def display_all_drum_file_names(self):
        for i, drum_name in enumerate(self.get_list_of_drum_files()):
            self.display_drum_name(i, drum_name)

    def display_drum_name(self, text_widget_num, file_path):
        if file_path is None:
            return
        drum_name = os.path.basename(file_path)
        self.drum_load_entry_widget[text_widget_num].delete(0, END)
        self.drum_load_entry_widget[text_widget_num].insert(0, drum_name)

    #
    # getters and setters begins
    #

    def get_current_pattern_dict(self):
        return self.all_patterns[self.current_pattern_index]

    def get_bpu(self):
        return self.get_current_pattern_dict()['bpu']

    def set_bpu(self):
        self.get_current_pattern_dict()['bpu'] = int(self.bpu_widget.get())

    def get_number_of_units(self):
        return self.get_current_pattern_dict()['number_of_units']

    def set_number_of_units(self):
        self.get_current_pattern_dict()['number_of_units'] = int(
            self.number_of_units_widget.get())

    def get_list_of_drum_files(self):
        return self.get_current_pattern_dict()['list_of_drum_files']

    def get_drum_file_path(self, drum_index):
        return self.get_list_of_drum_files()[drum_index]

    def set_drum_file_path(self, drum_index, file_path):
        self.get_list_of_drum_files()[drum_index] = file_path

    def get_is_button_clicked_list(self):
        return self.get_current_pattern_dict()['is_button_clicked_list']

    def set_is_button_clicked_list(self, num_of_rows, num_of_columns):
        self.get_current_pattern_dict()['is_button_clicked_list'] = [
            [False] * num_of_columns for x in range(num_of_rows)
        ]

    def init_all_patterns(self):
        self.all_patterns = [{
            'list_of_drum_files': [None] * MAX_NUMBER_OF_DRUM_SAMPLES,
            'number_of_units':
            INITIAL_NUMBER_OF_UNITS,
            'bpu':
            INITIAL_BPU,
            'is_button_clicked_list':
            self.init_is_button_clicked_list(
                MAX_NUMBER_OF_DRUM_SAMPLES,
                INITIAL_NUMBER_OF_UNITS * INITIAL_BPU)
        } for k in range(MAX_NUMBER_OF_PATTERNS)]

    def on_pattern_changed(self):
        pass

    def on_number_of_units_changed(self):
        self.set_number_of_units()
        self.set_is_button_clicked_list(MAX_NUMBER_OF_DRUM_SAMPLES,
                                        self.find_number_of_columns())
        self.create_right_button_matrix()

    def on_bpu_changed(self):
        self.set_bpu()
        self.set_is_button_clicked_list(MAX_NUMBER_OF_DRUM_SAMPLES,
                                        self.find_number_of_columns())
        self.create_right_button_matrix()

    def play_in_thread(self):
        self.thread = threading.Thread(target=self.play_pattern)
        self.thread.start()

    def on_play_button_clicked(self):
        self.start_play()
        self.toggle_play_button_state()

    def start_play(self):
        self.init_pygame()
        self.play_in_thread()

    def on_stop_button_clicked(self):
        self.stop_play()
        self.toggle_play_button_state()

    def toggle_play_button_state(self):
        if self.now_playing:
            self.play_button.config(state="disabled")
        else:
            self.play_button.config(state="normal")

    def exit_app(self):
        self.now_playing = False
        if messagebox.askokcancel("Quit", "Really quit?"):
            self.root.destroy()

    def stop_play(self):
        self.now_playing = False

    def init_pygame(self):
        pygame.mixer.pre_init(44100, -16, 1, 512)
        pygame.init()

    def play_sound(self, sound_filename):
        if sound_filename is not None:
            pygame.mixer.Sound(sound_filename).play()

    def get_column_from_matrix(self, matrix, i):
        return [row[i] for row in matrix]

    def play_pattern(self):
        self.now_playing = True
        self.toggle_play_button_state()
        while self.now_playing:
            play_list = self.get_is_button_clicked_list()
            num_columns = len(play_list[0])
            for column_index in range(num_columns):
                column_to_play = self.get_column_from_matrix(
                    play_list, column_index)
                for i, item in enumerate(column_to_play):
                    if item:
                        sound_filename = self.get_drum_file_path(i)
                        self.play_sound(sound_filename)
                time.sleep(self.time_to_play_each_column())
                if not self.now_playing: break
            if not self.loop: break
        self.now_playing = False
        self.toggle_play_button_state()

    def time_to_play_each_column(self):
        beats_per_second = self.beats_per_minute / 60
        time_to_play_each_column = 1 / beats_per_second
        return time_to_play_each_column

    def on_loop_button_toggled(self):
        self.loop = self.loopbuttonvar.get()

    def on_beats_per_minute_changed(self):
        self.beats_per_minute = int(self.beats_per_minute_widget.get())

    def init_is_button_clicked_list(self, num_of_rows, num_of_columns):
        return [[False] * num_of_columns for x in range(num_of_rows)]

    def get_button_value(self, row, col):
        return self.all_patterns[
            self.current_pattern_index]['is_button_clicked_list'][row][col]

    def find_number_of_columns(self):
        return int(self.number_of_units_widget.get()) * int(
            self.bpu_widget.get())

    def process_button_clicked(self, row, col):
        self.set_button_value(row, col, not self.get_button_value(row, col))
        self.display_button_color(row, col)

    def set_button_value(self, row, col, bool_value):
        self.all_patterns[self.current_pattern_index][
            'is_button_clicked_list'][row][col] = bool_value

    def on_button_clicked(self, row, col):
        def event_handler():
            self.process_button_clicked(row, col)

        return event_handler

    def display_all_button_colors(self):
        number_of_columns = self.find_number_of_columns()
        for r in range(MAX_NUMBER_OF_DRUM_SAMPLES):
            for c in range(number_of_columns):
                self.display_button_color(r, c)

    def display_button_color(self, row, col):
        bpu = int(self.bpu_widget.get())
        original_color = COLOR_1 if ((col // bpu) % 2) else COLOR_2
        button_color = BUTTON_CLICKED_COLOR if self.get_button_value(
            row, col) else original_color
        self.buttons[row][col].config(background=button_color)

    def create_play_bar(self):
        playbar_frame = Frame(self.root, height=15)
        start_row = MAX_NUMBER_OF_DRUM_SAMPLES + 10
        playbar_frame.grid(row=start_row,
                           columnspan=13,
                           sticky=W + E,
                           padx=15,
                           pady=10)
        self.play_icon = PhotoImage(file="images/play.gif")
        self.play_button = Button(playbar_frame,
                                  text='Play',
                                  image=self.play_icon,
                                  compound='left',
                                  command=self.on_play_button_clicked)
        self.play_button.grid(row=start_row, column=1, padx=2)
        Button(playbar_frame, text='Stop',
               command=self.on_stop_button_clicked).grid(row=start_row,
                                                         column=3,
                                                         padx=2)
        self.loopbuttonvar = BooleanVar()
        self.loopbuttonvar.set(True)
        self.loopbutton = Checkbutton(playbar_frame,
                                      text='Loop',
                                      command=self.on_loop_button_toggled,
                                      variable=self.loopbuttonvar)
        self.loopbutton.grid(row=start_row, column=16, padx=5)
        Label(playbar_frame, text='Beats Per Minute').grid(row=start_row,
                                                           column=25)
        self.beats_per_minute_widget = Spinbox(
            playbar_frame,
            from_=MIN_BEATS_PER_MINUTE,
            to=MAX_BEATS_PER_MINUTE,
            width=5,
            increment=5.0,
            command=self.on_beats_per_minute_changed)
        self.beats_per_minute_widget.grid(row=start_row, column=30)
        self.beats_per_minute_widget.delete(0, "end")
        self.beats_per_minute_widget.insert(0, INITIAL_BEATS_PER_MINUTE)
        photo = PhotoImage(file='images/signature.gif')
        label = Label(playbar_frame, image=photo)
        label.image = photo
        label.grid(row=start_row, column=50, padx=1, sticky='w')

    def create_right_button_matrix(self):
        right_frame = Frame(self.root)
        right_frame.grid(row=10,
                         column=6,
                         sticky=W + E + N + S,
                         padx=15,
                         pady=4)
        self.buttons = [[None for x in range(self.find_number_of_columns())]
                        for x in range(MAX_NUMBER_OF_DRUM_SAMPLES)]
        for row in range(MAX_NUMBER_OF_DRUM_SAMPLES):
            for col in range(self.find_number_of_columns()):
                self.buttons[row][col] = Button(right_frame,
                                                command=self.on_button_clicked(
                                                    row, col))
                self.buttons[row][col].grid(row=row, column=col)
                self.display_button_color(row, col)

    def create_left_drum_loader(self):
        left_frame = Frame(self.root)
        left_frame.grid(row=10, column=0, columnspan=6, sticky=W + E + N + S)
        open_file_icon = PhotoImage(file='images/openfile.gif')
        for i in range(MAX_NUMBER_OF_DRUM_SAMPLES):
            open_file_button = Button(
                left_frame,
                image=open_file_icon,
                command=self.on_open_file_button_clicked(i))
            open_file_button.image = open_file_icon
            open_file_button.grid(row=i, column=0, padx=5, pady=4)
            self.drum_load_entry_widget[i] = Entry(left_frame)
            self.drum_load_entry_widget[i].grid(row=i,
                                                column=4,
                                                padx=7,
                                                pady=4)

    def create_top_bar(self):
        topbar_frame = Frame(self.root, height=25)
        topbar_frame.grid(row=0, columnspan=12, rowspan=10, padx=5, pady=5)

        Label(topbar_frame, text='Pattern Number:').grid(row=0, column=1)
        self.pattern_index_widget = Spinbox(topbar_frame,
                                            from_=0,
                                            to=MAX_NUMBER_OF_PATTERNS - 1,
                                            width=5,
                                            command=self.on_pattern_changed)
        self.pattern_index_widget.grid(row=0, column=2)
        self.current_pattern_name_widget = Entry(topbar_frame)
        self.current_pattern_name_widget.grid(row=0, column=3, padx=7, pady=2)

        Label(topbar_frame, text='Number of Units:').grid(row=0, column=4)
        self.number_of_units_widget = Spinbox(
            topbar_frame,
            from_=1,
            to=MAX_NUMBER_OF_UNITS,
            width=5,
            command=self.on_number_of_units_changed)
        self.number_of_units_widget.delete(0, "end")
        self.number_of_units_widget.insert(0, INITIAL_NUMBER_OF_UNITS)
        self.number_of_units_widget.grid(row=0, column=5)
        Label(topbar_frame, text='BPUs:').grid(row=0, column=6)
        self.bpu_widget = Spinbox(topbar_frame,
                                  from_=1,
                                  to=MAX_BPU,
                                  width=5,
                                  command=self.on_bpu_changed)
        self.bpu_widget.grid(row=0, column=7)
        self.bpu_widget.delete(0, "end")
        self.bpu_widget.insert(0, INITIAL_BPU)

    def create_top_menu(self):
        self.menu_bar = Menu(self.root)
        self.file_menu = Menu(self.menu_bar, tearoff=0)
        self.file_menu.add_command(label="Load Project")
        self.file_menu.add_command(label="Save Project")
        self.file_menu.add_separator()
        self.file_menu.add_command(label="Exit")
        self.menu_bar.add_cascade(label="File", menu=self.file_menu)
        self.about_menu = Menu(self.menu_bar, tearoff=0)
        self.about_menu.add_command(label="About")
        self.menu_bar.add_cascade(label="About", menu=self.about_menu)
        self.root.config(menu=self.menu_bar)

    def init_gui(self):
        self.create_top_menu()
        self.create_top_bar()
        self.create_left_drum_loader()
        self.create_right_button_matrix()
        self.create_play_bar()
コード例 #24
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.labelU = Label(self, text="U:")
        self.labelP = Label(self, text="P:")

        self.mailrecipient = 'GoldenSights'

        self.entryUsername = Entry(self)
        self.entryUsername.focus_set()
        self.entryUsername.bind('<Return>',
                                lambda event: self.entryPassword.focus_set())

        self.entryPassword = Entry(self)
        self.entryPassword.config(show='•')
        self.entryPassword.bind(
            '<Return>', lambda event: self.login(self.entryUsername.get(),
                                                 self.entryPassword.get()))

        self.newbutton = Button(
            self,
            text="Login",
            command=lambda: self.login(self.entryUsername.get(),
                                       self.entryPassword.get()))
        self.newbutton.bind(
            '<Return>', lambda event: self.login(self.entryUsername.get(),
                                                 self.entryPassword.get()))
        self.newbutton.config(width=6)
        self.quitbutton = Button(self,
                                 text="Quit",
                                 command=lambda: self.quit())
        self.quitbutton.config(width=6)

        self.labelU.grid(row=0, column=0, padx=0)
        self.entryUsername.grid(row=0, column=1)
        self.labelP.grid(row=1, column=0)
        self.entryPassword.grid(row=1, column=1, pady=4)
        self.newbutton.grid(row=2, column=1)
        self.quitbutton.grid(row=3, column=1, pady=4)

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

        self.indicatorGreen = PhotoImage(file="indicatorGreen.gif")
        self.indicatorRed = PhotoImage(file="indicatorRed.gif")
        self.indicatorBlue = PhotoImage(file="indicatorBlue.gif")
        self.indicatorBlack = PhotoImage(file="indicatorBlack.gif")

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

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

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

    def login(self, username, password):
        print('U: ' + username)
        self.username = username
        if username == '' or not all(
                char in string.ascii_letters + string.digits + '_-'
                for char in username):
            print('Please enter a username')
            self.entryUsername.focus_set()
            self.labelErrorPointer.grid(row=0, column=2)
        elif password == '':
            print('Please enter a password')
            self.entryPassword.focus_set()
            self.labelErrorPointer.grid(row=1, column=2)

        else:
            self.labelErrorPointer.grid_forget()
            print('Attempting login for ' + username)
            try:
                self.USERAGENT = username + ' practices Tkinter+PRAW mixing with utility by /u/GoldenSights.'
                self.r = praw.Reddit(self.USERAGENT)
                #self.r.login(username, password)
                print('Success')
                self.labelU.grid_forget()
                self.labelP.grid_forget()
                self.entryUsername.grid_forget()
                self.entryPassword.grid_forget()
                self.newbutton.grid_forget()
                self.quitbutton.grid_forget()
                self.usernamelabel = Label(self,
                                           text=username + ', Sending to /u/' +
                                           self.mailrecipient)
                self.usernamelabel.grid(row=0, column=0, columnspan=8)
                self.quitbutton.grid(row=900, column=0)

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

                self.optionDiscuss = "Discussion Flair + Crossposting"
                self.optionRegister = "Register a new Candidate"

                self.prevmode = self.optionDiscuss
                self.curmode = self.optionDiscuss
                self.optionvar = tkinter.StringVar(self)
                self.optionvar.trace("w", self.permaloop)
                self.optionvar.set(self.optionDiscuss)
                self.option = OptionMenu(self, self.optionvar,
                                         self.optionDiscuss,
                                         self.optionRegister, "three", "four")
                self.newbutton.unbind("<Return>")
                self.entryUsername.unbind("<Return>")
                self.entryPassword.unbind("<Return>")
                self.option.grid(row=1, column=0, columnspan=8, pady=8)
                self.updategui(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(True)

    def updategui(self, *args):
        if args[0] == 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.optionDiscuss:
                self.newrowindex = 4
                self.labelPermalink = Label(self, text="Thread Permalink:")
                self.entryPermalink = Entry(self)
                self.rowconfigure(2, weight=2)
                self.labelPermalink.grid(row=2, column=0)
                self.entryPermalink.grid(row=2, column=1)
                self.labelcrossposting = Label(self, text="Crosspost to:")
                self.labelcrossposting.grid(row=3,
                                            column=0,
                                            columnspan=2,
                                            sticky="w")

                for m in range(5):
                    self.redditlabel = Label(self, text="/r/")
                    self.redditlabel.grid(row=self.newrowindex,
                                          column=0,
                                          sticky="e")
                    self.labellist.append(self.redditlabel)

                    self.redditentry = Entry(self)
                    self.redditentry.grid(row=self.newrowindex, column=1)
                    self.entrylist.append(self.redditentry)

                    self.newrowindex += 1

                self.morerowbutton = Button(
                    self,
                    text="+row",
                    command=lambda: self.morerows('/r/', 0, 1, 20))
                self.morerowbutton.grid(row=898, column=0, columnspan=2)

                self.verifybutton = Button(
                    self, text="Verify", command=lambda: self.updategui(False))
                self.verifybutton.grid(row=899, column=0, columnspan=2)

                self.newrowindex += 2

                self.misclist.append(self.labelPermalink)
                self.misclist.append(self.labelcrossposting)
                self.misclist.append(self.entryPermalink)
                self.misclist.append(self.morerowbutton)
                self.misclist.append(self.verifybutton)

            if self.curmode == self.optionRegister:
                self.newrowindex = 6
                self.labelCanUsername = Label(
                    self, text="Candidate's Username:  /u/")
                self.entryCanUsername = Entry(self)
                self.labelCanRealname = Label(self,
                                              text="Candidate's Realname:")
                self.entryCanRealname = Entry(self)
                self.labelCanFlair = Label(self, text="Candidate's Flair:")
                self.entryCanFlair = Entry(self)
                self.entryMo = Spinbox(
                    self,
                    width=9,
                    values=('January', 'February', 'March', 'April', 'May',
                            'June', 'July', 'August', 'September', 'October',
                            'November', 'December'))
                self.entryDa = Spinbox(self, width=2, from_=1, to=31)
                self.entryYr = Spinbox(self, width=4, from_=2014, to=2500)
                self.labelHH = Label(self, text="Schedule time UTC:")
                self.entryHH = Spinbox(self, from_=0, to=23, width=2)
                self.entryMM = Spinbox(self, from_=0, to=59, width=2)
                self.entryYr.delete(0, 'end')
                self.entryYr.insert(0, 2014)

                self.morerowbutton = Button(
                    self,
                    text="+question",
                    command=lambda: self.morerows('Q:', 0, 1, 25))
                self.morerowbutton.grid(row=898, column=0, columnspan=8)

                self.verifybutton = Button(
                    self, text="Verify", command=lambda: self.updategui(False))
                self.verifybutton.grid(row=899, column=0, columnspan=8)

                self.misclist.append(self.labelCanUsername)
                self.misclist.append(self.labelCanRealname)
                self.misclist.append(self.entryCanUsername)
                self.misclist.append(self.entryCanRealname)
                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.morerowbutton)
                self.misclist.append(self.verifybutton)

                self.labelCanUsername.grid(row=2, column=0, sticky="e")
                self.labelCanRealname.grid(row=3, column=0, sticky="e")
                self.labelCanFlair.grid(row=4, column=0, sticky="e")
                self.entryCanUsername.grid(row=2, column=1, columnspan=3)
                self.entryCanRealname.grid(row=3, column=1, columnspan=3)
                self.entryCanFlair.grid(row=4, column=1, columnspan=3)
                self.entryMo.grid(row=5, column=1, sticky="e")
                self.entryDa.grid(row=5, column=2)
                self.entryYr.grid(row=5, column=3)
                self.labelHH.grid(row=5, column=0, sticky="se", pady=5)
                self.entryHH.grid(row=6, column=1, sticky="e")
                self.entryMM.grid(row=6, column=2, sticky="w")
        else:
            if self.curmode == self.optionDiscuss:

                verifies = []

                i = self.entryPermalink.get()
                if len(i) == 6:
                    pid = i
                else:
                    if 'www.reddit.com/r/' in i and '/comments/' in i:
                        pid = i.split('/comments/')[1].split('/')[0]
                    if 'http://redd.it/' in i:
                        pid = i.split('redd.it/')[1]

                for flag in self.verifylist:
                    flag.grid_forget()
                    self.verifylist.remove(flag)

                try:
                    print('Fetching Submission ' + pid)
                    self.r.get_info(thing_id="t3_" + pid).title + 'Check'
                    self.redditlabel = Label(self, image=self.indicatorGreen)
                    self.redditlabel.grid(row=2, column=2)
                    self.verifylist.append(self.redditlabel)
                    verifies.append(True)
                    print('\tSuccess')
                except:
                    print(
                        'Failed. Make sure to include the http://. Copy and paste straight from your browser for best result'
                    )
                    self.redditlabel = Label(self, image=self.indicatorRed)
                    self.redditlabel.grid(row=2, column=2)
                    self.verifylist.append(self.redditlabel)
                    verifies.append(False)

                for entry in self.entrylist:
                    i = entry.get()
                    if i != '':
                        print('Fetching /r/' + i)
                        if all(char in string.ascii_letters + string.digits +
                               '_-' for char in i):
                            try:
                                sub = self.r.get_subreddit(i, fetch=True)
                                self.redditlabel = Label(
                                    self, image=self.indicatorGreen)
                                self.redditlabel.grid(
                                    row=entry.grid_info()['row'], column=2)
                                self.verifylist.append(self.redditlabel)
                                verifies.append(True)
                                print('\tSuccess')
                            except:
                                self.redditlabel = Label(
                                    self, image=self.indicatorRed)
                                self.redditlabel.grid(
                                    row=entry.grid_info()['row'], column=2)
                                self.verifylist.append(self.redditlabel)
                                verifies.append(False)
                                print('\tFailed')
                            time.sleep(2)
                        else:
                            self.redditlabel = Label(self,
                                                     image=self.indicatorRed)
                            self.redditlabel.grid(row=entry.grid_info()['row'],
                                                  column=2)
                            self.verifylist.append(self.redditlabel)
                            verifies.append(False)
                            print('\tFailed')

                print(verifies)

            if self.curmode == self.optionRegister:

                verifies = []
                u = self.entryCanUsername.get()
                print('Fetching /u/' + u)
                if not all(char in string.ascii_letters + string.digits + '_-'
                           for char in u):
                    self.redditlabel = Label(self, image=self.indicatorRed)
                    self.redditlabel.grid(row=2, column=4)
                    self.verifylist.append(self.redditlabel)
                    verifies.append(False)
                    print('\tBad characterage')
                else:
                    try:
                        u = self.r.get_redditor(u)
                        print(u)
                        self.redditlabel = Label(self,
                                                 image=self.indicatorGreen)
                        self.redditlabel.grid(row=2, column=4)
                        self.verifylist.append(self.redditlabel)
                        verifies.append(True)
                        print('\tSuccess')
                    except:
                        self.redditlabel = Label(self, image=self.indicatorRed)
                        self.redditlabel.grid(row=2, column=4)
                        self.verifylist.append(self.redditlabel)
                        verifies.append(False)
                        print('\tFailed')

                try:
                    print('Checking Time')
                    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 = datetime.datetime.utcfromtimestamp(
                        plandate.timestamp())
                    print('\t' + str(plandate.timestamp()))

                    self.redditlabel = Label(self, image=self.indicatorGreen)
                    self.redditlabel.grid(row=5, column=3)
                    self.verifylist.append(self.redditlabel)
                    verifies.append(True)
                except:
                    print('\tFailed')
                    self.redditlabel = Label(self, image=self.indicatorRed)
                    self.redditlabel.grid(row=5, column=3)
                    self.verifylist.append(self.redditlabel)
                    verifies.append(False)

                print(verifies)

    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)
コード例 #25
0
class painel_config_view(Toplevel):
    def __init__(self, controller):
        super().__init__(padx=10, pady=10)
        self.update()
        self.deiconify()
        self.resizable(False, False)
        self.controller = controller
        self.range_spinBox = models_app.range_freq()
        self.range_spinBox.load()

        self.buttonCancel = ttk.Button(self,
                                       command=self.cancel_config,
                                       text='Cancelar')
        self.buttonCancel.grid(row=3, column=0, sticky='WEN', padx=11)

        self.frame1 = LabelFrame(self, text='Experimento da onda na corda')
        self.frame1.grid(row=1,
                         column=0,
                         padx=11,
                         pady=11,
                         ipady=11,
                         sticky='N')
        self.label_frame1 = ttk.Label(self.frame1,
                                      text='Alterar resolução da frequência:')
        self.label_frame1.grid(column=0, row=0, columnspan=2)

        self.label_spinbox1_frame1 = ttk.Label(
            self.frame1, text='Frequencia inicial: (Hz) ')
        self.label_spinbox1_frame1.grid(row=1, column=0)
        self.spinbox1_frame1 = Spinbox(self.frame1,
                                       from_=self.range_spinBox.corda_from,
                                       to=self.range_spinBox.corda_to)
        self.spinbox1_frame1.grid(column=0, row=2, pady=10, padx=11)

        self.label_spinbox2_frame1 = ttk.Label(self.frame1,
                                               text='Frequencia final: (Hz) ')
        self.label_spinbox2_frame1.grid(row=1, column=1)
        self.spinbox2_frame1 = Spinbox(self.frame1,
                                       from_=self.range_spinBox.corda_from,
                                       to=self.range_spinBox.corda_to)
        self.spinbox2_frame1.grid(column=1, row=2, pady=10, padx=11)
        self.spinbox2_frame1.delete(0, "end")
        self.spinbox2_frame1.insert(0, str(self.range_spinBox.corda_to))

        self.button1_frame1 = ttk.Button(self.frame1,
                                         text='Salvar alterações',
                                         command=self.save_config)
        self.button1_frame1.grid(row=3,
                                 column=0,
                                 pady=10,
                                 padx=11,
                                 sticky='we')
        self.button2_frame1 = ttk.Button(self.frame1,
                                         text='Restaurar valores padrão',
                                         command=self.restore_config_corda)
        self.button2_frame1.grid(row=3,
                                 column=1,
                                 pady=10,
                                 padx=11,
                                 sticky='we')

        self.frame2 = LabelFrame(self,
                                 text='Experimento da onda na superfície')
        self.frame2.grid(row=2,
                         column=0,
                         padx=11,
                         pady=11,
                         ipady=11,
                         sticky='N')
        self.label_frame2 = ttk.Label(self.frame2,
                                      text='Alterar resolução da frequência:')
        self.label_frame2.grid(column=0, row=0, columnspan=2)

        self.label_spinbox1_frame2 = ttk.Label(
            self.frame2, text='Frequencia inicial: (Hz) ')
        self.label_spinbox1_frame2.grid(row=1, column=0)
        self.spinbox1_frame2 = Spinbox(self.frame2,
                                       from_=self.range_spinBox.sup_from,
                                       to=self.range_spinBox.sup_to)
        self.spinbox1_frame2.grid(column=0, row=2, pady=10, padx=11)

        self.label_spinbox2_frame2 = ttk.Label(self.frame2,
                                               text='Frequencia final: (Hz) ')
        self.label_spinbox2_frame2.grid(row=1, column=1)
        self.spinbox2_frame2 = Spinbox(self.frame2,
                                       from_=self.range_spinBox.sup_from,
                                       to=self.range_spinBox.sup_to)
        self.spinbox2_frame2.grid(column=1, row=2, pady=10, padx=11)
        self.spinbox2_frame2.delete(0, "end")
        self.spinbox2_frame2.insert(0, str(self.range_spinBox.sup_to))

        self.button1_frame2 = ttk.Button(self.frame2,
                                         text='Salvar alterações',
                                         command=self.save_config)
        self.button1_frame2.grid(row=3,
                                 column=0,
                                 pady=10,
                                 padx=11,
                                 sticky='we')
        self.button2_frame2 = ttk.Button(self.frame2,
                                         text='Restaurar valores padrão',
                                         command=self.restore_config_sup)
        self.button2_frame2.grid(row=3,
                                 column=1,
                                 pady=10,
                                 padx=11,
                                 sticky='we')

        self.padroesView = padroes_view(self, self.controller)
        self.padroesView.grid(row=1, column=1, rowspan=10)

    def cancel_config(self):
        self.destroy()

    def restore_config_corda(self):
        #O range é restaurado:
        self.controller.restore_model(self.range_spinBox, tipo='corda')
        #SpinBox são reiniciadas:
        self.spinbox1_frame1.delete(0, "end")
        self.spinbox1_frame1.insert(0, str(self.range_spinBox.corda_from))
        self.spinbox2_frame1.delete(0, "end")
        self.spinbox2_frame1.insert(0, str(self.range_spinBox.corda_to))

    def restore_config_sup(self):
        # O range é restaurado:
        self.controller.restore_model(self.range_spinBox, tipo='sup')

        self.spinbox1_frame2.delete(0, "end")
        self.spinbox1_frame2.insert(0, str(self.range_spinBox.sup_from))
        self.spinbox2_frame2.delete(0, "end")
        self.spinbox2_frame2.insert(0, str(self.range_spinBox.sup_to))

    def save_config(self):
        corda_from = self.spinbox1_frame1.get()
        corda_to = self.spinbox2_frame1.get()
        sup_from = self.spinbox1_frame2.get()
        sup_to = self.spinbox2_frame2.get()
        self.controller.update_model(self.range_spinBox,
                                     corda_from=corda_from,
                                     corda_to=corda_to,
                                     sup_from=sup_from,
                                     sup_to=sup_to)

    def update_view(self):
        self.padroesView.update_view()
        self.update()
        self.deiconify()

    def altera_exp(self):
        self.controller.show_frame('padroes_view')
コード例 #26
0
ファイル: scheduleclient.py プロジェクト: A-J-/reddit
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)
コード例 #27
0
ファイル: 3.03.py プロジェクト: joyfish/Programas
class DrumMachine:

    def __init__(self, root):
        self.root = root
        self.root.title(PROGRAM_NAME)
        self.all_patterns = [None] * MAX_NUMBER_OF_PATTERNS
        self.beats_per_minute = INITIAL_BEATS_PER_MINUTE
        self.current_pattern_index = 0
        self.drum_load_entry_widget = [None] * MAX_NUMBER_OF_DRUM_SAMPLES
        self.init_all_patterns()
        self.init_gui()

    def init_all_patterns(self):
        self.all_patterns = [
            {
                'list_of_drum_files': [None] * MAX_NUMBER_OF_DRUM_SAMPLES,
                'number_of_units': INITIAL_NUMBER_OF_UNITS,
                'bpu': INITIAL_BPU,
                'is_button_clicked_list':
                self.init_is_button_clicked_list(
                    MAX_NUMBER_OF_DRUM_SAMPLES,
                    INITIAL_NUMBER_OF_UNITS * INITIAL_BPU
                )
            }
            for k in range(MAX_NUMBER_OF_PATTERNS)]

    def on_pattern_changed(self):
        pass

    def on_number_of_units_changed(self):
        pass

    def on_bpu_changed(self):
        pass

    def on_open_file_button_clicked(self, drum_index):
        pass

    def on_play_button_clicked(self):
        pass

    def on_stop_button_clicked(self):
        pass

    def on_loop_button_toggled(self):
        pass

    def on_beats_per_minute_changed(self):
        pass

    def init_is_button_clicked_list(self, num_of_rows, num_of_columns):
        return [[False] * num_of_columns for x in range(num_of_rows)]

    def get_button_value(self, row, col):
        return self.all_patterns[self.current_pattern_index][
            'is_button_clicked_list'][row][col]

    def find_number_of_columns(self):
        return int(self.number_of_units_widget.get()) * int(self.bpu_widget.get())

    def process_button_clicked(self, row, col):
        self.set_button_value(row, col, not self.get_button_value(row, col))
        self.display_button_color(row, col)

    def set_button_value(self, row, col, bool_value):
        self.all_patterns[self.current_pattern_index][
            'is_button_clicked_list'][row][col] = bool_value

    def on_button_clicked(self, row, col):
        def event_handler():
            self.process_button_clicked(row, col)
        return event_handler

    def display_all_button_colors(self):
        number_of_columns = self.find_number_of_columns()
        for r in range(MAX_NUMBER_OF_DRUM_SAMPLES):
            for c in range(number_of_columns):
                self.display_button_color(r, c)

    def display_button_color(self, row, col):
        bpu = int(self.bpu_widget.get())
        original_color = COLOR_1 if ((col//bpu) % 2) else COLOR_2
        button_color = BUTTON_CLICKED_COLOR if self.get_button_value(
            row, col) else original_color
        self.buttons[row][col].config(background=button_color)

    def create_play_bar(self):
        playbar_frame = Frame(self.root, height=15)
        start_row = MAX_NUMBER_OF_DRUM_SAMPLES + 10
        playbar_frame.grid(row=start_row, columnspan=13,
                           sticky=W + E, padx=15, pady=10)
        self.play_icon = PhotoImage(file="images/play.gif")
        self.play_button = Button(
            playbar_frame, text='Play',  image=self.play_icon, compound='left', command=self.on_play_button_clicked)
        self.play_button.grid(row=start_row, column=1, padx=2)
        Button(playbar_frame, text='Stop', command=self.on_stop_button_clicked).grid(
            row=start_row, column=3, padx=2)
        self.loopbutton = Checkbutton(
            playbar_frame, text='Loop', command=self.on_loop_button_toggled, textvariable=True)
        self.loopbutton.grid(row=start_row, column=16, padx=5)
        Label(playbar_frame, text='Beats Per Minute').grid(
            row=start_row, column=25)
        self.beats_per_minute_widget = Spinbox(playbar_frame, from_=MIN_BEATS_PER_MINUTE, to=MAX_BEATS_PER_MINUTE, width=5,
                increment=5.0, command=self.on_beats_per_minute_changed)
        self.beats_per_minute_widget.grid(row=start_row, column=30)
        self.beats_per_minute_widget.delete(0,"end")
        self.beats_per_minute_widget.insert(0,INITIAL_BEATS_PER_MINUTE)
        photo = PhotoImage(file='images/signature.gif')
        label = Label(playbar_frame, image=photo)
        label.image = photo
        label.grid(row=start_row, column=50, padx=1, sticky='w')

    def create_right_button_matrix(self):
        right_frame = Frame(self.root)
        right_frame.grid(row=10, column=6, sticky=W +
                         E + N + S, padx=15, pady=4)
        self.buttons = [[None for x in range(
            self.find_number_of_columns())] for x in range(MAX_NUMBER_OF_DRUM_SAMPLES)]
        for row in range(MAX_NUMBER_OF_DRUM_SAMPLES):
            for col in range(self.find_number_of_columns()):
                self.buttons[row][col] = Button(
                    right_frame, command=self.on_button_clicked(row, col))
                self.buttons[row][col].grid(row=row, column=col)
                self.display_button_color(row, col)

    def create_left_drum_loader(self):
        left_frame = Frame(self.root)
        left_frame.grid(row=10, column=0, columnspan=6, sticky=W + E + N + S)
        open_file_icon = PhotoImage(file='images/openfile.gif')
        for i in range(MAX_NUMBER_OF_DRUM_SAMPLES):
            open_file_button = Button(left_frame, image=open_file_icon,
                                      command=self.on_open_file_button_clicked(i))
            open_file_button.image = open_file_icon
            open_file_button.grid(row=i, column=0,  padx=5, pady=4)
            self.drum_load_entry_widget[i] = Entry(left_frame)
            self.drum_load_entry_widget[i].grid(
                row=i, column=4, padx=7, pady=4)

    def create_top_bar(self):
        topbar_frame = Frame(self.root, height=25)
        topbar_frame.grid(row=0, columnspan=12, rowspan=10, padx=5, pady=5)

        Label(topbar_frame, text='Pattern Number:').grid(row=0, column=1)
        self.pattern_index_widget = Spinbox(topbar_frame, from_=0, to=MAX_NUMBER_OF_PATTERNS - 1, width=5,
                command=self.on_pattern_changed)
        self.pattern_index_widget.grid(row=0, column=2)
        self.current_pattern_name_widget = Entry(topbar_frame)
        self.current_pattern_name_widget.grid(row=0, column=3, padx=7, pady=2)

        Label(topbar_frame, text='Number of Units:').grid(row=0, column=4)
        self.number_of_units_widget = Spinbox(topbar_frame, from_=1, to=MAX_NUMBER_OF_UNITS, width=5,
                command=self.on_number_of_units_changed)
        self.number_of_units_widget.delete(0,"end")
        self.number_of_units_widget.insert(0,INITIAL_NUMBER_OF_UNITS)
        self.number_of_units_widget.grid(row=0, column=5)
        Label(topbar_frame, text='BPUs:').grid(row=0, column=6)
        self.bpu_widget = Spinbox(topbar_frame, from_=1, to=MAX_BPU, width=5,
                command=self.on_bpu_changed)
        self.bpu_widget.grid(row=0, column=7)
        self.bpu_widget.delete(0,"end")
        self.bpu_widget.insert(0,INITIAL_BPU)


    def create_top_menu(self):
        self.menu_bar = Menu(self.root)
        self.file_menu = Menu(self.menu_bar, tearoff=0)
        self.file_menu.add_command(label="Load Project")
        self.file_menu.add_command(label="Save Project")
        self.file_menu.add_separator()
        self.file_menu.add_command(label="Exit")
        self.menu_bar.add_cascade(label="File", menu=self.file_menu)
        self.about_menu = Menu(self.menu_bar, tearoff=0)
        self.about_menu.add_command(label="About")
        self.menu_bar.add_cascade(label="About", menu=self.about_menu)
        self.root.config(menu=self.menu_bar)

    def init_gui(self):
        self.create_top_menu()
        self.create_top_bar()
        self.create_left_drum_loader()
        self.create_right_button_matrix()
        self.create_play_bar()
コード例 #28
0
class SettingsForm:
    """TODO: INSERT DOCSTRING."""
    def __init__(self):
        """TODO: INSERT DOCSTRING."""
        self.form = tk.Tk()
        self.form.geometry(INIT_SCREEN_SIZE)
        self.form.minsize(MIN_SCREEN_SIZE[0], MIN_SCREEN_SIZE[1])
        self.form.title(SCREEN_TITLE)

        # Store the last status of the directory path to determine if the
        # directory changed in order to update the file display boxes.
        self.last_dir_path: str = Settings.directory_path

        # Each file in the current directory is stored as the key of a
        # dictionary, with each key mapping to a bool of if that file
        # is enabled or not.
        self.all_files: Dict[str, bool] = {}
        self.load_all_files()

        # Create the main frame to hold all the elements.
        self.frame: Frame = Frame(self.form, background=LIGHT_GRAY)
        # Make the main frame fit the size of the window.
        self.frame.pack(fill=BOTH, expand=1)

        # Track the most recenly selected item in the active files and disabled
        # files listboxes.
        self.sel_item_in_active_files: int = 0
        self.sel_item_in_disabled_files: int = 0

        self.create_widgets()

    def create_widgets(self):
        """Create all form elements, and populate the form.

        This should only be called once when the form is being created.
        """
        #
        # Form Layout Hierarchy:
        #
        #     Main Frame
        #     |---File Frame
        #     |   |---Active Files
        #     |   |---File Button Frame
        #     |   |   |---Activate Button
        #     |   |   |---Disable Button
        #     |   |---Disable Files
        #     |---Content Frame
        #     |   |---Directory Frame
        #     |   |   |---Directory Label
        #     |   |   |---Directory Input
        #     |   |---Font Size Frame
        #     |   |   |---Font Size Label
        #     |   |   |---Font Size Input
        #     |   |---Typeface Frame
        #     |   |   |---Typeface Label
        #     |   |   |---Typeface Input
        #     |   |---Theme Frame
        #     |   |   |---Theme Label
        #     |   |   |---Theme Input
        #     |   |---Display Item Frame
        #     |   |   |---Display Item Label
        #     |   |   |---Display Item Input
        #     |   |---Button Frame
        #     |   |   |---Save Button
        #     |   |   |---Cancel Button
        #

        # ----- FILE SELECTOR -----
        self.file_frame = Frame(self.frame, background=LIGHT_GRAY)
        self.file_frame.pack(fill=BOTH, expand=1, side=LEFT, padx=5, pady=5)

        self.active_files = Listbox(self.file_frame,
                                    relief=FLAT,
                                    foreground=BLACK,
                                    background=WHITE,
                                    highlightthickness=0)
        self.active_files.pack(fill=BOTH, expand=1, padx=5, pady=5)
        self.refresh_active_files()

        self.file_button_frame = Frame(self.file_frame, background=LIGHT_GRAY)
        self.file_button_frame.pack(fill=BOTH, expand=0, padx=5, pady=5)

        self.activate_button = Button(self.file_button_frame,
                                      text='▲',
                                      relief=FLAT,
                                      foreground=BLACK,
                                      background=MEDIUM_GRAY,
                                      command=self.activate_callback,
                                      highlightthickness=0)
        self.activate_button.pack(fill=BOTH,
                                  expand=1,
                                  side=LEFT,
                                  padx=5,
                                  pady=5)

        self.disable_button = Button(self.file_button_frame,
                                     text='▼',
                                     relief=FLAT,
                                     foreground=BLACK,
                                     background=MEDIUM_GRAY,
                                     command=self.disable_callback,
                                     highlightthickness=0)
        self.disable_button.pack(fill=BOTH,
                                 expand=1,
                                 side=RIGHT,
                                 padx=5,
                                 pady=5)

        self.disabled_files = Listbox(self.file_frame,
                                      relief=FLAT,
                                      foreground=BLACK,
                                      background=WHITE,
                                      highlightthickness=0)
        self.disabled_files.pack(fill=BOTH, expand=1, padx=5, pady=5)
        self.refresh_disabled_files()
        # ------------------------------

        self.content_frame = Frame(self.frame, background=LIGHT_GRAY)
        self.content_frame.pack(fill=Y, expand=0, side=RIGHT, padx=5, pady=10)

        # ----- DIRECTORY SETTING -----
        self.directory_frame = Frame(self.content_frame, background=LIGHT_GRAY)
        self.directory_frame.pack(fill=X, expand=0, side=TOP, padx=5, pady=10)

        self.directory_label = Label(self.directory_frame,
                                     text='Directory: ',
                                     font=DEFAULT_FONT,
                                     background=LIGHT_GRAY,
                                     foreground=BLACK)
        self.directory_label.pack(side=LEFT)

        self.directory_input = Entry(self.directory_frame,
                                     text='null',
                                     font=DEFAULT_FONT,
                                     background=WHITE,
                                     relief=FLAT,
                                     width=DEFAULT_WIDTH,
                                     foreground=BLACK,
                                     highlightthickness=0)
        self.directory_input.pack(side=LEFT)
        self.directory_input.insert(0, Settings.directory_path)
        # ------------------------------

        # ----- FONT SIZE SETTING -----
        self.font_size_frame = Frame(self.content_frame, background=LIGHT_GRAY)
        self.font_size_frame.pack(fill=X, expand=0, side=TOP, padx=5, pady=10)

        self.font_size_label = Label(self.font_size_frame,
                                     text='Font Size:',
                                     font=DEFAULT_FONT,
                                     background=LIGHT_GRAY,
                                     foreground=BLACK)
        self.font_size_label.pack(side=LEFT, anchor=SW)

        self.font_size_input = Scale(self.font_size_frame,
                                     orient=HORIZONTAL,
                                     font=DEFAULT_FONT,
                                     background=WHITE,
                                     relief=FLAT,
                                     from_=4,
                                     to=140,
                                     sliderlength=20,
                                     resolution=4,
                                     length=175,
                                     foreground=BLACK,
                                     highlightthickness=0)
        self.font_size_input.pack(side=LEFT)
        self.font_size_input.set(Settings.font_size)
        # ------------------------------

        # ----- TYPEFACE SETTING -----
        self.typeface_frame = Frame(self.content_frame, background=LIGHT_GRAY)
        self.typeface_frame.pack(fill=X, expand=0, side=TOP, padx=5, pady=10)

        self.typeface_label = Label(self.typeface_frame,
                                    text='Typeface: ',
                                    font=DEFAULT_FONT,
                                    background=LIGHT_GRAY,
                                    foreground=BLACK)
        self.typeface_label.pack(side=LEFT)

        self.typeface_input = Entry(self.typeface_frame,
                                    text='Verdana',
                                    font=DEFAULT_FONT,
                                    width=DEFAULT_WIDTH,
                                    background=WHITE,
                                    relief=FLAT,
                                    foreground=BLACK,
                                    highlightthickness=0)
        self.typeface_input.pack(side=LEFT)
        self.typeface_input.insert(0, Settings.typeface)
        # ------------------------------

        # ----- THEME SETTING -----
        self.theme_frame = Frame(self.content_frame, background=LIGHT_GRAY)
        self.theme_frame.pack(fill=X, expand=0, side=TOP, padx=5, pady=10)

        self.theme_label = Label(self.theme_frame,
                                 text='Theme: ',
                                 font=DEFAULT_FONT,
                                 background=LIGHT_GRAY,
                                 foreground=BLACK)
        self.theme_label.pack(side=LEFT)

        self.theme_input = Listbox(self.theme_frame,
                                   font=DEFAULT_FONT,
                                   background=WHITE,
                                   relief=FLAT,
                                   height=len(Settings.theme_names) + 3,
                                   width=DEFAULT_WIDTH + 2,
                                   foreground=BLACK,
                                   highlightthickness=0)
        self.theme_input.pack(side=LEFT)
        self.theme_input.insert(
            END, CURRENT_THEME_STR.format(Settings.current_theme))
        self.theme_input.insert(END, '')
        for theme_name in Settings.theme_names:
            self.theme_input.insert(END, theme_name)
        self.theme_input.select_set(0)
        # ------------------------------

        # ----- ITEM RANGE -----
        self.display_item_frame = Frame(self.content_frame,
                                        background=LIGHT_GRAY)
        self.display_item_frame.pack(fill=X,
                                     expand=0,
                                     side=TOP,
                                     padx=5,
                                     pady=10)

        self.display_item_label = Label(self.display_item_frame,
                                        text='Display Item: ',
                                        font=DEFAULT_FONT,
                                        background=LIGHT_GRAY,
                                        foreground=BLACK)
        self.display_item_label.pack(side=LEFT)

        self.display_item_input = Spinbox(self.display_item_frame,
                                          from_=-1,
                                          to=100,
                                          font=DEFAULT_FONT,
                                          width=DEFAULT_WIDTH - 4,
                                          background=WHITE,
                                          relief=FLAT,
                                          foreground=BLACK,
                                          highlightthickness=0)
        self.display_item_input.pack(side=LEFT)
        self.display_item_input.delete(0, END)
        self.display_item_input.insert(0, Settings.display_item)
        # ------------------------------

        # ----- SAVE AND CANCEL BUTTONS -----
        self.button_frame = Frame(self.content_frame, background=LIGHT_GRAY)
        self.button_frame.pack(fill=X, expand=0, side=BOTTOM, padx=10, pady=10)

        self.save_button = Button(self.button_frame,
                                  text='Save & Quit',
                                  background=MEDIUM_GRAY,
                                  relief=FLAT,
                                  command=self.save_callback,
                                  foreground=BLACK,
                                  highlightthickness=0)
        self.save_button.pack(side=RIGHT, padx=3, pady=3)

        self.cancel_button = Button(self.button_frame,
                                    text='Cancel',
                                    background=MEDIUM_GRAY,
                                    relief=FLAT,
                                    command=self.cancel_callback,
                                    foreground=BLACK,
                                    highlightthickness=0)
        self.cancel_button.pack(side=LEFT, padx=3, pady=3)
        # ------------------------------

    def cancel_callback(self) -> None:
        """Restore the previous saved settings and close the form."""
        FileReader.load_settings()
        self.form.destroy()

    def save_callback(self) -> None:
        """Save the newly updated settings and close the form."""
        FileReader.save_settings()
        self.form.destroy()

    def activate_callback(self) -> None:
        """Take currently selected 'disabled' file and sets it to 'enabled'."""
        # Get and save the index of the currently selected item if it exists,
        # this allows for the next item to be automatically selected after the
        # currently selected item is transfered, allowing for rapid item
        # activation.
        current_selection: tuple = self.disabled_files.curselection()
        if len(current_selection) > 0:
            self.sel_item_in_disabled_files = current_selection[0]

        file: str = str(self.disabled_files.get(ACTIVE))
        if file in self.all_files.keys():
            self.all_files[file] = True
        # Update the file display text boxes.
        self.refresh_active_files()
        self.refresh_disabled_files()
        self.disabled_files.activate(self.sel_item_in_disabled_files)

    def disable_callback(self) -> None:
        """Take currently selected 'enabled' file and sets it to 'disabled'."""
        # Get and save the index of the currently selected item if it exists,
        # this allows for the next item to be automatically selected after the
        # currently selected item is transfered, allowing for rapid item
        # deactivation.
        current_selection: tuple = self.active_files.curselection()
        if len(current_selection) > 0:
            self.sel_item_in_active_files = current_selection[0]

        file: str = str(self.active_files.get(ACTIVE))
        if file in self.all_files.keys():
            self.all_files[file] = False
        # Update the file display text boxes.
        self.refresh_active_files()
        self.refresh_disabled_files()
        self.active_files.activate(self.sel_item_in_active_files)

    def refresh_active_files(self) -> None:
        """Clear and fill active files text box with current active files.

        This refreshes the data in the text box. Replacing the old data with
        the new data, keeping it up to date.
        """
        self.active_files.delete(0, END)
        self.active_files.insert(END, '       active       ')
        self.active_files.insert(END, '--------------------')
        for file in self.all_files:
            if self.all_files[file]:  # File is active.
                self.active_files.insert(END, file)

    def refresh_disabled_files(self) -> None:
        """Clear and fill disabled files text box with current disabled files.

        This refreshes the data in the text box. Replacing the old data with
        the new data, keeping it up to date.
        """
        self.disabled_files.delete(0, END)
        self.disabled_files.insert(END, '      disabled      ')
        self.disabled_files.insert(END, '--------------------')
        for file in self.all_files:
            if not self.all_files[file]:  # File is disabled.
                self.disabled_files.insert(END, file)

    def load_all_files(self) -> None:
        """Load all files from the current directory into self.all_files.

        This also sets the state if the files are active or disabled.
        """
        dir_path: str = Settings.directory_path
        all_files: Dict[str, bool] = {}
        if os.path.exists(dir_path):
            # Loops through all files in the current directory.
            for file in [
                    f for f in os.listdir(dir_path)
                    if os.path.isfile(os.path.join(dir_path, f))
            ]:
                is_active: bool = file in Settings.active_files
                # Add new file (key) and activity status (value) to all_files
                # dict.
                all_files[file] = is_active
        self.all_files = all_files

    def update_directory_path(self) -> str:
        """Return the current directory in the directory input box.

        Update the current working files and file display boxes if
        a new directory was set.

        Returns:
            str: The directory path to be saved to the settings.
        """
        new_dir_path: str = self.directory_input.get()
        # Update the current working files and file display boxes if the
        # directory changed. This is done to always display the files that
        # are in the current directory.
        if self.last_dir_path != Settings.directory_path:
            self.load_all_files()
            self.refresh_active_files()
            self.refresh_disabled_files()
            self.last_dir_path = Settings.directory_path
        # Set the last directory, then return the new directory to be
        # set the the settings. This makes it so that the elements update
        # from the conditional above. This is because the Settings will be
        # updated after this function returns.
        elif new_dir_path != Settings.directory_path:
            self.last_dir_path = Settings.directory_path
            return new_dir_path
        return Settings.directory_path

    def update_theme(self) -> str:
        """Return the current theme in the theme input box.

        Use current theme if new theme isn't valid (i.e. title portion), and
        update the currenly selected theme in the input box.

        Returns:
            str: The name of the new theme to be saved to the settings.
        """
        # Get the current selected theme from the Listbox. If the theme
        # is not valid, set it to the current theme so that a valid theme
        # is always used.
        theme_name: str = str(self.theme_input.get(ACTIVE))
        if theme_name not in Settings.theme_names:
            theme_name = Settings.current_theme
        # Reset the first element of the Listbox which displays the current
        # theme, this shows the user the name of the theme that is currently
        # enabled. This also has the side effect of that element not being
        # able to be selected (which doesn't change anything).
        self.theme_input.delete(0)
        self.theme_input.insert(
            0, CURRENT_THEME_STR.format(Settings.current_theme))

        return theme_name

    def update_settings(self) -> None:
        """Set all of the current form values to the settings."""
        # Get the current directory path.
        dir_path: str = self.update_directory_path()
        # Get the current theme name.
        theme_name: str = self.update_theme()
        # Get all active files.
        active_files: List[str] = [
            f for f in self.all_files if self.all_files[f]
        ]
        # Get the current display item, or 0 if invalid value.
        display_item: int = 0
        try:
            display_item = int(self.display_item_input.get())
        except ValueError:
            pass

        # Update the setings to the new values.
        Settings.set_value({
            "directory_path": dir_path,
            "active_files": active_files,
            "display_item": display_item,
            "font_size": self.font_size_input.get(),
            "typeface": self.typeface_input.get(),
            "current_theme": theme_name,
        })

    def update(self):
        """Update the form screen.

        This is used to update the screen and settings every 'tick' when this
        function is called.
        """
        try:
            self.update_settings()
            self.form.update_idletasks()
            self.form.update()
        except TclError:  # The form has been destroyed (i.e. on exit)
            # Return None so the main form knows this form is no longer active.
            return None
        # Return itself so the main form knows this form is still active.
        return self
コード例 #29
0
class Settings_for_frame(Frame):
    def __init__(self, master, board, tag, board_dims):
        super().__init__(master, bg="#435661")

        self.board = board
        self.board_width, self.board_height = board_dims
        self.tag = tag
        self.background = "white"
        self.record = {}
        self.index = 0
        self.spin_relx = None
        self.spin_rely = None
        self.spin_relw = None
        self.spin_relh = None
        self.label_arguments = None
        self.entry_arguments = None
        self.listbox = None
        self.entry_name = None
        self.set_layout()
        self.set_bindings()
        self.set_listbox()
        self.set_spinboxes()

    def set_layout(self):
        # self-explanatory
        Label(self, background='#435661', text='relx:', foreground='#defffc') \
            .place(relx=0.145, rely=0.0125, relwidth=0.1625, relheight=0.025, anchor='nw')

        Label(self, background='#435661', foreground='#defffc', text='rely:') \
            .place(relx=0.6845, rely=0.0135, relwidth=0.155, relheight=0.0225, anchor='nw')

        Label(self, background='#435661', text='relwidth:', foreground='#defffc') \
            .place(relx=0.044, rely=0.089, relwidth=0.37, relheight=0.02125, anchor='nw')

        Label(self, background='#435661', foreground='#defffc', text='relheight:') \
            .place(relx=0.667, rely=0.0875, relwidth=0.195, relheight=0.02375, anchor='nw')

        self.spin_relx = Spinbox(self,
                                 readonlybackground='#defffc',
                                 highlightthickness=0,
                                 foreground='#435661',
                                 from_=0,
                                 command=self.mod,
                                 to_=1,
                                 increment=0.001,
                                 justify='center')
        self.spin_relx.place(relx=0.085,
                             rely=0.0425,
                             relwidth=0.295,
                             relheight=0.03375,
                             anchor='nw')

        self.spin_rely = Spinbox(self,
                                 readonlybackground='#defffc',
                                 foreground='#435661',
                                 justify='center',
                                 highlightthickness=0,
                                 command=self.mod,
                                 from_=0,
                                 to_=1,
                                 increment=0.001)
        self.spin_rely.place(relx=0.6135,
                             rely=0.0425,
                             relwidth=0.3005,
                             relheight=0.03375,
                             anchor='nw')

        self.spin_relw = Spinbox(self,
                                 readonlybackground='#defffc',
                                 foreground='#435661',
                                 justify='center',
                                 highlightthickness=0,
                                 command=self.mod,
                                 from_=0,
                                 to_=1,
                                 increment=0.001)
        self.spin_relw.place(relx=0.084,
                             rely=0.1175,
                             relwidth=0.295,
                             relheight=0.035,
                             anchor='nw')

        self.spin_relh = Spinbox(self,
                                 readonlybackground='#defffc',
                                 foreground='#435661',
                                 justify='center',
                                 highlightthickness=0,
                                 command=self.mod,
                                 from_=0,
                                 to_=1,
                                 increment=0.001)
        self.spin_relh.place(relx=0.6115,
                             rely=0.1177,
                             relwidth=0.304,
                             relheight=0.035,
                             anchor='nw')

        self.label_arguments = Label(self,
                                     background='#557282',
                                     foreground='#defffc')
        self.label_arguments.place(relx=0.086,
                                   rely=0.1832,
                                   relwidth=0.8305,
                                   relheight=0.06125,
                                   anchor='nw')

        self.entry_arguments = Entry(self,
                                     background='#defffc',
                                     foreground='#435661',
                                     justify='center')
        self.entry_arguments.place(relx=0.22,
                                   rely=0.2625,
                                   relwidth=0.545,
                                   relheight=0.04375,
                                   anchor='nw')

        self.listbox = Listbox(self,
                               background='#557282',
                               foreground='#defffc',
                               borderwidth=0)
        self.listbox.place(relx=0.085,
                           rely=0.3275,
                           relwidth=0.83,
                           relheight=0.4062,
                           anchor='nw')

        myButton(self, command=lambda *a: self.set_value(), text='OK') \
            .place(relx=0.8245, rely=0.2672, relwidth=0.13, relheight=0.0355, anchor='nw')

        Label(self, background='#435661', foreground='#defffc', text='Name:', anchor='w') \
            .place(relx=0.083, rely=0.766, relwidth=0.1205, relheight=0.035, anchor='nw')

        self.entry_name = Entry(self,
                                background='#defffc',
                                foreground='#435661',
                                justify='center')
        self.entry_name.place(relx=0.245,
                              rely=0.7662,
                              relwidth=0.5225,
                              relheight=0.035,
                              anchor='nw')

        myButton(self, command=lambda *a: self.confirm(), text='CONFIRM') \
            .place(relx=0.201, rely=0.8575, relwidth=0.6155, relheight=0.0825, anchor='nw')

    def set_bindings(self):
        # self-explanatory
        self.entry_arguments.bind("<Return>", lambda *a: self.set_value())
        self.listbox.bind("<ButtonRelease-1>",
                          lambda *a: self.listbox_clicked())

    def set_spinboxes(self):
        # self-explanatory
        self.spin_relx.delete(0, "end")
        self.spin_rely.delete(0, "end")
        self.spin_relw.delete(0, "end")
        self.spin_relh.delete(0, "end")

        self.spin_relx.insert("end", self.master.fake_frame_place_info["relx"])
        self.spin_rely.insert("end", self.master.fake_frame_place_info["rely"])
        self.spin_relw.insert("end",
                              self.master.fake_frame_place_info["relwidth"])
        self.spin_relh.insert("end",
                              self.master.fake_frame_place_info["relheight"])

        self.spin_relx.configure(state="readonly")
        self.spin_rely.configure(state="readonly")
        self.spin_relw.configure(state="readonly")
        self.spin_relh.configure(state="readonly")

    def mod(self):
        relx = float(self.spin_relx.get())
        rely = float(self.spin_rely.get())
        relw = float(self.spin_relw.get())
        relh = float(self.spin_relh.get())

        x, y = int(relx * self.board_width), int(rely * self.board_height)
        width, height = int(relw * self.board_width), int(relh *
                                                          self.board_height)

        self.board.delete(self.tag)
        self.board.create_rectangle(x,
                                    y,
                                    x + width,
                                    y + height,
                                    width=0,
                                    fill=self.background,
                                    tag=self.tag)

    def set_listbox(self):
        self.listbox.insert("end", "background")
        self.record["background"] = self.master.fake_frame_background

    def listbox_clicked(self):
        # Changes entry_arguments's text and label_arguments's text, sets focus on entry_name
        self.index = self.listbox.curselection()[0]
        parameter = list(self.record.keys())[self.index]
        value = self.record[parameter]
        self.entry_arguments.delete(0, "end")
        self.entry_arguments.insert("end", value)
        self.label_arguments.configure(text=f"{parameter} = {value}")
        self.entry_arguments.focus_set()

    def set_value(self):

        parameter = list(self.record.keys())[self.index]
        value = self.entry_arguments.get()

        try:
            evaluated_value = eval(value)
            self.record[parameter] = evaluated_value
        except:
            evaluated_value = value
            self.record[parameter] = f"{evaluated_value}"

        self.background = evaluated_value
        self.mod()

        self.label_arguments.configure(text=f"{parameter} = {value}")

    def fake_place_info(self):
        relx = float(self.spin_relx.get())
        rely = float(self.spin_rely.get())
        relw = float(self.spin_relw.get())
        relh = float(self.spin_relh.get())
        return {
            "relx": relx,
            "rely": rely,
            "relwidth": relw,
            "relheight": relh,
            "anchor": "nw"
        }

    def confirm(self):
        name = self.entry_name.get().replace(" ", "")
        if name and name not in self.master.record_of_names:
            self.master.record_of_names[name] = Frame(self.board)
            widget_cls = "Frame"

            self.master.writer.define_widget(name, widget_cls,
                                             self.fake_place_info())
            self.master.writer.begin_configure(name)
            for key, value in self.record.items():
                if value:
                    self.master.writer.write_configure(name, key, f"'{value}'")
            self.master.writer.end_configure(name)

            self.destroy()
コード例 #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 == 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 == 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:

                    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 Settings_for_root(Frame):
    def __init__(self, master, board, writer, background, dimensions,
                 transparency):
        super().__init__(master, bg='#435661')

        self.master = master
        self.board = board
        self.writer = writer
        self.width = None
        self.height = None
        self.xoff = None
        self.yoff = None
        self.transparency = None
        self.entry = None
        self.current_dim = None
        self.apply = None
        self.confirm = None

        self.set_layout(background, dimensions, transparency)

    def set_layout(self, background, dimensions, transparency):
        w, h, x, y = dimensions

        self.width = Spinbox(self,
                             background='#defffc',
                             foreground='#435661',
                             from_=0,
                             to_=10000,
                             justify='center',
                             highlightthickness=0,
                             increment=1,
                             command=self._apply)
        self.width.place(relx=0.0725,
                         rely=0.075,
                         relwidth=0.3325,
                         relheight=0.0325,
                         anchor='nw')

        self.height = Spinbox(self,
                              background='#defffc',
                              foreground='#435661',
                              from_=0,
                              to_=10000,
                              justify='center',
                              highlightthickness=0,
                              increment=1,
                              command=self._apply)
        self.height.place(relx=0.5825,
                          rely=0.075,
                          relwidth=0.3425,
                          relheight=0.033,
                          anchor='nw')

        self.xoff = Spinbox(self,
                            background='#defffc',
                            foreground='#435661',
                            from_=0,
                            to_=10000,
                            justify='center',
                            highlightthickness=0,
                            increment=1,
                            command=self._apply)
        self.xoff.place(relx=0.069,
                        rely=0.186,
                        relwidth=0.333,
                        relheight=0.0325,
                        anchor='nw')

        self.yoff = Spinbox(self,
                            background='#defffc',
                            foreground='#435661',
                            from_=0,
                            to_=10000,
                            justify='center',
                            highlightthickness=0,
                            increment=1,
                            command=self._apply)
        self.yoff.place(relx=0.582,
                        rely=0.186,
                        relwidth=0.343,
                        relheight=0.033,
                        anchor='nw')

        Label(self, background='#435661', foreground='#defffc', text='width') \
            .place(relx=0.103, rely=0.048, relwidth=0.27, relheight=0.0275, anchor='nw')

        Label(self, background='#435661', foreground='#defffc', text='height') \
            .place(relx=0.63, rely=0.05, relwidth=0.25, relheight=0.025, anchor='nw')

        Label(self, background='#435661', foreground='#defffc', text='x offset') \
            .place(relx=0.135, rely=0.161, relwidth=0.2025, relheight=0.025, anchor='nw')

        Label(self, background='#435661', foreground='#defffc', text='y offset') \
            .place(relx=0.635, rely=0.16, relwidth=0.23, relheight=0.02625, anchor='nw')

        self.current_dim = myButton(self,
                                    text="Set current root's dimensions",
                                    command=lambda *args: self.set_current())
        self.current_dim.place(relx=0.175,
                               rely=0.2537,
                               relwidth=0.65,
                               relheight=0.035,
                               anchor='nw')

        self.transparency = Spinbox(self,
                                    background='#defffc',
                                    foreground='#435661',
                                    from_=0,
                                    to_=1,
                                    justify='center',
                                    highlightthickness=0,
                                    increment=0.01,
                                    command=self._apply)
        self.transparency.place(relx=0.3,
                                rely=0.36,
                                relwidth=0.4,
                                relheight=0.03375,
                                anchor='nw')

        Label(self, background='#435661', foreground='#defffc', text='transparency') \
            .place(relx=0.324, rely=0.335, relwidth=0.34, relheight=0.025, anchor='nw')

        self.entry = Entry(self,
                           borderwidth=0,
                           background='#557282',
                           foreground='#defffc',
                           highlightthickness=0,
                           justify="center")
        self.entry.place(relx=0.3,
                         rely=0.4725,
                         relwidth=0.4,
                         relheight=0.04625,
                         anchor='nw')

        Label(self, background='#435661', foreground='#defffc', text='background') \
            .place(relx=0.375, rely=0.449, relwidth=0.2525, relheight=0.02375, anchor='nw')

        self.apply = myButton(self,
                              text="Apply",
                              command=lambda *args: self._apply())
        self.apply.place(relx=0.23,
                         rely=0.6075,
                         relwidth=0.54,
                         relheight=0.05125,
                         anchor='nw')

        self.confirm = myButton(self,
                                text="CONFIRM",
                                command=lambda *args: self._confirm())
        self.confirm.place(relx=0.23,
                           rely=0.7762,
                           relwidth=0.54,
                           relheight=0.09125,
                           anchor='nw')

        self.width.delete(0, "end")
        self.height.delete(0, "end")
        self.xoff.delete(0, "end")
        self.yoff.delete(0, "end")
        self.width.insert("end", w)
        self.height.insert("end", h)
        self.xoff.insert("end", x)
        self.yoff.insert("end", y)

        self.transparency.delete(0, "end")
        self.transparency.insert("end", transparency)

        self.width.bind("<Return>", lambda *args: self._apply())
        self.height.bind("<Return>", lambda *args: self._apply())
        self.xoff.bind("<Return>", lambda *args: self._apply())
        self.yoff.bind("<Return>", lambda *args: self._apply())
        self.transparency.bind("<Return>", lambda *args: self._apply())

        self.entry.insert("end", background)

    def set_current(self):
        w, h = self.board.winfo_width(), self.board.winfo_height()
        x, y = self.board.master.winfo_x(), self.board.master.winfo_y()

        self.width.delete(0, "end")
        self.height.delete(0, "end")
        self.xoff.delete(0, "end")
        self.yoff.delete(0, "end")
        self.width.insert("end", w)
        self.height.insert("end", h)
        self.xoff.insert("end", x)
        self.yoff.insert("end", y)

    def _apply(self):
        self.board.configure(bg=self.entry.get())

        w = self.width.get()
        h = self.height.get()
        x = self.xoff.get()
        y = self.yoff.get()
        self.board.master.geometry(f"{w}x{h}+{x}+{y}")

        self.board.master.attributes("-alpha", self.transparency.get())

    def _confirm(self):
        self.board.configure(bg=self.entry.get())
        self.writer.app_background = self.entry.get()

        w = self.width.get()
        h = self.height.get()
        x = self.xoff.get()
        y = self.yoff.get()
        self.board.master.geometry(f"{w}x{h}+{x}+{y}")

        self.writer.app_geometry = f"{w}x{h}+{x}+{y}"
        self.writer.app_transparency = self.transparency.get()

        self.destroy()
コード例 #32
0
ファイル: titita.py プロジェクト: due204/Titita
class MiVistas(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.parent.protocol("WM_DELETE_WINDOW", self.saliendo)
        self.vivista()
        self.valid = Validacion()

    def vivista(self):
        # Titulo
        self.parent.title("Titita")
        # Tamaño y pocision de la ventana
        self.parent.geometry("1050x480+100+100")
        # Redimensionable
        self.parent.resizable(False, False)
        # Color de fondo
        self.parent.config(background="lavender")
        #  Elegimos el icono del programa en base al OS
        if sistema == "linux":
            logo = PhotoImage(file=ruta2[0] + "/imagenes/titita.gif")
            self.parent.call("wm", "iconphoto", self.parent._w, logo)
        else:
            self.parent.iconbitmap(ruta2[0] + "\\imagenes\\titita.ico")

        #######################################################################
        # Define los distintos widgets

        # Frame de los entry
        entry_frame = LabelFrame(
            self.parent,
            text="Datos del cliente y el aparato",
            bg="lavender",
        )
        entry_frame.place(x=10, y=0)

        # Frame de los entry2
        entry2_frame = LabelFrame(
            self.parent,
            text="Datos sobre la reparacion",
            bg="lavender",
        )
        entry2_frame.place(x=550, y=0)

        # Frame de los botones
        button_frame = LabelFrame(self.parent, text="Comandos", bg="lavender")
        button_frame.place(x=920, y=0)

        # Frame del treeview
        tree_frame = Frame(self.parent)
        tree_frame.place(x=9, y=245)

        #######################################################################
        # Labels y Entrys
        self.nombre_label = Label(
            entry_frame,
            text="Nombre: ",
            bg="lavender",
        )
        self.nombre_entry = Entry(entry_frame, width=50)
        self.nombre_label.grid(row=0, column=0)
        self.nombre_entry.grid(row=0, column=1)

        self.apellido_label = Label(
            entry_frame,
            text="Apellido: ",
            bg="lavender",
        )
        self.apellido_entry = Entry(entry_frame, width=50)
        self.apellido_label.grid(row=1, column=0)
        self.apellido_entry.grid(row=1, column=1)

        self.telefono_label = Label(
            entry_frame,
            text="Telefono: ",
            bg="lavender",
        )
        self.telefono_entry = Entry(entry_frame, width=50)
        self.telefono_label.grid(row=2, column=0)
        self.telefono_entry.grid(row=2, column=1)

        self.direccion_label = Label(
            entry_frame,
            text="Direccion:",
            bg="lavender",
        )
        self.direccion_entry = Entry(entry_frame, width=50)
        self.direccion_label.grid(row=3, column=0)
        self.direccion_entry.grid(row=3, column=1)

        self.tipo_label = Label(
            entry_frame,
            text="Tipo:",
            bg="lavender",
        )
        self.tipo_spinbox = Spinbox(
            entry_frame,
            width=48,
            values=(
                "",
                "Amplificador",
                "Auricular",
                "Auto estereo",
                "Decodificador",
                "Camara",
                "Celular",
                "Centro Musical",
                "Consola de video juegos",
                "Consola portatil",
                "Estabilizador de tension",
                "Fuente de alimentacion",
                "Fuente inversora",
                "Impresora",
                "Mixer",
                "Monitor",
                "Netbook",
                "Notebook",
                "Parlante Bluetooth",
                "PC",
                "Potencia de audio",
                "Radio",
                "Reproductor de DVD",
                "Tablet",
                "Teclado",
                "Teclado musical",
                "Tv",
                "UPS",
                "Otro",
            ),
        )
        self.tipo_label.grid(row=4, column=0)
        self.tipo_spinbox.grid(row=4, column=1, sticky="w")

        self.marca_label = Label(
            entry_frame,
            text="Marca: ",
            bg="lavender",
        )
        self.marca_entry = Entry(entry_frame, width=50)
        self.marca_label.grid(row=5, column=0)
        self.marca_entry.grid(row=5, column=1)

        self.modelo_label = Label(
            entry_frame,
            text="Modelo:",
            bg="lavender",
        )
        self.modelo_entry = Entry(entry_frame, width=50)
        self.modelo_label.grid(row=6, column=0)
        self.modelo_entry.grid(row=6, column=1)

        self.falla_label = Label(
            entry_frame,
            text="Falla: ",
            bg="lavender",
        )
        self.falla_entry = Entry(entry_frame, width=50)
        self.falla_label.grid(row=7, column=0)
        self.falla_entry.grid(row=7, column=1)

        self.otros_label = Label(
            entry_frame,
            text="Otros:",
            bg="lavender",
        )
        self.otros_entry = Entry(entry_frame, width=50)
        self.otros_label.grid(row=8, column=0, pady=5)
        self.otros_entry.grid(row=8, column=1, pady=5)

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

        self.estado_spin = Spinbox(
            entry2_frame,
            values=("En reparacion", "Presupuestado", "Entrgado"),
        )
        self.estado_label = Label(
            entry2_frame,
            text="Estado",
            bg="lavender",
        )
        self.estado_spin.grid(row=0, column=1, sticky="w")
        self.estado_label.grid(row=0, column=0, sticky="w")

        self.costo_label = Label(
            entry2_frame,
            text="Costos",
            bg="lavender",
        )
        self.costo_entry = Entry(entry2_frame, width=30)
        self.costo_label.grid(row=1, column=0, pady=10, sticky="w")
        self.costo_entry.grid(row=1, column=1, pady=10, sticky="w")

        self.total_label = Label(
            entry2_frame,
            text="Total",
            bg="lavender",
        )
        self.total_entry = Entry(entry2_frame, width=30)
        self.total_label.grid(row=2, column=0, pady=10, sticky="w")
        self.total_entry.grid(row=2, column=1, pady=10, sticky="w")

        self.descripcion_label = Label(
            entry2_frame,
            text="Descripcion",
            bg="lavender",
        )
        self.descripcion_entry = Entry(entry2_frame, width=30)
        self.descripcion_label.grid(row=3, column=0, pady=10, sticky="w")
        self.descripcion_entry.grid(row=3, column=1, pady=10, sticky="w")

        self.notificacion_spin = Spinbox(
            entry2_frame,
            width=5,
            values=("No", "Si"),
        )
        self.notificacion_label = Label(
            entry2_frame,
            text="Se notifico",
            bg="lavender",
        )
        self.notificacion_spin.grid(row=4, column=1, sticky="w")
        self.notificacion_label.grid(row=4, column=0, sticky="w")

        #######################################################################
        # Buttons
        # Boton insertar
        self.submit_button = Button(button_frame,
                                    text="Guardar",
                                    command=self.insert_data)
        # Esto es para el enter
        self.submit_button.bind("<Return>", self.insert_data)
        self.submit_button.grid(row=0, column=0)

        # Boton Buscar en db
        self.search_button = Button(button_frame,
                                    text="Buscar",
                                    command=self.search_data)
        # Esto es para el enter
        self.search_button.bind("<Return>", self.search_data)
        self.search_button.grid(row=1, column=0, padx=10, pady=10)

        # Boton de borrado de campos
        self.rm_button = Button(
            button_frame,
            text="Borrar",
            command=self.rm_data,
        )
        # Esto es para el enter
        self.rm_button.bind("<Return>", self.rm_data)
        self.rm_button.grid(row=2, column=0, padx=10, pady=10)

        # Boton de configuraciones
        self.config_button = Button(button_frame,
                                    text="Configurar",
                                    command=self.config_data)
        # Esto es para el enter
        self.config_button.bind("<Return>", self.config_data)
        self.config_button.grid(row=3, column=0)

        ##########################
        tree_scroll = Scrollbar(tree_frame)
        tree_scroll.pack(side="right", fill="y")

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

        # Treeview
        self.tree = ttk.Treeview(
            tree_frame,
            yscrollcommand=tree_scroll.set,
            columns=(
                "Fecha",
                "Nombre",
                "Apellido",
                "Telefono",
                "Direccion",
                "Tipo",
                "Marca",
                "Modelo",
                "Falla",
                "Otros",
            ),
        )
        tree_scroll.config(command=self.tree.yview)
        self.tree.heading("#0", text="Orden")
        self.tree.heading("#1", text="Fecha")
        self.tree.heading("#2", text="Nombre")
        self.tree.heading("#3", text="Apellido")
        self.tree.heading("#4", text="Telefono")
        self.tree.heading("#5", text="Direccion")
        self.tree.heading("#6", text="Tipo")
        self.tree.heading("#7", text="Marca")
        self.tree.heading("#8", text="Modelo")
        self.tree.heading("#9", text="Falla")
        self.tree.heading("#10", text="Otros")
        self.tree.column("#0", stretch="YES", width=70)
        self.tree.column("#1", stretch="YES", width=87)
        self.tree.column("#2", stretch="YES", width=110)
        self.tree.column("#3", stretch="YES", width=110)
        self.tree.column("#4", stretch="YES", width=100)
        self.tree.column("#5", stretch="YES", width=100)
        self.tree.column("#6", stretch="YES", width=80)
        self.tree.column("#7", stretch="YES", width=80)
        self.tree.column("#8", stretch="YES", width=90)
        self.tree.column("#9", stretch="YES", width=100)
        self.tree.column("#10", stretch="YES", width=90)

        self.tree.pack()
        # Esto es para seleccionar con el click
        self.tree.bind("<ButtonRelease-1>", self.select_data)
        self.treeview = self.tree
        self.ver_data()

    # Esta funcion se encarga de borrar los datos de la pantalla del treeview
    def rm_data(self):
        self.nombre_entry.delete(0, "end")
        self.apellido_entry.delete(0, "end")
        self.telefono_entry.delete(0, "end")
        self.direccion_entry.delete(0, "end")
        self.tipo_spinbox.delete(0, "end")
        self.marca_entry.delete(0, "end")
        self.modelo_entry.delete(0, "end")
        self.falla_entry.delete(0, "end")
        self.otros_entry.delete(0, "end")
        self.estado_spin.delete(0, "end")
        self.costo_entry.delete(0, "end")
        self.total_entry.delete(0, "end")
        self.descripcion_entry.delete(0, "end")
        self.notificacion_spin.delete(0, "end")

    # Esta funcion se encarga de insertar los datos de la base en el treeview
    def ver_data(self):
        resultado = BaseDatos.select()
        records = self.tree.get_children()
        for element in records:
            self.tree.delete(element)
        for fila in resultado:
            self.tree.insert(
                "",
                0,
                text=str(fila.orden).zfill(5),
                values=(
                    fila.fecha,
                    fila.nombre,
                    fila.apellido,
                    fila.telefono,
                    fila.direccion,
                    fila.tipo,
                    fila.marca,
                    fila.modelo,
                    fila.falla,
                    fila.otros,
                    fila.estado,
                    fila.costo,
                    fila.total,
                    fila.descripcion,
                    fila.notificacion,
                    fila.orden,
                ),
            )

    #  Esta funcion se encarga de guardar los datos y de actualizarlos
    def insert_data(self, *argus):
        # Verifica que los campos no esten vacios.
        seleccionad = self.tree.focus()
        # Toma los items del campo seleccionado del treeview
        valore = self.tree.item(seleccionad, "values")
        try:
            # Controlo que el campo del nombre este completo antes de continuar
            namae = self.valid.vali(self.nombre_entry.get())
            if not namae:
                messagebox.showinfo(
                    title="Campos incompletos",
                    message="Debe completar el nombre como minimo.",
                )
            else:
                # Acutualizo la base de datos
                print("Orden:", valore[15], "actualizada")
                actualizar = BaseDatos.update(
                    nombre=self.nombre_entry.get(),
                    apellido=self.apellido_entry.get(),
                    telefono=self.telefono_entry.get(),
                    direccion=self.direccion_entry.get(),
                    tipo=self.tipo_spinbox.get(),
                    marca=self.marca_entry.get(),
                    modelo=self.modelo_entry.get(),
                    falla=self.falla_entry.get(),
                    otros=self.otros_entry.get(),
                    estado=self.estado_spin.get(),
                    costo=self.costo_entry.get(),
                    total=self.total_entry.get(),
                    descripcion=self.descripcion_entry.get(),
                    notificacion=self.notificacion_spin.get(),
                ).where(BaseDatos.orden == valore[15])
                actualizar.execute()
                # Limpia los campos del entry
                self.rm_data()
                # Imprimo por pantalla los datos
                self.ver_data()
        except:
            # Controlo que el campo del nombre este completo antes de continuar
            namae = self.valid.vali(self.nombre_entry.get())
            if not namae:
                messagebox.showinfo(
                    title="Campos incompletos",
                    message="Debe completar el nombre como minimo.",
                )
            else:
                # Guardo los datos en la base de datos
                guard = BaseDatos()
                guard.guardar(
                    self.nombre_entry.get(),
                    self.apellido_entry.get(),
                    self.telefono_entry.get(),
                    self.direccion_entry.get(),
                    self.tipo_spinbox.get(),
                    self.marca_entry.get(),
                    self.modelo_entry.get(),
                    self.falla_entry.get(),
                    self.otros_entry.get(),
                    self.estado_spin.get(),
                    self.costo_entry.get(),
                    self.total_entry.get(),
                    self.descripcion_entry.get(),
                    self.notificacion_spin.get(),
                )
                # Mando a imprimir los datos
                self.print_data2()
                # Limpia los campos del entry
                self.rm_data()
                # Imprimo por pantalla los datos
                self.ver_data()

    #  Esta funcion se encarga de hacer la busqueda en nuestra base de datos
    def search_data(self, *argus):
        busqueda()

    #  Esta funcion se encarga de mandar los datos a imprimir
    def print_data2(self, *argus):
        # Creamos una lista, guardamos los datos y se los mandamos
        # a factura.py para generar el pdf
        mi_lisu = []
        orde = BaseDatos.select().order_by(BaseDatos.orden.desc()).get()
        mi_lisu.append(str(orde).zfill(5))
        mi_lisu.append(
            str(self.nombre_entry.get() + " " + self.apellido_entry.get()), )
        mi_lisu.append(str(self.direccion_entry.get()))
        mi_lisu.append(str(self.telefono_entry.get()))
        mi_lisu.append(str(self.marca_entry.get()))
        mi_lisu.append(str(self.modelo_entry.get()))
        mi_lisu.append(str(self.falla_entry.get()))
        mi_lisu.append(str(self.otros_entry.get()))
        mi_lisu.append(str(self.tipo_spinbox.get()))
        boleta(mi_lisu)
        bole = messagebox.askyesno(message="¿Imprimir boleta?", title="Boleta")
        if bole:
            # Mandamos el numero de orden a imprimir
            imprimir(str(orde).zfill(5))

    #  Esta funcion se encarga de la configuracion
    def config_data(self, *argus):
        configuracion()

    #  Esta funcion se encarga de cargar el valor seleccionado en el treeview
    def select_data(self, *argus):
        # Borro todos los campos
        self.rm_data()
        # Selecciona la fila del treeview
        seleccionado = self.tree.focus()
        # Toma los items del campo seleccionado del treeview
        valores = self.tree.item(seleccionado, "values")
        # Inserta los valores en los campos
        self.nombre_entry.insert(0, valores[1])
        self.apellido_entry.insert(0, valores[2])
        self.telefono_entry.insert(0, valores[3])
        self.direccion_entry.insert(0, valores[4])
        self.tipo_spinbox.insert(0, valores[5])
        self.marca_entry.insert(0, valores[6])
        self.modelo_entry.insert(0, valores[7])
        self.falla_entry.insert(0, valores[8])
        self.otros_entry.insert(0, valores[9])
        self.estado_spin.insert(0, valores[10])
        self.costo_entry.insert(0, valores[11])
        self.total_entry.insert(0, valores[12])
        self.descripcion_entry.insert(0, valores[13])
        self.notificacion_spin.insert(0, valores[14])

    #  Esta funcion se ejecuta al cerrar la ventada
    def saliendo(self):
        self.parent.quit()
        self.parent.destroy()
        print("Saliendo del programa")