Ejemplo n.º 1
0
    def __init__(self, parent, music_filepath):
        Frame.__init__(self, parent)
        self.player = Player(music_filepath)
        
        title = os.path.basename(music_filepath) 

        label = tkinter.Label(self, text=title, width=30)
        label.pack(side=LEFT)

        padx = 10
        #image = tkinter.PhotoImage(file=icon_play)
        play_button = Button(self, text="Play")#image=image)
        play_button.pack(side=LEFT, padx=padx)
        play_button.bind("<Button-1>", self.play)
        
        #image = tkinter.PhotoImage(file=icon_pause)
        #pause_button = Button(self, text="Pause")#image=image)
        #pause_button.pack(side=LEFT, padx=padx)
        #pause_button.bind("<Button-1>", self.pause)
        #self.pausing = False
        
        #image = tkinter.PhotoImage(file=icon_stop)
        stop_button = Button(self, text="Stop")#image=image)
        stop_button.pack(side=LEFT, padx=padx)
        stop_button.bind("<Button-1>", self.stop)
Ejemplo n.º 2
0
    def initUI(self, mainFrame):
        """initialize the User Interface"""
        
        # styles
        style = Style()
        style.configure("GRN.TLabel", background="#ACF059")
        style.configure("GRN.TFrame", background="#ACF059")
        style.configure("BLK.TFrame", background="#595959")
        
        
        # create top frame
        topFrame = Frame(mainFrame, style="GRN.TFrame", padding=8)
        topFrame.pack(fill=BOTH, side=TOP)
        
        # create black border
        borderFrame = Frame(mainFrame, style="BLK.TFrame")
        borderFrame.pack(fill=BOTH, side=TOP)
        
        # create add player frame
        addPlayerFrame = Frame(mainFrame, padding=8)
        addPlayerFrame.pack(side=TOP)
        
        # create text field for add button
        self.nameFieldVar = StringVar()
        self.playerNameEntry = Entry(addPlayerFrame, textvariable = self.nameFieldVar)
        self.playerNameEntry.pack(side=LEFT)
        # create add player button
        addButton = Button(addPlayerFrame, text="Add player")
        addButton.pack(side=LEFT)
        
        # create choose game list
        self.currentGame = StringVar()
        self.currentGame.set(self.gameList[0])
        gameDropDown = OptionMenu(mainFrame, self.currentGame, self.gameList[0], *self.gameList)
        gameDropDown.pack(side=TOP)

        # create start game button
        startGameButton = Button(mainFrame, text="Start")
        
        startGameButton.bind("<Button-1>", self.startGame)
        startGameButton.pack(side=TOP)
        
        # create label and set text
        self.playerString = StringVar()
        self.playerString.set(self.buildPlayerHeaderString())
        headerLabel = Label(topFrame, textvariable=self.playerString, style="GRN.TLabel")
        headerLabel.pack(side=TOP)     
        addButton.bind("<Button-1>", self.onAddPlayerClick)
        self.playerNameEntry.bind("<Key>", self.onAddPlayerEnter)
        
        #set focus
        self.playerNameEntry.focus()
Ejemplo n.º 3
0
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent 

        self.music_root = ''
        self.query_path = ''
        self.extractor = Extractor(n_frames=40, 
                                   n_blocks=100, 
                                   learning_rate=0.00053,
                                   verbose=True)

        self.style = Style()
        self.style.theme_use("default")
        
        padx = 2
        pady = 2

        root_select_button = Button(self, text="Select a directory")
        root_select_button.pack(fill=tkinter.X, padx=padx, pady=pady)
        root_select_button.bind("<Button-1>", self.set_music_root)

        analyze_button = Button(self, text="Analyze")
        analyze_button.pack(fill=tkinter.X, padx=padx, pady=pady)
        analyze_button.bind("<Button-1>", self.analyze)

        query_select_button = Button(self, text="Select a file")
        query_select_button.pack(fill=tkinter.X, padx=padx, pady=pady)
        query_select_button.bind("<Button-1>", self.set_query_path)

        search_button = Button(self, text="Search similar songs")
        search_button.pack(fill=tkinter.X, padx=padx, pady=pady)
        search_button.bind("<Button-1>", self.search_music)
 
        self.pack(fill=BOTH, expand=1)
Ejemplo n.º 4
0
    def create_widgets(self, names):
        ''' Creates appropriate widgets.

            Args:
                names (list of str): list of available sheet names.
        '''
        sheet_name_lbl = Label(self,
                               text='Choose sheet name where data is stored:')
        sheet_name_lbl.grid(sticky=N+W, padx=5, pady=5)
        sheet_names_box = Combobox(self, state="readonly", width=20,
                                   textvariable=self.sheet_name_str,
                                   values=names)
        sheet_names_box.current(0)
        sheet_names_box.grid(row=1, column=0, columnspan=2,
                             sticky=N+W, padx=5, pady=5)
        ok_btn = Button(self, text='OK', command=self.ok)
        ok_btn.grid(row=2, column=0, sticky=N+E, padx=5, pady=5)
        ok_btn.bind('<Return>', self.ok)
        ok_btn.focus()
        cancel_btn = Button(self, text='Cancel', command=self.cancel)
        cancel_btn.grid(row=2, column=1, sticky=N+E, padx=5, pady=5)
        cancel_btn.bind('<Return>', self.cancel)
Ejemplo n.º 5
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.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)
Ejemplo n.º 6
0
class IsopachFrame(LabelFrame):
    
    entryWidth = 8
    buttonWidth = 15
    buttonPadding = 7

    removedEntriesStack = []

    def __init__(self,parent,calculationTimeEstimationFunction):
        
        LabelFrame.__init__(self,parent,text="Isopachs",borderwidth=5)
        self.numberOfIsopachs = DEFAULT_NUMBER_OF_ISOPACHS
        self.calculationTimeEstimationFunction = calculationTimeEstimationFunction
        
        openButtonImage = tkinter.PhotoImage(file=IMAGE_DIR + "open_file-icon.gif")
        self.tickImage = tkinter.PhotoImage(file=IMAGE_DIR + "tick.gif")
        
        self.loadFromFileButton = Button(self,image=openButtonImage)
        self.loadFromFileButton.grid(row=0,column=0,padx=self.buttonPadding,pady=10)
        self.loadFromFileButton.bind("<Button-1>",self.loadFromFile)
        self.loadFromFileButton.image = openButtonImage
        
        self.addButton = Button(self,text="Add isopach",width=self.buttonWidth)
        self.addButton.grid(row=0,column=1,padx=self.buttonPadding,pady=10)
        self.addButton.bind("<Button-1>",self.addIsopach)

        self.removeButton = Button(self,text="Remove isopach",width=self.buttonWidth)
        self.removeButton.grid(row=0,column=2,padx=self.buttonPadding,pady=10)
        self.removeButton.bind("<Button-1>",self.removeIsopach)
        
        self.scrollFrame = ScrollFrame(self)
        self.scrollFrame.grid(row=1,column=0,columnspan=3, sticky="NS")
        self.innerFrame = self.scrollFrame.innerFrame

        self.grid_rowconfigure(1,weight=1)

        self.rows = [self.createRow(i) for i in range(self.numberOfIsopachs)]
        
        thicknessM_L = Label(self.innerFrame, text="Thickness (m)")
        thicknessM_L.grid(column=1, row=1, padx=5, pady=5)
        sqrtAreaKM_L = Label(self.innerFrame, text="\u221AArea (km)")
        sqrtAreaKM_L.grid(column=2, row=1, padx=5, pady=5)
        include_L = Label(self.innerFrame, text="Use?")
        include_L.grid(column=3, row=1, padx=5, pady=5)
        
    def createRow(self,rowNumber):
        isopach_L = Label(self.innerFrame, text=str(rowNumber+1), width=2)
        isopach_L.grid(column=0, row=rowNumber+2, padx=(0,5), pady=5)
        
        thicknessVar = tkinter.StringVar()
        thicknessM_E = Entry(self.innerFrame,width=self.entryWidth,textvariable=thicknessVar, justify="right")
        thicknessM_E.grid(column=1, row=rowNumber+2, pady=5)
        
        areaVar = tkinter.StringVar()
        sqrtAreaKM_E = Entry(self.innerFrame,width=self.entryWidth,textvariable=areaVar, justify="right")
        sqrtAreaKM_E.grid(column=2, row=rowNumber+2, pady=5)

        includeVar = tkinter.IntVar()
        includeCB = tkinter.Checkbutton(self.innerFrame,variable=includeVar, selectimage=self.tickImage)
        includeCB.grid(column=3,row=rowNumber+2,pady=5)
        includeCB.invoke()
        includeCB.bind("<Leave>",self.calculationTimeEstimationFunction)
        
        return (isopach_L,None),(thicknessM_E,thicknessVar),(sqrtAreaKM_E,areaVar),(includeCB,includeVar)
    
    def addIsopach(self,event):
        row = self.createRow(self.numberOfIsopachs)

        if(len(self.removedEntriesStack) > 0):
            entry = self.removedEntriesStack.pop()

            row[1][1].set(entry[0])
            row[2][1].set(entry[1])
            row[3][1].set(entry[2])

        self.rows.append(row)
        self.numberOfIsopachs += 1
        self.calculationTimeEstimationFunction(None)
        
    def removeIsopach(self,event):
        if self.numberOfIsopachs > MINIMUM_NUMBER_OF_ISOPACHS:
            row = self.rows[-1]
            

            for wg,var in row:
                
                wg.grid_remove()
            self.numberOfIsopachs -= 1
            self.rows = self.rows[:self.numberOfIsopachs]
            self.calculationTimeEstimationFunction(None)

            rowValues = []
            for _,var in row[1:]:
                rowValues.append(var.get())
            self.removedEntriesStack.append(rowValues)    

    def getData(self):
        values = [(thicknessVar.get(), sqrtAreaVar.get(), includeVar.get()) for (_,_),(_,thicknessVar),(_,sqrtAreaVar),(_,includeVar) in self.rows]
        isopachs = []
        for index, (thicknessStr, sqrtAreaStr, includeInt) in enumerate(values):
            if includeInt == 1:
                thicknessM = helper_functions.validateValue(
                                thicknessStr,
                                "Isopach " + str(index+1) + "'s thickness must be a strictly positive number",
                                "float",
                                strictLowerBound=0)
                sqrtAreaKM = helper_functions.validateValue(
                                sqrtAreaStr,
                                "Isopach " + str(index+1) + "'s area must be a strictly positive number",
                                "float",
                                strictLowerBound=0)
                isopachs.append(Isopach(thicknessM, sqrtAreaKM))
        isopachs = sorted(isopachs, key=lambda i : i.thicknessM, reverse=True)
        
        if len({i.thicknessM for i in isopachs}) != len(isopachs):
            raise ValueError("Isopachs must all have unique thicknesses")
        
        return isopachs
    
    def loadData(self, isopachs):
        current = len(self.rows)
        difference = len(isopachs)-current

        if difference < 0:
            for _ in range(-difference):
                self.removeIsopach(None)
        elif difference > 0:
            for _ in range(difference):
                self.addIsopach(None)
                
        for row, isopach in zip(self.rows, isopachs):
            row[1][1].set(isopach.thicknessM)
            row[2][1].set(isopach.sqrtAreaKM)
            row[3][1].set(1)
            
    def getNumberOfIncludedIsopachs(self):
        return len([None for _,_,_,(_,includeVar) in self.rows if includeVar.get() == 1])
    
    def loadFromFile(self,event):
        fileName = tkinter.filedialog.askopenfilename();
        
        if fileName is None or fileName == "":
            return;
        
        try:
            file = open(fileName, "r")
        except FileNotFoundError:
            messagebox.showerror("Could not find file:\n\n\\t\"" + fileName.replace("\n","") + "\"")
            return
        
        isopachs = []
        success = True
        
        try:
            for index, line in enumerate(file):
                try:
                    thicknessM, sqrtAreaKM = line.split(',')
                    line = line.replace(" ","")
                    isopachs.append(Isopach(float(thicknessM), float(sqrtAreaKM)))
                except (ValueError, UnicodeDecodeError):
                    messagebox.showerror("File format error", "Line " + str(index+1) + " of the file \n\n\t\"" + 
                                         line.replace("\n","") + "\"\n\nis not in the format of 'thickness (M),\u221Aarea (KM)'")
                    success = False
                    break
        except:
            messagebox.showerror("File format error", "The file\n\n" + fileName + "\n\nis not in the format of 'thickness (M),\u221Aarea (KM)'")
            success = False
            
        if success:
            self.loadData(isopachs)
Ejemplo n.º 7
0
class Application:
    def __init__(self, master=None):
        self.config()

        self.main_window = Frame(master, padding="3 3 12 12")
        self.main_window['width'] = 350
        self.main_window.grid(column=0, row=0, sticky=(N, W, E, S))

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

        ############## INPUT ELEMENTS ################
        self.l_dir_input = Label(self.main_window)
        self.l_dir_input['text'] = 'Input directory'
        self.l_dir_input.grid(column=1, row=1, sticky=(E))

        self.e_input_dir = Entry(self.main_window)
        self.e_input_dir['width'] = 60
        self.e_input_dir.grid(column=2, row=1, sticky=(W, E))

        self.b_browse_input = Button(self.main_window)
        self.b_browse_input['text'] = 'Browse'
        self.b_browse_input.bind("<1>", lambda event,  e=self.e_input_dir:
                                 self.browse(event, e))
        self.b_browse_input.grid(column=2, row=2, sticky=E)

        ############## OUTPUT ELEMENTS ################
        self.l_dir_output = Label(self.main_window)
        self.l_dir_output['text'] = 'Output directory'
        self.l_dir_output.grid(column=1, row=3, sticky=(E))

        self.e_output_dir = Entry(self.main_window)
        self.e_output_dir['width'] = 60
        self.e_output_dir.grid(column=2, row=3, sticky=(W, E))

        self.b_browse_output = Button(self.main_window)
        self.b_browse_output['text'] = 'Browse'
        self.b_browse_output.bind("<1>", lambda event,  e=self.e_output_dir:
                                  self.browse(event, e))
        self.b_browse_output.grid(column=2, row=4, sticky=E)                                  

        ############## PARSER ELEMENTS ################
        self.l_parsers = Label(self.main_window)
        self.l_parsers['text'] = 'Select a parser'
        self.l_parsers.grid(column=1, row=5, sticky=(W))

        self.c_parsers = Combobox(self.main_window)
        self.c_parsers['values'] = self.parsers
        self.c_parsers['width'] = 60
        self.c_parsers.grid(column=2, row=5, sticky=(E))
        
        selected = 0
        if len(self.parsers) > 0:
            selected = len(self.parsers)-1

        self.c_parsers.current(selected)

        ############## BUTTON ELEMENTS ################
        self.button_container = Frame(self.main_window)
        self.button_container.grid(column=2, row=8, sticky=E)

        self.b_start = Button(self.button_container)
        self.b_start['text'] = "Start extraction"
        self.b_start['command'] = self.start
        self.b_start.pack(side=LEFT, padx='5')

        self.b_exit = Button(self.button_container)
        self.b_exit['text'] = "Exit"
        self.b_exit['command'] = self.exit
        self.b_exit.pack(side=RIGHT)

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

    def config(self):
        """
        Sets up common variables used within the GUI
        """
        if platform.system() == "Windows":
            self.python = 'python'
        else:
            self.python = 'python3'

        b = ''
        (_, _, filenames) = next(os.walk('.'))

        for filename in filenames:
            if filename == 'cli.py':
                b = os.path.abspath(filename)
                break

        self.binary = b
        self.parsers = []

        try:
            print(self.python, self.binary)
            r = subprocess.check_output([self.python, self.binary, '-lp'])
            # The output will always have a trailing element after split so I
            # might as well add the all option.
            self.parsers = r.decode(encoding='utf-8').split('\n')
            self.parsers[-1] = 'all'
        except subprocess.CalledProcessError as e:
            messagebox.showerror('Error', 'Couldn\'t configure the software.' +
                                 ' It will now autoterminate.')
            print(e)                        
            sys.exit(1)

    def start(self):
        """
        Init application with the parameters of the GUI
        """
        self.idir = self.e_input_dir.get()
        self.odir = self.e_output_dir.get()
        self.parser = self.c_parsers.get()

        r = subprocess.call([self.python, self.binary, '-d', self.idir,
                            '-p', self.parser, '-o', self.odir])

        if r == 0:
            messagebox.showinfo('Success', 'The extraction was a success')
        else:
            messagebox.showerror('Error', 'The extraction was not a success')

    def exit(self):
        sys.exit()

    def browse(self, event, element):
        """
        """
        folder = filedialog.askdirectory()
        element.insert(0, folder)
Ejemplo n.º 8
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.entryUsername = Entry(self)
        self.entryUsername.config(relief='flat')
        self.entryUsername.focus_set()
        self.entryUsername.bind('<Return>', lambda event: self.entryPassword.focus_set())

        self.entryPassword = Entry(self)
        self.entryPassword.config(relief='flat', 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.mailIconRed = PhotoImage(file="mail.gif")
        self.labelRed = Label(self, image=self.mailIconRed)
        self.mailIconGray = PhotoImage(file="mail2.gif")
        self.labelGray = Label(self, image=self.mailIconGray)
        self.labelKarma = Label(self, text = '•')

        self.labelU.grid(row=0, column=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)
        

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

        w=150
        h=112
        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 == '':
            #print('Please enter a username')
            self.entryUsername.focus_set()
        elif password == '':
            #print('Please enter a password')
            self.entryPassword.set_focus()
            
        if username != '' and password != '':
            #print('Attempting login for ' + username)
            try:
                self.USERAGENT = username + ' scans his inbox for new mail.'
                self.r = praw.Reddit(self.USERAGENT)
                #self.r.config._ssl_url = None
                self.r.login(username, password)
                #print('You have logged in as ' + username)
                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)
                self.usernamelabel.grid(row=0, column=0, pady = 10, padx = 30)
                self.quitbutton.grid(row=1, column=0)
                self.labelKarma.grid(row = 3, column = 0)
                self.playedSound = 'false'
                self.loop()
            except praw.errors.InvalidUserPass:
                pass
                #print('Invalid username or password')

    def loop(self):
        while True:
            try:
                #print('Starting new search')
                hasmail = 'false'
                for msg in self.r.get_unread(limit=None):
                    hasmail = 'true'
                
                if hasmail == 'true':
                    #print("You've got mail!")
                    if self.playedSound == 'false':
                        winsound.PlaySound('pop.wav', winsound.SND_FILENAME)
                    self.playedSound = 'true'
                    self.labelGray.grid_forget()
                    self.labelRed.grid(row=2, column=0)
                if hasmail == 'false':
                    self.playedSound = 'false'
                    #print('No mail!')
                    self.labelRed.grid_forget()
                    self.labelGray.grid(row=2, column=0)
                self.user = self.r.get_redditor(self.username)
                lkarma = str(self.user.link_karma)
                ckarma = str(self.user.comment_karma)
                lkarma = self.karmaRound(lkarma)
                ckarma = self.karmaRound(ckarma)
                karmastring = lkarma + ' • ' + ckarma
                self.labelKarma.config(text = karmastring)
                time.sleep(10)
            except Exception:
                time.sleep(10)


    def karmaRound(self, karma):
        if len(karma) > 4 and len(karma) < 7:
            tstring = karma[:-3]
            tstring2 = karma[-3:]
            karma = tstring + '.' + tstring2[:2] + 'K'
            return karma
        if len(karma) > 6:
            tstring = karma[:-6]
            tstring2 = karma[-6:]
            karma = tstring + '.' + tstring2[:2] + 'M'
            return karma
        else:
            return karma
Ejemplo n.º 9
0
           activebackground="green",
           command=callback)
b.place(relx=0.4, rely=0.5)
# b1 = Button(root, text="Submit", width=50, bg="#C8F9C4", height=5, relief='raised', font='Rockwell', bd=10, activebackground="green", command=callback)
# b1.place(relx=0.5, rely=0.6)

e = Entry(
    root,
    width=50,
)
e.pack()
e.insert(0, "Enter an Expression")
text = e.get()
e.bind("<FocusIn>", clear_search)

b.bind("<Enter>", on_enter)
b.bind("<Leave>", on_leave)
#!/usr/bin/env python3
"""
ZetCode Tkinter tutorial

In this script, we use the grid
manager to create a more complicated Windows
layout.

Author: Jan Bodnar
Last modified: April 2019
Website: www.zetcode.com
"""

from tkinter import Tk, Text, BOTH, W, N, E, S
Ejemplo n.º 10
0
class Timer(BaseWidget):
    def __init__(self, master):
        BaseWidget.__init__(self, 'Timer', master)

    def create_content(self, **kw):
        self.minsize(50, 120)

        self._time = [0, 0, 0]
        self._on = False
        self._after_id = ''

        self.img_play = PhotoImage(master=self, file=IM_START)
        self.img_pause = PhotoImage(master=self, file=IM_PAUSE)
        self.img_stop = PhotoImage(master=self, file=IM_STOP)

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

        # --- GUI elements
        self.display = Label(self, text='%i:%.2i:%.2i' % tuple(self._time),
                             anchor='center',
                             style='timer.TLabel')
        self.intervals = Text(self, highlightthickness=0, relief='flat',
                              height=3, width=1,
                              inactiveselectbackground=self.style.lookup('TEntry', 'selectbackground'))
        self.intervals.tag_configure('center', justify='center')
        self.intervals.configure(state='disabled')
        self.b_interv = Button(self, text=_('Interval'), style='timer.TButton',
                               command=self.add_interval)
        self.b_interv.state(('disabled',))

        self.b_launch = Button(self, image=self.img_play, padding=2,
                               command=self.launch, style='timer.TButton')
        self.b_stop = Button(self, image=self.img_stop, padding=2,
                             command=self.stop, style='timer.TButton')

        # --- placement
        self.display.grid(row=0, columnspan=2, sticky='ew', padx=8, pady=(4, 0))
        Label(self, text=_('Intervals:'),
              style='timer.TLabel').grid(row=1, columnspan=2, sticky='w', padx=4)
        self.intervals.grid(row=2, columnspan=2, sticky='eswn')
        self.b_interv.grid(row=3, columnspan=2, sticky='ew')
        self.b_launch.grid(row=4, column=0, sticky='ew')
        self.b_stop.grid(row=4, column=1, sticky='ew')

        self._corner = Sizegrip(self, style="timer.TSizegrip")
        self._corner.place(relx=1, rely=1, anchor='se')

        # --- bindings
        self.intervals.bind("<1>", lambda event: self.intervals.focus_set())
        self.bind('<3>', lambda e: self.menu.tk_popup(e.x_root, e.y_root))
        self.display.bind('<ButtonPress-1>', self._start_move)
        self.display.bind('<ButtonRelease-1>', self._stop_move)
        self.display.bind('<B1-Motion>', self._move)
        self.b_stop.bind('<Enter>', self._on_enter)
        self.b_stop.bind('<Leave>', self._on_leave)

    def update_style(self):
        self.attributes('-alpha', CONFIG.get(self.name, 'alpha', fallback=0.85))
        bg = CONFIG.get('Timer', 'background')
        fg = CONFIG.get('Timer', 'foreground')
        active_bg = active_color(*self.winfo_rgb(bg))
        self.configure(bg=bg)
        self.menu.configure(bg=bg, fg=fg, selectcolor=fg, activeforeground=fg,
                            activebackground=active_bg)
        self.menu_pos.configure(bg=bg, fg=fg, selectcolor=fg, activeforeground=fg,
                                activebackground=active_bg)
        self.display.configure(font=CONFIG.get('Timer', 'font_time'))
        self.intervals.configure(bg=bg, fg=fg,
                                 font=CONFIG.get('Timer', 'font_intervals'))
        self.style.configure('timer.TButton', background=bg, relief='flat',
                             foreground=fg, borderwidth=0)
        self.style.configure('timer.TLabel', background=bg,
                             foreground=fg)
        self.style.configure('timer.TSizegrip', background=bg)
        self.style.map('timer.TSizegrip', background=[('active', active_bg)])
        self.style.map('timer.TButton', background=[('disabled', bg),
                                                    ('!disabled', 'active', active_bg)])

    def _on_enter(self, event=None):
        self._corner.state(('active',))

    def _on_leave(self, event=None):
        self._corner.state(('!active',))

    def show(self):
        self.deiconify()
        self.update_idletasks()
        self.withdraw()
        if self._position.get() == 'above':
            self.overrideredirect(True)
        else:
            self.overrideredirect(False)
        BaseWidget.show(self)
        self.update_idletasks()
        self.withdraw()
        self.deiconify()

    def _run(self):
        if self._on:
            self._time[2] += 1
            if self._time[2] == 60:
                self._time[2] = 0
                self._time[1] += 1
                if self._time[1] == 60:
                    self._time[1] = 0
                    self._time[0] += 1
            self.display.configure(text='%i:%.2i:%.2i' % tuple(self._time))
            self._after_id = self.after(1000, self._run)

    def launch(self):
        if self._on:
            self._on = False
            self.b_launch.configure(image=self.img_play)
            self.b_interv.state(('disabled',))
        else:
            self._on = True
            self.b_interv.state(('!disabled',))
            self.b_launch.configure(image=self.img_pause)
            self.after(1000, self._run)

    def add_interval(self):
        tps = '\n%i:%.2i:%.2i' % tuple(self._time)
        if self.intervals.get('1.0', 'end') == '\n':
            tps = tps[1:]
        self.intervals.configure(state='normal')
        self.intervals.insert('end', tps, 'center')
        self.intervals.configure(state='disabled')

    def stop(self):
        self._on = False
        self.b_interv.state(('disabled',))
        self.b_launch.configure(image=self.img_play)
        self._time = [0, 0, 0]
        self.intervals.configure(state='normal')
        self.intervals.delete('1.0', 'end')
        self.intervals.configure(state='disabled')
        self.display.configure(text='%i:%.2i:%.2i' % tuple(self._time))
Ejemplo n.º 11
0
    cnvs.create_oval(x1, y1, x2, y2, fill=black_color)
    draw.ellipse([x1, y1, x2, y2], fill=255)


def clear(event):
    cnvs.delete("all")
    draw.rectangle([0, 0, canvas_width, canvas_height], 0)
    result_area.configure(text="Predictions\n\n")


cnvs.bind("<B1-Motion>", paint)

##Canvas Controls
clear_btn = Button(text='Clear')
clear_btn.grid(row=2, column=0, sticky='EW')
clear_btn.bind("<1>", clear)
run_btn = Button(text='Run', command=getImage)
run_btn.grid(row=2, column=1, sticky='EW')
#Result Code Section
text_title = Label(main_window,
                   height=1,
                   text='Predictions',
                   highlightthickness=1,
                   borderwidth=0,
                   background='#A9A9A9')
text_title.grid(row=0, column=1, sticky='EW')
result_area = Label(main_window,
                    width=50,
                    text='Predictions\n\n',
                    foreground='#20C20E',
                    highlightthickness=1,
Ejemplo n.º 12
0
class IntScroller(Frame):
    def __init__(self, master, **kwargs):
        super().__init__(master)

        # define from_ < to, even for negative increment
        self.min = kwargs.pop('from_', 0)
        self.max = kwargs.pop('to', 5)
        self.increment = kwargs.pop('increment', 1)
        self.var = kwargs.pop('textvariable', IntVar())
        # Defaulting to min if no starting value given
        value = kwargs.pop('value', self.min)
        label_text = kwargs.pop('label', None)

        # Clamp value to range
        value = min(self.max, max(value, self.min))

        self.set(value)

        right_frame = Frame(self)

        if label_text:
            left_frame = Frame(self)
            self.label = Label(left_frame, text=label_text, justify=RIGHT)
            self.label.pack()
            left_frame.grid(row=0, column=0)
            scroller_column = 1
        else:
            self.label = None
            scroller_column = 0

        self.up_button = Button(right_frame,
                                text='\u25b2',
                                command=self.inc,
                                **kwargs)
        self.text = Entry(right_frame,
                          textvariable=self.var,
                          justify=CENTER,
                          state='readonly',
                          **kwargs)
        self.down_button = Button(right_frame,
                                  text='\u25bc',
                                  command=self.dec,
                                  **kwargs)

        self.up_button.grid(row=0)
        self.text.grid(row=1)
        self.down_button.grid(row=2)
        right_frame.grid(row=0, column=scroller_column)

        # Using a third column, same width as text column, to help keep scroller central in widget
        self.columnconfigure(0, weight=1, uniform='foo')
        if label_text:
            self.columnconfigure(1, weight=1)
            self.columnconfigure(2, weight=1, uniform='foo')

        self.bind('<Key>',
                  self.master.key_pressed)  # pass keypresses to parent
        self.up_button.bind('<Key>', self.master.key_pressed)
        self.down_button.bind('<Key>', self.master.key_pressed)
        self.text.bind('<Key>', self.master.key_pressed)

        # Copied from spindown, hoping to implement similar options for compatibility
        #
        # STANDARD OPTIONS
        #
        #     activebackground, background, borderwidth,
        #     cursor, exportselection, font, foreground,
        #     highlightbackground, highlightcolor,
        #     highlightthickness, insertbackground,
        #     insertborderwidth, insertofftime,
        #     insertontime, insertwidth, justify, relief,
        #     repeatdelay, repeatinterval,
        #     selectbackground, selectborderwidth
        #     selectforeground, takefocus, textvariable
        #     xscrollcommand.
        #
        # WIDGET-SPECIFIC OPTIONS
        #
        #     buttonbackground, buttoncursor,
        #     buttondownrelief, buttonuprelief,
        #     command, disabledbackground,
        #     disabledforeground, format, from_,
        #     invalidcommand, increment,
        #     readonlybackground, state, to,
        #     validate, validatecommand values,
        #     width, wrap,

    def inc(self):
        value = self.var.get() + self.increment
        value = min(self.max, max(value, self.min))
        self.var.set(value)

    def dec(self):
        value = self.var.get() - self.increment
        value = min(self.max, max(value, self.min))
        self.var.set(value)

    def set(self, value):
        self.var.set(value)

    def activate(self):
        self.text.config(fg='red')

    def deactivate(self):
        self.text.config(fg='black')
Ejemplo n.º 13
0
class PixivSort:
    curr_search_result = []
    image_files = []
    images_obj = []
    image_list = []
    current_page = 1
    loading_img = None
    image_raiting_labels = []
    image_pages_labels = []

    def __init__(self):
        self.pth = "./"
        try:
            self.pth = sys._MEIPASS + "/"
        except Exception:
            pass

        self.root = Tk()
        self.root.title('PixivSort by Zettroke')
        self.root.iconbitmap(os.path.join(base_dir, 'icon.ico'))
        self.progress_bar_var = IntVar()
        self.progress_bar_label_var = StringVar()
        self.frame = Frame(self.root, height=100, width=1000, bg='#0094DC')
        self.frame.place(x=0, y=0)
        Style().configure("TButton", padding=1, relief="flat",
                                                background="#0094DC")
        Style().configure("TLabel", background="#0094DC")
        Style().configure("C.TButton", padding=0, relief="flat", font="Arial 12")
        self.root.minsize(1000, 810)
        self.root.maxsize(1000, 810)
        self.canvas = Canvas(self.root, width=1000, height=2000, bg='white')

        self.canvas.place(x=0, y=100)
        self.canvas.bind('<Button-1>', self.press)

        self.progress_bar = Progressbar(self.root, length=915, orient='horizont', variable=self.progress_bar_var, maximum=1000)
        self.progress_bar.place(x=0, y=790)

        self.progress_bar_label = LabelOld(self.root, textvariable=self.progress_bar_label_var, font='Arial 10', bg='white')
        self.progress_bar_label.place(x=915, y=787.5)

        cnv = Canvas(self.root, width=300, height=100, bg='#0094DC', bd=0, highlightthickness=0, relief='ridge')
        cnv.place(x=0, y=0)
        MyLabel = ImageTk.PhotoImage(Image.open(os.path.join(base_dir, 'Label.png')).resize((round(564/(264/100)), 100), Image.BICUBIC))
        cnv.create_image(125, 52.5, image=MyLabel)

        label = Label(self.root, text='Search', anchor=CENTER, font='Arial 16')
        label.place(x=500, y=20)

        self.total_pages_num = 0
        self.total_pages_label = Label(self.root, text='/0', anchor=W, font='Arial 14')
        self.total_pages_label.place(x=920, y=70)

        self.button = Button(self.root, text='Go!')
        self.button.place(x=650, y=50)
        self.button.bind('<Button-1>', self.search)

        self.button_page_inc = Button(self.root, text='>', width=1, state=DISABLED)
        self.button_page_dec = Button(self.root, text='<', width=1, state=DISABLED)

        self.button_page_inc.place(x=970, y=72)
        self.button_page_dec.place(x=845, y=72)

        self.button_page_inc.bind('<Button-1>', self.page_button)
        self.button_page_dec.bind('<Button-1>', self.page_button)

        self.loading_img = ImageTk.PhotoImage(Image.open(os.path.join(base_dir, 'loading.png')).resize((170, 170), Image.BICUBIC))

        self.entry = Entry(self.root, width=18, font='Arial 14')
        self.entry.place(x=430, y=50)
        self.entry.bind('<Return>', self.search)

        self.entry_page_number = Entry(self.root, width=5, font='Arial 14', state=DISABLED)
        self.entry_page_number.place(x=860, y=70)
        self.entry_page_number.bind('<Return>', self.show_new)

        self.root.mainloop()

    def press(self, event):
        tap = event.widget.find_overlapping(event.x, event.y, event.x+1, event.y+1)
        if len(tap) != 0:
            tap = int(event.widget.gettags(tap[0])[0])
            img = self.image_list[tap-1]
            if img[3] == 1:
                webbrowser.open("https://www.pixiv.net/member_illust.php?mode=medium&illust_id=" + str(img[0]))
            else:
                webbrowser.open("https://www.pixiv.net/member_illust.php?mode=manga&illust_id=" + str(img[0]))

    def set_total_pages(self, total):
        self.total_pages_num = math.ceil(40000/15 if total/15 > 40000/15 else total/15)
        self.total_pages_label.config(text='/' + str(self.total_pages_num))
        self.entry_page_number.delete(0, END)
        self.entry_page_number.insert(0, '1')
        self.current_page = 1

    def search(self, event):
        event.widget.config(state=DISABLED)
        self.progress_bar_label_var.set('downloading...')
        self.progress_bar_var.set(0)
        Thread(target=send_request_multiproc.search, args=(self.entry.get(), self.done, self.progress_update), daemon=True).start()

    def done(self, res):
        self.curr_search_result = res

        self.entry_page_number.configure(state=NORMAL)
        self.button_page_inc.configure(state=NORMAL)
        self.button_page_dec.configure(state=NORMAL)

        self.set_total_pages(len(res))
        self.progress_bar_label_var.set('done!!!')
        self.show()
        self.entry.config(state=NORMAL)

    def progress_update(self, done, total):
        print("done", round(done/total*100, 2))
        self.root.after_idle(self.change_pbar_value, (done/total))

    def change_pbar_value(self, val):
        self.progress_bar_var.set(val*1000)

    def load_image(self, num):
        img = self.image_list[num]
        if hi_res_preview:
            f = io.BytesIO(requests.get(img[1], headers={"Referer": "https://www.pixiv.net/"}).content)
        else:
            f = io.BytesIO(requests.get(img[2], headers={"Referer": "https://www.pixiv.net/"}).content)
        image = ImageTk.PhotoImage(Image.open(f).resize((170, 170), Image.BICUBIC))
        if img in self.image_list:
            self.image_files.append(image)
            self.canvas.itemconfig(self.images_obj[num], image=image)

    def show_new(self, event=None):
        if not 0 < int(self.entry_page_number.get()) < self.total_pages_num:
            self.entry_page_number.delete(0, END)
            self.entry_page_number.insert(0, '0')
        else:
            self.current_page = int(self.entry_page_number.get())
        self.show()

    def page_button(self, event):
        if event.widget.cget('text') == '>' and self.current_page < self.total_pages_num:
            temp = int(self.entry_page_number.get())
            self.entry_page_number.delete(0, END)
            self.entry_page_number.insert(0, str(temp + 1))
            self.show_new()
        elif event.widget.cget('text') == '<' and self.current_page > 1:
            temp = int(self.entry_page_number.get())
            self.entry_page_number.delete(0, END)
            self.entry_page_number.insert(0, str(temp - 1))
            self.show_new()

    def show(self, event=None):
        self.button.config(state=NORMAL)
        for i in self.image_pages_labels:
            i.destroy()
        for i in self.image_raiting_labels:
            i.destroy()
        self.image_pages_labels.clear()
        self.image_raiting_labels.clear()
        self.images_obj.clear()
        self.image_files.clear()
        self.canvas.delete(ALL)
        try:
            self.image_list = self.curr_search_result[self.current_page*15-15:self.current_page*15]
            y = 0
            x = 35
            for i in range(len(self.image_list)):
                if i % 5 == 0:
                    y += 220
                    x = 35
                self.images_obj.append(self.canvas.create_image(x, y, image=self.loading_img, anchor=SW, tags=str(i+1)))
                label1 = LabelOld(self.root, text='Raiting: ' + str(self.image_list[i][4]), bg='white')
                label1.place(x=x, y=y+100)
                self.image_raiting_labels.append(label1)
                label2 = LabelOld(self.root, text='Pages: ' + str(self.image_list[i][3]), bg='white')
                label2.place(x=x+120, y=y+100)
                self.image_pages_labels.append(label2)
                x += 190
            for i in range(len(self.image_list)):
                Thread(target=self.load_image, args=(i,), daemon=True).start()
        except Exception:
            pass
Ejemplo n.º 14
0
def bind_button(button: ttk.Button):
    button.bind("<Key-Return>", lambda e: button.invoke())
    button.bind("<KP_Enter>", lambda e: button.invoke())
Ejemplo n.º 15
0
class FrameRunServer(FrameTab):
    def __init__(self, master=None, **kw):
        """
        GUI tab that handles interface and region selection and starting the server.
        :param master: root window
        :param kw: args
        """
        FrameTab.__init__(self, master, **kw)
        self.wii_u_interface = None
        self.normal_interface = None
        self.drc_sim_c = None
        self.wpa_supplicant = None
        LoggerGui.extra("Initializing FrameRunServer")
        # Create Widgets
        self.label_wpa = Label(self, text="Wii U Connection:")
        self.label_backend = Label(self, text="Server Status:")
        self.label_wpa_status = Label(self)
        self.label_backend_status = Label(self)
        self.button_start = Button(self, text="Start")
        self.button_stop = Button(self, text="Stop")
        self.label_wiiu_interface = Label(self, text="Wii U Interface")
        self.label_normal_interface = Label(self, text="Normal Interface")
        self.dropdown_wiiu_interface = Combobox(self, state="readonly")
        self.dropdown_normal_interface = Combobox(self, state="readonly")
        self.label_interface_info = Label(self)
        self.label_region = Label(self, text="Region")
        self.dropdown_region = Combobox(self, state="readonly")
        # Events
        self.button_start.bind("<Button-1>", self.start_server)
        self.button_stop.bind("<Button-1>", self.stop_server)
        # Position widgets
        self.label_wpa.grid(column=0, row=0, sticky="e")
        self.label_backend.grid(column=0, row=1, sticky="e")
        self.label_wpa_status.grid(column=1, row=0, sticky="w")
        self.label_backend_status.grid(column=1, row=1, sticky="w")
        self.label_wiiu_interface.grid(column=0, row=2)
        self.label_normal_interface.grid(column=0, row=3)
        self.dropdown_wiiu_interface.grid(column=1, row=2, columnspan=2)
        self.dropdown_normal_interface.grid(column=1, row=3, columnspan=2)
        self.label_region.grid(column=0, row=4)
        self.dropdown_region.grid(column=1, row=4, columnspan=2)
        self.button_start.grid(column=1, row=5)
        self.button_stop.grid(column=2, row=5)
        self.label_interface_info.grid(column=0, row=6, columnspan=3)
        LoggerGui.extra("Initialized FrameRunServer")

    def start_server(self, event=None):
        """
        Try to start wpa_supplicant and connect to a Wii U.
        :param event: Determines if this was a user initiated start.
        :return: None
        """
        if event:
            LoggerGui.debug("User clicked start server button")
        LoggerGui.debug("Start server called")
        if self.label_backend_status["text"] != DrcSimC.STOPPED and \
                (self.label_wpa_status["text"] not in (WpaSupplicant.DISCONNECTED, WpaSupplicant.TERMINATED)):
            messagebox.showerror("Running", "Server is already running")
            return
        if not os.path.exists(constants.PATH_CONF_CONNECT):
            messagebox.showerror(
                "Auth Error",
                "No auth details found. Use the \"Get Key\" tab to pair with a Wii U."
            )
            self.activate()
            return
        self.normal_interface = self.dropdown_normal_interface.get()
        self.wii_u_interface = self.dropdown_wiiu_interface.get()
        if not self.normal_interface or not self.wii_u_interface:
            messagebox.showerror("Interface Error",
                                 "Two interfaces need to be selected.")
            self.activate()
            return
        if self.normal_interface == self.wii_u_interface:
            messagebox.showerror(
                "Interface Error",
                "The selected normal and Wii U interfaces must be different.")
            self.activate()
            return
        try:
            InterfaceUtil.get_mac(self.normal_interface)
            InterfaceUtil.get_mac(self.wii_u_interface)
        except ValueError:
            messagebox.showerror(
                "Interface Error",
                "The selected Interface is no longer available.")
            self.activate()
            return
        if InterfaceUtil.is_managed_by_network_manager(self.wii_u_interface):
            set_unmanaged = messagebox.askokcancel(
                "Managed Interface",
                "This interface is managed by Network Manager. To use it with DRC Sim it needs "
                "to be set to unmanaged. Network Manager will not be able to control the interface"
                " after this.\nSet %s to unmanaged?" % self.wii_u_interface)
            if set_unmanaged:
                InterfaceUtil.set_unmanaged_by_network_manager(
                    self.wii_u_interface)

            else:
                messagebox.showerror(
                    "Managed Interface",
                    "Selected Wii U interface is managed by Network Manager.")
                self.activate()
                return

            #reboot_now = messagebox.askokcancel(
            #    "Applying Changes", "For the changes to fully take effect you need to restart your PC "
            #    "Do it now?")
            #if reboot_now:
            #    ProcessUtil.call(["reboot", "-h", "now"])
            #else:
            #    self.activate()
            #    return

        LoggerGui.debug("Starting wpa supplicant")
        self.wpa_supplicant = WpaSupplicant()
        self.wpa_supplicant.add_status_change_listener(self.wpa_status_changed)
        self.wpa_supplicant.connect(constants.PATH_CONF_CONNECT,
                                    self.wii_u_interface)
        self.label_backend_status.config(text="WAITING")

    def wpa_status_changed(self, status):
        """
        Handles wpa status changes. Initializes backend server if a connection is made.
        :param status: status message
        :return: None
        """
        LoggerGui.debug("Wpa changed status to %s", status)
        self.label_wpa_status.config(text=status)
        if status == WpaSupplicant.CONNECTED:
            LoggerGui.debug("Routing")
            InterfaceUtil.dhclient(self.wii_u_interface)
            InterfaceUtil.set_metric(self.wii_u_interface, 1)
            InterfaceUtil.set_metric(self.normal_interface, 0)
            LoggerGui.debug("Starting backend")
            self.drc_sim_c = DrcSimC()
            self.drc_sim_c.add_status_change_listener(
                self.backend_status_changed)
            self.drc_sim_c.set_region(self.dropdown_region.get())
            self.drc_sim_c.start()
            self.label_interface_info.config(
                text="Server IP: " +
                InterfaceUtil.get_ip(self.normal_interface) + "\n" +
                os.uname()[1])
        elif status in (WpaSupplicant.DISCONNECTED, WpaSupplicant.TERMINATED):
            InterfaceUtil.set_metric(self.wii_u_interface, 0)
            self.stop_server()
        elif status == WpaSupplicant.NOT_FOUND:
            self.stop_server()
            messagebox.showerror("Scan Error", "No Wii U found.")
        elif status == WpaSupplicant.FAILED_START:
            InterfaceUtil.set_metric(self.wii_u_interface, 0)
            self.stop_server()
            messagebox.showerror(
                "Cannot Connect",
                "Failed to start wpa_supplicant_drc. This could mean there is a "
                "configuration error or wpa_supplicant_drc is not installed. "
                "Check %s for details." % constants.PATH_LOG_WPA)

    def backend_status_changed(self, status):
        """
        Handles backend status changes.
        :param status: status message
        :return: None
        """
        LoggerGui.debug("Backend status changed to %s", status)
        self.label_backend_status.config(text=status)
        if status == DrcSimC.STOPPED:
            self.stop_server()

    def stop_server(self, event=None):
        """
        Stops active threads.
        :param event: Determines if this is a user initiated stop
        :return: None
        """
        if event:
            LoggerGui.debug("User clicked stop server button")
        LoggerGui.debug("Stop server called")
        if event and (self.label_wpa_status["text"]
                      in (WpaSupplicant.DISCONNECTED, WpaSupplicant.TERMINATED)
                      and self.label_backend_status["text"]
                      == DrcSimC.STOPPED):
            messagebox.showerror("Stop", "Server is not running.")
            return
        if self.drc_sim_c:
            self.drc_sim_c.stop()
            self.drc_sim_c = None
        if self.wpa_supplicant:
            self.wpa_supplicant.stop()
            self.wpa_supplicant = None
        self.activate()

    def activate(self):
        """
        Initializes the frame.
        :return: None
        """
        LoggerGui.debug("FrameRunServer activated")
        self.dropdown_wiiu_interface[
            "values"] = InterfaceUtil.get_wiiu_compatible_interfaces()
        self.dropdown_normal_interface[
            "values"] = InterfaceUtil.get_all_interfaces()
        self.dropdown_region["values"] = ["NONE", "NA"]
        self.label_wpa_status["text"] = self.wpa_supplicant.get_status() \
            if self.wpa_supplicant and self.wpa_supplicant.get_status() else WpaSupplicant.DISCONNECTED
        self.label_backend_status["text"] = self.drc_sim_c.get_status() \
            if self.drc_sim_c and self.drc_sim_c.get_status() else DrcSimC.STOPPED
        self.button_start.config(state="normal")
        self.button_stop.config(state="normal")
        self.label_interface_info.config(text="")

    def deactivate(self):
        """
        De-initializes the frame.
        :return: None
        """
        LoggerGui.debug("FrameRunServer deactivated")
        self.stop_server()

    def kill_other_tabs(self):
        return True