コード例 #1
0
def google(self, text, goog, nom):
    goog.destroy()
    # Progress bar widget
    progress = Progressbar(self,
                           orient=HORIZONTAL,
                           length=200,
                           mode='determinate')
    progress.place(x=350, y=300)
    l2 = Label(self, text=" Currently researching...")
    l2.place(x=350, y=200)
    # print("\n"+information+" Renseignez Prénom, Nom, Ville, Département, Sport, Etablissement scolaire ...\n")
    # nom = input(" Recherche: ")
    # print("\n"+wait+" Recherche en cours...")
    url = "https://www.google.com/search?num=20&q=\\%s\\"
    try:
        nom2 = nom.split(" ")
        nom = nom2[0] + '+' + nom2[1]
    except:
        pass
    progress['value'] = 10
    self.update_idletasks()
    time.sleep(0.1)
    requete = requests.get(url % (nom))
    progress['value'] = 20
    self.update_idletasks()
    time.sleep(0.1)
    searchGoogle(self, text, progress, l2, requete=requete)
コード例 #2
0
ファイル: Progress.py プロジェクト: miles-1/EasyTracker
class Progress:
    def __init__(self, root, length=1):
        self.root = root
        self.length = length
        self.progress = Progressbar(self.root,
                                    orient=HORIZONTAL,
                                    length=200,
                                    mode='determinate')

    def pack(self, **kwargs):
        self.progress.pack(**kwargs)

    def place(self, **kwargs):
        self.progress.place(**kwargs)

    def grid(self, **kwargs):
        self.progress.grid(**kwargs)

    def config(self, length):
        self.length = int(length)

    def reset(self):
        self.progress["value"] = 0
        self.root.update()

    def increase(self, num=1):
        temp = self.progress["value"]
        self.progress["value"] = min(temp + num * (100 - temp) / self.length,
                                     100) if self.length else 100
        self.length = (self.length - num) if self.length - num > 0 else 0
        self.root.update()
コード例 #3
0
def calc():
    f = float(en.get()) + float(en1.get()) + float(en2.get()) + float(
        en3.get())
    f1 = float(en4.get()) + float(en5.get()) + float(en6.get()) + float(
        en7.get())
    f2 = float(en8.get()) + float(en9.get()) + float(en10.get()) + float(
        en11.get())
    summa = round(eval('(f + f1 + f2) *10 /4 /3 /10'), 2)

    lb_pb = Label(window, text="КРУТОСТЬ ФИЛЬМА", bg=BGRA)
    lb_pb.place(x=25, y=230)
    bar = Progressbar(window,
                      orient="horizontal",
                      mode="determinate",
                      maximum=10)
    bar.place(x=25, y=260)
    bar['value'] = summa
    window.update()

    lb_sum = Label(window, text='ОЦЕНКА ЗА ФИЛЬМ ТУТ', bg=BGRA)
    lb_sum.place(x=185, y=230)
    lb_sum1 = Label(window, text=bar['value'], bg=BGRA)
    lb_sum1.place(x=185, y=260)

    lb_ser = Label(window, text=f, bg=BGRA)
    lb_ser.place(x=170, y=15)

    lb_lex = Label(window, text=f1, bg=BGRA)
    lb_lex.place(x=245, y=15)

    lb_sur = Label(window, text=f2, bg=BGRA)
    lb_sur.place(x=318, y=15)
コード例 #4
0
def deleteAll():
    en.delete(0, END)
    en1.delete(0, END)
    en2.delete(0, END)
    en3.delete(0, END)
    en4.delete(0, END)
    en5.delete(0, END)
    en6.delete(0, END)
    en7.delete(0, END)
    en8.delete(0, END)
    en9.delete(0, END)
    en10.delete(0, END)
    en11.delete(0, END)

    lb_ser = Label(window, text='         ', bg=BGRA)
    lb_ser.place(x=170, y=15)
    #lb_ser['text'] = '         '

    lb_lex = Label(window, text='         ', bg=BGRA)
    lb_lex.place(x=245, y=15)

    lb_sur = Label(window, text='         ', bg=BGRA)
    lb_sur.place(x=318, y=15)

    lb_sum1 = Label(window, text='         ', bg=BGRA)
    lb_sum1.place(x=185, y=260)

    bar = Progressbar(window,
                      orient="horizontal",
                      mode="determinate",
                      maximum=10)
    bar.place(x=25, y=260)
    bar['value'] = 0
    window.update()
コード例 #5
0
def upload():
    quantity = 0
    username = e_login.get()
    password = e_password.get()
    progress = Progressbar(window,
                           orient=HORIZONTAL,
                           length=100,
                           mode='determinate')
    progress["maximum"] = length_onlyfiles
    progress.place(y=190, x=197)
    with client(username, password) as cli:
        while quantity < length_onlyfiles:
            file_da_caricare = (filename + "/" + onlyfiles[quantity])
            info_file1 = str(quantity + 1)
            info_quantity = str(length_onlyfiles)
            info_file2 = ("[" + info_file1 + "/" + info_quantity + "] " +
                          file_da_caricare)
            print(info_file2)
            time.sleep(1)
            cli.upload(file_da_caricare)
            quantity += 1
            global gaythanos
            bo2 = str(quantity + 1)
            gaythanos = ("Uploading... " + "[" + bo2 + "/" + info_quantity +
                         "] ")
            progress['value'] = quantity
コード例 #6
0
        def moveFiles():

            # creating the folders
            if images:
                createIfNotExist(f'{filePath}/Images')
            if zips:
                createIfNotExist(f'{filePath}/Zip')
            if docs:
                createIfNotExist(f'{filePath}/Docs')
            if medias:
                createIfNotExist(f'{filePath}/Media')
            if softwares:
                createIfNotExist(f'{filePath}/Software')
            if extras:
                createIfNotExist(f'{filePath}/Extras')

            # moving files to respective folders
            for image in images:
                shutil.move(f"{filePath}/{image}",
                            f"{filePath}/Images/{image}")

            for zip in zips:
                shutil.move(f"{filePath}/{zip}", f"{filePath}/Zip/{zip}")

            for doc in docs:
                shutil.move(f"{filePath}/{doc}", f"{filePath}/Docs/{doc}")

            for media in medias:
                shutil.move(f"{filePath}/{media}", f"{filePath}/Media/{media}")

            for software in softwares:
                shutil.move(f"{filePath}/{software}",
                            f"{filePath}/Software/{software}")

            for extra in extras:
                shutil.move(f"{filePath}/{extra}",
                            f"{filePath}/Extras/{extra}")

            progress = Progressbar(root,
                                   orient="horizontal",
                                   length=300,
                                   mode="determinate")
            progress.place(x=70, y=300)

            for i in range(1, 100, 1):
                progress['value'] = i
                root.update_idletasks()
                time.sleep(0.02)
            progress['value'] = 100
            progress.destroy()

            doneLabel = Label(root, image=tickPhoto, bg="white")
            doneLabel.place(x=180, y=320)

            resultLabel = Label(root,
                                text="Done !!",
                                font=('arial', 16, 'bold'),
                                bg="white",
                                fg="green")
            resultLabel.place(x=180, y=380)
コード例 #7
0
 def click_scan_button():
     result_label['text'] = ''
     input_site = entry_id.get()
     if len(input_site) < 5 or '.' not in input_site:
         scanning_label['text'] = 'Enter a valid website!'
     else:
         scanning_label['text'] = 'Scanning in progress...'
         style = Style()
         style.configure("black.Horizontal.TProgressbar",
                         foreground='black',
                         background='black')
         progress_bar = Progressbar(frame_results_website,
                                    orient='horizontal',
                                    mode='determinate',
                                    style='black.Horizontal.TProgressbar')
         progress_bar.place(relx=0.15,
                            rely=0.43,
                            relwidth=0.7,
                            relheight=0.2)
         run_progress_website(progress_bar)
         if progress_bar['value'] == progress_bar['maximum']:
             prediction = detect_url.load_model_and_predict(
                 'model_data/model.pkl', 'model_data/vectorizer.pkl',
                 [input_site])
             scanning_label['text'] = 'Scan Finished!'
             if prediction[0] == 'good':
                 result_label['text'] = 'Trusty website.'
             else:
                 result_label['text'] = 'On your Risk!'
コード例 #8
0
class load_class:
    def __init__(self):
        self.rt = Tk()
        self.rt.title("YOUR BANKING SOLUTIONS")
        self.rt.config(background="#ccffcc")
        self.rt.geometry("1145x500+160+100")
        #self.rt.geometry("920x450+200+180")

        self.l1 = Label(self.rt)
        self.l1.place(relx=0.25, rely=0.0, height=200, width=650)
        self.l1.config(background="#ccffcc")
        img1 = ImageTk.PhotoImage(Image.open("bank_images/load.gif"))
        self.l1.configure(image=img1)

        self.label1 = Label(self.rt)
        self.label1.place(relx=0.26, rely=0.29, height=200, width=650)
        self.label1.config(background="#ccffcc")
        imgq = ImageTk.PhotoImage(Image.open("bank_images/l.gif"))
        self.label1.configure(image=imgq)

        self.v1 = IntVar()  #has the current value of progressbar

        self.l2 = Label(self.rt)
        self.l2.place(relx=0.06, rely=0.71, height=40, width=380)
        self.l2.configure(background="#ccffcc")
        self.l2.configure(width=380)

        self.pb = Progressbar(self.rt, orient=HORIZONTAL)
        self.pb.configure(mode='determinate', maximum=100)
        self.pb.configure(variable=self.v1)

        self.pb.place(relx=0.08,
                      rely=0.80,
                      relwidth=0.90,
                      relheight=0.0,
                      height=49)
        self.pb.configure(length="650")

        tup = (101, )
        self.t1 = threading.Thread(target=self.move, args=tup, name='first')
        self.t1.start()
        self.rt.after(500, self.check)
        self.rt.mainloop()

    def move(self, a):
        for i in range(a):
            self.v1.set(i)
            self.l2.configure(text="Loading " + str(self.v1.get()) + "%")
            time.sleep(0.01)

    def check(self):
        if self.v1.get() != 100:
            self.rt.after(500, self.check)
        else:
            self.rt.destroy()
            object = Login_new.Login_Class()


#ob=load_class()
コード例 #9
0
ファイル: main_3.py プロジェクト: csbsvnnq/labs
    def install(self, items, entry_path):
        if entry_path == "":
            mb.showwarning("Внимание",
                           "Вы не указали путь для установки программы.")
            return

        if path.exists(entry_path) is False:
            mb.showerror(
                "Ошибка",
                "Указаного пути не существует, выберите другой путь!")
            return

        status = False
        try:
            my_signature = str(GetComputerName()) + " | " + str(
                GetWindowsDirectory()) + " | " + str(
                    GetSystemMetrics(0)) + " | " + str(
                        GetSystemMetrics(1)) + " | " + str(
                            GetSystemDirectory()) + " | " + str(getlogin())
            my_signature = sha512(my_signature.encode()).hexdigest()

            try:
                winkey = CreateKey(HKEY_CURRENT_USER,
                                   "Software\\Ervin Abkerimov")
            except:
                winkey = OpenKey(HKEY_CURRENT_USER,
                                 "Software\\Ervin Abkerimov", 0,
                                 KEY_ALL_ACCESS)

            SetValueEx(winkey, "MY SIGNATURE", 0, REG_SZ, my_signature)
            winkey.Close()

            #Repo.clone_from(url='http://*****:*****@github.com/user/any.git', to_path=entry_path)
        except:
            pass
        else:
            status = True

        for i in items:
            i.destroy()

        label_info = Label(
            root,
            text="Программа будет установлена в: {}".format(entry_path),
            font=("Times new Roman", 12))
        label_info.place(x=15, y=70)
        progressbar = Progressbar(root,
                                  orient="horizontal",
                                  length=500,
                                  mode="determinate")
        progressbar.place(x=15, y=100)

        items = [label_info, progressbar]
        self.button_back.config(command=lambda: self.choose_path(items))
        self.button_next.config(
            text="Установить",
            command=lambda: self.process_install(status, items))
コード例 #10
0
def ipFinder(self, text, Lookup_ipaddr, ip):
    Lookup_ipaddr.destroy()
    # ip = input(" Adresse IP: ")

    # Progress bar widget
    progress = Progressbar(self,
                           orient=HORIZONTAL,
                           length=200,
                           mode='determinate')
    progress.place(x=350, y=300)
    l2 = Label(self, text=" Locating {0}...".format(ip))
    l2.place(x=350, y=200)
    # print("\n"+wait+" Locating '%s'..." % (ip))

    TABLE_DATA = []

    url = "http://ip-api.com/json/"
    data = requests.get(url + ip).content.decode('utf-8')
    values = json.loads(data)

    progress['value'] = 20
    self.update_idletasks()
    time.sleep(0.1)

    status = values['status']

    if status != "success":
        messagebox.showerror("Invalid!", " Adresse IP invalid.")
        progress['value'] = 50
        self.update_idletasks()
        time.sleep(0.1)
        progress.destroy()
        l2.destroy()

    else:
        text.insert(END, "[ %s ]" % (ip))
        text.insert(END, "\n IP: " + ip)
        # text.insert(END,"\n Hostname: " + values['ipName'])
        text.insert(END, "\n ISP: " + values['isp'])
        text.insert(END, "\n Organisation: " + values['org'])
        text.insert(END, "\n Pays: " + values['country'])
        text.insert(END, "\n Region: " + values['region'])
        text.insert(END, "\n Ville: " + values['city'])
        localisation = str(values['lat']) + ',' + str(values['lon'])
        text.insert(END, "\n Localisation: " + localisation)
        text.insert(
            END, "\n Maps: https://www.google.fr/maps?q=%s" % (localisation))
        progress['value'] = 100
        self.update_idletasks()
        time.sleep(0.1)
        progress.destroy()
        l2.destroy()
コード例 #11
0
class TKProgress:
    """Create initial button"""
    def __init__(self, win, x, y):
        self.posx = x
        self.posy = y
        self.progress = Progressbar(win, length=200, mode='determinate')
        self.progress.place(x=self.posx, y=self.posy)

    def get_position(self):
        return (self.posx, self.posy)

    def set_progress(self, value):
        self.progress['value'] = value
コード例 #12
0
class Loading_class:
    def __init__(self):
        self.top = Tk()
        self.top.geometry("791x376+268+88")
        self.top.title("BANKING SOLUTIONS")
        self.top.configure(background="#FFFFCC")

        self.Label1 = Label(self.top)
        self.Label1.place(relx=0.24, rely=0.0, height=82, width=443)
        self.Label1.configure(background="#FFFFCC")
        img1 = ImageTk.PhotoImage(Image.open("images/rahul2.jpg"))
        self.Label1.configure(image=img1)

        self.v1 = IntVar()  #it will hold the current value of progress bar

        self.Label2 = Label(self.top)
        self.Label2.place(relx=0.08, rely=0.43, height=41, width=374)
        self.Label2.configure(background="#FFFFCC")
        self.Label2.configure(width=374)

        self.pb = Progressbar(self.top, orient=HORIZONTAL)
        self.pb.config(mode='determinate', maximum=100)
        self.pb.config(variable=self.v1)

        self.pb.place(relx=0.08,
                      rely=0.56,
                      relwidth=0.87,
                      relheight=0.0,
                      height=22)
        self.pb.configure(length="690")
        tup = (101, )
        self.t1 = threading.Thread(target=self.move, args=tup, name='first')
        self.t1.start()
        self.top.after(500, self.check)
        self.top.mainloop()

    def move(self, a):
        for i in range(a):
            self.v1.set(i)
            self.Label2.configure(text='LOADING ' + str(self.v1.get()) + '%')
            time.sleep(.05)

    def check(self):
        if self.v1.get() != 100:
            self.top.after(500, self.check)
        else:
            self.top.destroy()
            o1 = Login.Login_Class()


#obj = Loading_class()
コード例 #13
0
def refresh_server_code():
    url = 'http://192.168.1.78:2350/login/request/mac/qr'
    try:
        response = str(requests.get(url).content)

        if 'true' in response:
            print('logged in')

            displayWeixinQr.place_forget()
            hint.place_forget()
            notice.place_forget()

            p = Progressbar(root,
                            orient=HORIZONTAL,
                            length=200,
                            mode="determinate",
                            takefocus=True,
                            maximum=100)
            p.place(relx=0.5, rely=0.5, anchor=CENTER)

            p['value'] = 0
            root.update()
            sleep(0.5)

            p['value'] = 20
            root.update()
            sleep(0.5)

            p['value'] = 40
            root.update()
            sleep(0.5)

            p['value'] = 60
            root.update()
            sleep(0.5)

            p['value'] = 80
            root.update()
            sleep(0.5)

            p['value'] = 100
            root.update()
            subprocess.call(['open', '/Applications/WeChat.app'])
            root.destroy()
        else:
            pass
    except:
        pass

    root.after(ms=2500, func=refresh_server_code)
コード例 #14
0
def progBar():
    lb_pb = Label(window, text="КРУТОСТЬ ФИЛЬМА", bg=BGRA)
    lb_pb.place(x=25, y=230)
    bar = Progressbar(window,
                      orient="horizontal",
                      mode="determinate",
                      maximum=10)
    bar.place(x=25, y=260)
    bar['value'] = 0
    window.update()

    lb_sum = Label(window, text='ОЦЕНКА ЗА ФИЛЬМ ТУТ', bg=BGRA)
    lb_sum.place(x=185, y=230)
    lb_sum1 = Label(window, text=bar['value'], bg=BGRA)
    lb_sum1.place(x=185, y=260)
コード例 #15
0
def convert_txt_to_HW():
    text = txt2.get("1.0", END)
    ts = time.time()
    dat = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d')
    timeStam = datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S')
    Hour, Minute, Second = timeStam.split(":")
    fileN = "./results/" + dat + "_" + Hour + "-" + Minute + "-" + Second + ".png"
    img_txt = kit.text_to_handwriting(text, fileN, rgb=color_result_rgb)

    def bar():
        progress['value'] = 20
        windo.update_idletasks()
        time.sleep(1)
        progress['value'] = 40
        windo.update_idletasks()
        time.sleep(1)
        progress['value'] = 60
        windo.update_idletasks()
        time.sleep(1)
        progress['value'] = 80
        windo.update_idletasks()
        time.sleep(1)
        progress['value'] = 100
        windo.update_idletasks()
        progress.destroy()

    progress = Progressbar(windo,
                           orient=HORIZONTAL,
                           length=100,
                           mode='determinate')
    progress.place(x=770, y=652)
    bar()

    conv_text_lbl.config(text="Handwritten Text",
                         width=15,
                         height=2,
                         fg="#00FF89",
                         bg="blue",
                         font=('segou UI', 16, ' bold'))
    conv_text_lbl.place(x=990, y=157)

    im2 = PIL.Image.open(fileN)
    im2 = im2.resize((887, 402), PIL.Image.ANTIALIAS)
    sp_img2 = ImageTk.PhotoImage(im2)
    panel6.config(image=sp_img2)
    panel6.image = sp_img2
    panel6.pack()
    panel6.place(x=1005, y=237)
コード例 #16
0
def loading(raiz):
    '''
    :param raiz: Recibe una dirección a la interfáz gráfica principal de la aplicación
    :return: No devuelve nada
    '''
    #print("raiz = " .format(raiz))
    progressAttackWindow = Toplevel(raiz)
    progressAttackWindow.title("SSHAttack progreso")
    progressAttackWindow.wm_resizable(0, 0)
    progressAttackWindow.geometry("300x300")
    progressbar = Progressbar(progressAttackWindow)
    progressbar.place(x=30, y=60, width=200)
    progressbar.start(10)
    # print("Salgo de loading")

    #def loadingStop(raiz):
    '''
コード例 #17
0
class loading_class:
    def __init__(self):
        self.root=Tk()
        self.root.geometry('700x600+350+100')
        self.root.config(bg='gray85')
        self.root.resizable(False, False)
        
        img=Image.open('d:/2.jpg')
        img1=img.resize((100,100),Image.ANTIALIAS)
        a=ImageTk.PhotoImage(img1)
        self.l1=Label(self.root,text='SG.. BANKS',bg='gray85',foreground='gray20',font=('Times New Roman',54,'bold','underline'),image=a,compound='left')
        
        img=Image.open('d:/4.jpg')
        img1=img.resize((700,300),Image.ANTIALIAS)
        b=ImageTk.PhotoImage(img1)
        self.l2=Label(self.root,text='Your Application Is Now Loading',bg='gray85',foreground='gray40',font=('italic',20,'bold'),image=b,compound='center')
        
        self.l1.place(x=110,y=10)
        self.l2.place(x=0,y=150)
        
        self.l3=Label(self.root,text='loading 1%',bg='gray85',foreground='gray40',font=('italic',15,'bold'))
        self.l3.place(x=100,y=480)
        
        self.v1=IntVar()
        self.v1.set(1)
        self.p1=Progressbar(self.root,mode='determinate',orient='horizontal',length=500,variable=self.v1)
        self.p1.place(x=100,y=520)
        self.t1=Thread(target=self.run,name='progressbar',args=(101,))
        self.t1.start()
        self.root.after(500, self.target)
        self.root.mainloop()
        
        
    def run(self,a):
        for i in range(a):
            self.v1.set(i)
            self.l3.config(text='loading {0}%'.format(i))
            time.sleep(0.05) 
        
    def target(self):
        if int(self.v1.get())==100:
            self.root.destroy() 
            a1=admin.admin_class()
        else:
            self.root.after(500,self.target)
コード例 #18
0
def hashSlashAndStoreWithPath(topFolderPath, numberOfFiles):
    global root
    global c
    global conn
    filesHashed = 0
    ext = ["rgb", "gif", "pbm", "pgm", "ppm", "tiff", "rast", "xbm", "jpeg", "bmp", "png", "webp", "exr"]

    # clear main window
    for widget in root.winfo_children():
        widget.destroy()

    # add label teeling user number of images hashed
    textImagesHashed = "About to begin hashing of images ..."
    labelImagesHashed = Label(root, text=textImagesHashed)
    labelImagesHashed.place(relx=0.5, rely=0.3, anchor=CENTER)

    textFilenameShow = ""
    labelFilenameShow = Label(root, text=textFilenameShow)
    labelFilenameShow.place(relx=0.5, rely=0.7, anchor=CENTER)

    # add progress bar showing number of images hashed
    progressBar = Progressbar(root, orient = HORIZONTAL, 
                length = 350, mode = 'determinate') 
    progressBar.place(relx=0.5, rely=0.5, anchor=CENTER)

    for dirpath, dirs, files in os.walk(topFolderPath):
        for fil in files:
            filename = os.path.join(dirpath,fil)
            if str(imghdr.what(str(filename))) in ext:
                openImage = Image.open(filename)
                c.execute("INSERT INTO pathandhashtb VALUES (?,?)", (str(filename), str(imagehash.average_hash(openImage))))
                openImage.close()
                
                filesHashed = filesHashed + 1
                textImagesHashed = str(filesHashed) + "/" + str(numberOfFiles) + " images hashed"
                labelImagesHashed["text"] = textImagesHashed

                textFilenameShow = str(fil)
                labelFilenameShow["text"] = textFilenameShow

                progressBar['value'] = int((filesHashed/numberOfFiles)*100)
                root.update_idletasks()
                conn.commit()

    getSameImagesFromDB()
コード例 #19
0
 def first_download_page(self, font):
     all_objects = []
     text = Label(self.window, text="Загрузка списка друзей", font=(font, 15))
     text.place(x=250, y=160)
     all_objects.append(text)
     self.users = self.me.friends + [self.me]
     bar = Progressbar(self.window, length=200)
     all_objects.append(bar)
     bar['value'] = 0
     bar["maximum"] = len(self.users)
     bar.place(x=252, y=200)
     for i, user in enumerate(self.users):
         image = user.image
         name = user.first_name
         bar['value'] = i
     self.vk.save_cache()
     destroy_all_objects(all_objects)
     self.draw_second_page(font)
コード例 #20
0
def Widgets():
    url = Label(root, text="YouTube link :", bg="red", fg="white")
    url.place(x=50, y=60, height=30)

    linkTxt = Entry(root, textvariable=video_Link)
    linkTxt.place(x=160, y=60, height=30, width=250)

    destination_lbl = Label(root, text="Destination :", bg="red", fg="white")
    destination_lbl.place(x=50, y=100, height=30)

    destination_Txt = Entry(root, textvariable=download_Path)
    destination_Txt.place(x=160, y=100, height=30, width=200)

    browse_Btn = Button(root,
                        text="Browse",
                        command=Browse,
                        bg="blue",
                        fg="white")
    browse_Btn.place(x=370, y=105)

    Download_Btn = Button(root,
                          text="Download",
                          command=Download,
                          bg="green",
                          fg="white",
                          activebackground="orange")
    Download_Btn.place(x=180, y=180, height=35, width=80)

    cancel_btn = Button(root,
                        text="cancel",
                        command=quit,
                        bg="grey",
                        fg="white",
                        activebackground="purple")
    cancel_btn.place(x=300, y=180, height=35, width=100)

    progress_bar = Progressbar(root,
                               orient=HORIZONTAL,
                               length=590,
                               mode='determinate')
    progress_bar.place(x=40, y=250, height=25, width=400)
    label = Label(root, text="Status", bg="brown", fg="white").place(x=200,
                                                                     y=280)
コード例 #21
0
def browse_action_page():
    ## create new frame
    frame_results_file = tk.Frame(root, bg='#60ba74')
    frame_results_file.place(relx=0.1, rely=0.4, relheight=0.5, relwidth=0.8)
    cwd = os.getcwd()
    ##getting database to calculate len for printing output
    database = database_logic.import_data_from_database(
        'database/malware_file_samples.data')
    ## getting filname with path from selecting in browse a file mode
    filename = filedialog.askopenfilename(initialdir=cwd,
                                          title='Select a file')
    ## if file im outputing all stuff that i need, label, progressbar, label_result
    if filename:
        ## Label for progress bar
        progress_label = tk.Label(frame_results_file, bg='#60ba74', font=33)
        progress_label['text'] = 'Scanning in progress...'
        progress_label.place(relx=0.29, rely=0.07, relwidth=0.4, relheight=0.2)
        ## style for progressbar basically i need black color
        style = Style()
        style.configure("black.Horizontal.TProgressbar",
                        foreground='black',
                        background='black')
        ## creating progress bar
        progress_bar = Progressbar(frame_results_file,
                                   orient='horizontal',
                                   mode='determinate',
                                   style='black.Horizontal.TProgressbar')
        progress_bar.place(relx=0.15, rely=0.33, relwidth=0.7, relheight=0.2)
        # creating result label to print
        result_label = tk.Label(frame_results_file, bg='#60ba74', font=40)
        result_label['text'] = ''
        result_label.place(relx=0.24, rely=0.66, relwidth=0.5, relheight=0.2)
        ## run progress bar
        run_progress(progress_bar, database)
        ## progressbar works until len(database) so i decide to print when its finished
        if progress_bar['value'] == len(database):
            detect_logic = detect_file.threaded_logic(filename)
            progress_label['text'] = 'Scan Finished!'
            result_label['text'] = detect_logic
        return detect_logic
    else:
        pass
コード例 #22
0
def load():
    global i, progress, loadingLabel
    loadingLabel = Label(mainWindow,
                         text='',
                         font=('arial', 10, 'bold'),
                         fg='blue')
    loadingLabel.place(x=400, y=420)
    progress = Progressbar(mainWindow,
                           orient=HORIZONTAL,
                           length=250,
                           mode='determinate')
    progress.place(x=150, y=420)
    if i <= 10:
        txt = str(10 * i) + '%'
        loadingLabel.config(text=txt)
        loadingLabel.after(1000, load)
        progress['value'] = int(10 * i)
        i += 1
    if progress['value'] == 100:
        getName()
コード例 #23
0
 def callback():
     progress = Progressbar(root,
                            orient=HORIZONTAL,
                            length=100,
                            mode='determinate')
     progress.pack()
     progress.place(x=10, y=200)
     request = urllib.request.urlopen(url)
     filename = str(
         file_name_field.get())  ##filename will be the basepath of url
     meta = request.info(
     )  ## get information from request object used for determining size of content
     file_size = int(meta['Content-Length'])
     buffer_size = file_size / segments
     file_name1.configure(text="Filename: " + filename)
     print("File size : {0:.2f}".format(float(
         (file_size / 1024) / 1024)))  ## get file size in MB
     file_download_size.configure(
         text="File Size: {0:.2f} MB".format((file_size / 1024) / 1024))
     total_download = 0
     fd = open(filename, 'wb')  ## save file to current working directory
     while total_download != file_size:
         buffer = request.read(
             int(buffer_size))  ## reading files upto buffer_size
         fd.write(buffer)
         total_download += len(buffer)
         cur_download.configure(text="Downloaded {0}%".format(
             math.trunc((int(total_download) / int(file_size)) * 100)))
         progress['value'] = math.trunc(
             (int(total_download) / int(file_size)) *
             100)  ## To retrieve percentage of download
     print("Download success")
     fd.close()
     file_download_size.destroy()
     file_name1.destroy()
     progress.destroy()
     cur_download.destroy()
     messagebox.showinfo(
         "File Downloaded",
         "Your file {0} has been saved in current directory".format(
             filename))
コード例 #24
0
        def create_result():
            nonlocal for_destroy
            destroy_all_objects(for_destroy)
            ind1 = names.index(combobox1.get())
            ind2 = names.index(combobox2.get())
            user1 = self.users[ind1]
            user2 = self.users[ind2]

            bar = Progressbar(self.window, length=200)
            bar['value'] = 0
            bar["maximum"] = 100
            bar.place(x=200, y=200)
            score, description = UsersComparator(user1, user2, bar).compare()
            description += "\n\n Итоговый счёт: " + str(int(score))
            print(int(score))
            text = Label(self.window, text="Результаты сравнения", font=(font, 18))
            text.place(x=200, y=150)
            for_destroy.append(text)

            text = Label(self.window, text=description, font=(font, 10))
            text.place(x=5, y=180)
            for_destroy.append(text)
            self.wait = False
コード例 #25
0
def go_():
    messagebox.showinfo(
        'INFO', 'For better result turn \n on the internet connection')
    global bar, label, top, quote, status
    top = Toplevel(root, bg='black')
    top.title('progress...')
    top.geometry('500x300')

    top.iconbitmap('.img\\photo2.ico')
    style = ttk.Style()
    style.theme_use('vista')
    style.configure("black.Horizontal.TProgressbar", background='blue')
    bar = Progressbar(top, length=200, style='black.Horizontal.TProgressbar')
    bar['value'] = 0
    bar.place(relx=0.3, rely=0.07)
    status = Label(top, bg='black', fg='white')
    status.place(relx=0.13, rely=0.07)

    label = Label(top, bg='black', fg='white')
    label.place(relx=0.45, rely=0.2)
    quote = Label(top,
                  font=('Arial', 12),
                  text=quotes_list[random.randint(0,
                                                  len(quotes_list) - 1)],
                  bg='black',
                  fg='white',
                  justify=CENTER,
                  anchor=CENTER)
    quote.place(relwidth=1, relx=0, rely=0.4, relheight=0.6)
    result_box2.delete('1.0', END)
    result_box1.delete('1.0', END)
    if pos.get() == -1:
        Thread(target=start).start()
    else:
        Thread(target=start, args=(pos.get(), )).start()
        pos.set(-1)
コード例 #26
0
    l4.config(font=lst4)
    l4.place(x=18, y=210)

    import time
    r = 0
    for i in range(100):
        progress['value'] = r
        w.update_idletasks()
        time.sleep(0.03)
        r = r + 1
        print(f"Loading.. {r} %")
    w.destroy()
    LoadingSuccess()


progress.place(x=-10, y=235)


def printlen(event):
    print("Opps you touch me ! >//<")


'''

def rgb(r):
    return "#%02x%02x%02x" % r
#Frame(w,width=432,height=241,bg=rgb((100,100,100))).
'''
# a='#249794'
a = '#18de98'
Frame(w, width=427, height=241, bg=a).place(x=0, y=0)  #249794
コード例 #27
0
class InpaintApp(Frame):
    def __init__(self):
        super().__init__()

        self.initInpaintUI()

    def initInpaintUI(self):
        self.master.title("Fill Your Face")

        self.pack(fill=BOTH, expand=True)

        self.columnconfigure(1, weight=1)
        self.columnconfigure(4, pad=2)
        self.rowconfigure(4, weight=1)
        self.rowconfigure(5, pad=2)

        lbl = Label(self, text="Please select a mask type & face to fill.")
        lbl.grid(sticky=W, pady=4, padx=5)

        wbtn = Button(self, text="Choose Folder", command=self.saveLoc)
        wbtn.place(x=10, y=30)

        # variables
        self.save_loc = None
        self.chosen_img = None
        self.completed_img = None
        self.msk = None

        self.lr = config.learning_rate
        self.moment = config.momentum
        self.nitrs = config.niters
        self.l2loss = False
        self.saveEaItr = False  # saves images after ea iteration to visualize manifold
        self.weighted_mask = config.weighted_mask

        self.show_mskedim = False

        self.saveMask = IntVar()  # checkboxes whether to save as image
        self.saveMaskedIm = IntVar()

        # buttons right
        abtn = Button(self, text="Select Image", command=self.openImg)
        abtn.grid(row=2, column=4, padx=5, pady=5)

        abtn = Button(self, text="Random Image", command=self.getRandImg)
        abtn.grid(row=1, column=4, padx=5, pady=5)

        # choose mask
        choices = {'Center', 'Random', 'Half'}
        self.mask_type = StringVar(root)
        self.mask_type.set("Select Mask Type")
        popupMenu = OptionMenu(self,
                               self.mask_type,
                               *choices,
                               command=self.display_mask)
        popupMenu.grid(row=1, column=3, padx=5)

        dmbtn = Button(self,
                       text="Display Masked Image",
                       command=self.display_masked_img)
        dmbtn.grid(row=2, column=3, padx=5)

        # buttons lower
        hbtn = Button(self, text="Help", command=self.clickHelp)
        hbtn.grid(row=5, column=0, padx=5, pady=5)

        wbtn = Button(self, text="Settings", command=self.setParams)
        wbtn.grid(row=5, column=1)

        Button(self, text="Save Image(s)", command=self.saveImg).grid(row=5,
                                                                      column=2,
                                                                      padx=5,
                                                                      pady=5)

        obtn = Button(self, text="Start Inpaint", command=self.start_inpaint)
        obtn.grid(row=5, column=3, padx=5, pady=5)

        cbtn = Button(self, text="Quit", command=self.ExitApplication)
        cbtn.grid(row=5, column=4, padx=5, pady=5)

        # progress bar
        Label(self, text="Inpainting Progress:").place(x=40, y=260)
        self.progressbar = Progressbar(self, length=500)
        # self.progressbar.config(mode = 'determinate',  maximum=self.nitrs)
        self.progressbar.place(x=40, y=280)

    def ExitApplication(self):
        MsgBox = messagebox.askquestion(
            'Exit Application',
            'Are you sure you want to exit the application',
            icon='warning')
        if MsgBox == 'yes':
            root.destroy()

    def openImg(self):
        filename = filedialog.askopenfilename(
        )  # show an "Open" dialog box and return the path to the selected file
        if filename[-4:] == '.png' or filename[-4:] == 'jpeg' or filename[
                -4:] == '.jpg':
            img = Image.open(filename)
            self.blend_tar = np.asarray(img)  # for poisson blending later
            self.blend_tar.flags.writeable = True
            if img.size != (64, 64):
                messagebox.showwarning(
                    "Error", "Please choose a 64x64 rgb face image.\
                \n You can use openface to crop your image. Click Help for more info."
                )
                return
            self.chosen_img = np.asarray(img, dtype="float32")
            img = img.resize((100, 100), Image.ANTIALIAS)
            imgtk = ImageTk.PhotoImage(img)
            txt_lbl = Label(self, text="Your Image")
            txt_lbl.place(x=50, y=110)
            dis_img = Label(self, image=imgtk)
            dis_img.image = imgtk
            dis_img.place(x=50, y=127)
        else:
            messagebox.showwarning("Error",
                                   "Please select a png or jpeg image")

    def getRandImg(self):
        dataset = tf.data.TFRecordDataset(filenames="data.tfrecord")
        dataset = dataset.map(func.extract_fn)

        # dataset = tf.data.TFRecordDataset.from_tensor_slices(dataset)
        dataset = dataset.shuffle(buffer_size=300)
        dataset = dataset.batch(1)

        iterator = tf.data.Iterator.from_structure(dataset.output_types,
                                                   dataset.output_shapes)
        init_op = iterator.make_initializer(dataset)

        # batched data to feed in
        image_data = iterator.get_next()

        # visualize original data
        with tf.Session() as sess:
            sess.run(init_op)
            real_img = np.array(sess.run(image_data))
            rand_img = real_img[0, :, :, :]
            self.chosen_img = np.asarray(rand_img, dtype="float32")
            img = toimage(rand_img)
            self.blend_tar = np.asarray(img)  # for poisson blending later
            self.blend_tar.flags.writeable = True
            img = img.resize((100, 100), Image.ANTIALIAS)
            imgtk = ImageTk.PhotoImage(img)
            txt_lbl = Label(self, text="Your Image")
            txt_lbl.place(x=50, y=110)
            dis_img = Label(self, image=imgtk)
            dis_img.image = imgtk
            dis_img.place(x=50, y=127)

    def saveLoc(self):
        self.save_loc = filedialog.askdirectory()
        self.dis_save = Label(self, text='Save Location: ')
        self.dis_save.place(x=10, y=60)
        slength = len(self.save_loc)

        if slength > 40:
            self.dis_save['text'] += "..."
            self.dis_save['text'] += self.save_loc[-40:]
        else:
            self.dis_save['text'] += self.save_loc

    def saveImg(self):
        if self.completed_img is not None:
            im = toimage(self.completed_img)
            im = im.resize((250, 250), Image.ANTIALIAS)

            if self.save_loc is not None:
                # file = filedialog.asksaveasfile(mode='w', defaultextension=".jpg")
                uniq_filename = 'CompletedImg_' + str(
                    datetime.datetime.now().time()).replace(':', '.')
                filename = self.save_loc + '/' + uniq_filename + '.jpg'
                imageio.imwrite(filename, im)
                if self.saveMask.get():
                    uniq_filename = 'Mask_' + str(
                        datetime.datetime.now().time()).replace(':', '.')
                    filename = self.save_loc + '/' + uniq_filename + '.jpg'
                    mskimg = toimage(self.msk)
                    mskimg = mskimg.resize((250, 250), Image.ANTIALIAS)
                    imageio.imwrite(filename, mskimg)

                if self.saveMaskedIm.get():
                    uniq_filename = 'MaskedImg_' + str(
                        datetime.datetime.now().time()).replace(':', '.')
                    filename = self.save_loc + '/' + uniq_filename + '.jpg'
                    masked_img = preinpaint.get_masked_image(
                        self.msk, self.chosen_img)
                    masked_img = toimage(masked_img)
                    masked_img = masked_img.resize((250, 250), Image.ANTIALIAS)
                    imageio.imwrite(filename, masked_img)

                messagebox.showinfo("Success!", "Your image has been saved")
            else:
                messagebox.showwarning("Error",
                                       "Please choose folder to save image.")

        else:
            messagebox.showwarning("Error",
                                   "Please inpaint first to get image.")

    def display_mask(self, mask_type):
        if mask_type != "Select Mask Type":
            self.msk = preinpaint.make_mask(mask_type,
                                            weighted_mask=self.weighted_mask)
            # mskimg = Image.fromarray(msk, 'RGB')
            # dispmsk = preinpaint.make_mask(mask_type, weighted_mask=False)
            mskimg = toimage(self.msk)
            mskimg = mskimg.resize((100, 100), Image.ANTIALIAS)
            imgtk = ImageTk.PhotoImage(mskimg)
            txt_lbl = Label(self, text="Your Mask: ")
            txt_lbl.place(x=200, y=110)
            dis_img = Label(self, image=imgtk)
            dis_img.image = imgtk
            dis_img.place(x=200, y=127)
        else:
            messagebox.showwarning("Error", "Please select a mask first!")

    def display_masked_img(self):
        if self.chosen_img is not None and self.msk is not None:
            masked_img = preinpaint.get_masked_image(self.msk, self.chosen_img)
            masked_img = toimage(masked_img)
            masked_img = masked_img.resize((100, 100), Image.ANTIALIAS)
            imgtk = ImageTk.PhotoImage(masked_img)
            txt_lbl = Label(self, text="Masked Image: ")
            txt_lbl.place(x=350, y=110)
            dis_img = Label(self, image=imgtk)
            dis_img.image = imgtk
            dis_img.place(x=350, y=127)
            self.show_mskedim = True
        else:
            messagebox.showwarning("Error", "Please load image and mask")

    def start_inpaint(self):
        l2 = self.l2loss
        savegenerated = self.saveEaItr

        if self.chosen_img is not None and self.msk is not None:
            self.progressbar['value'] = 0
            self.progressbar.update_idletasks()

            img = preinpaint.preprocess(self.chosen_img)
            # print(img.dtype, np.amax(img), np.amin(img)) # debugging
            images = preinpaint.single_to_batch(img)
            masks = preinpaint.single_to_batch(self.msk)

            # gen_images, loss = inpaint.get_best_z_img(masks, images, iters=self.nitrs)
            # backprop to z
            z = np.random.randn(config.BATCH_SIZE, config.z_dim)
            vel = 0
            iters = self.nitrs
            r = self.lr
            momentum = self.moment

            self.progressbar.config(mode='determinate', maximum=self.nitrs)

            # load frozen graph
            graph, graph_def = func.loadpb("dcgan-100.pb")

            g_in = graph.get_tensor_by_name('dcgan/z:0')
            g_out = graph.get_tensor_by_name('dcgan/Tanh:0')
            g_loss = graph.get_tensor_by_name('dcgan/Mean_2:0')
            d_in = graph.get_tensor_by_name('dcgan/real_images:0')
            d_out = graph.get_tensor_by_name('dcgan/Sigmoid:0')

            with tf.Session(graph=graph) as sess:
                # create batches of masks & images to feed in
                mask_placeholder = tf.placeholder(
                    tf.float32,
                    shape=(config.BATCH_SIZE, config.image_size,
                           config.image_size, config.channels))
                # real image batches, use if own image input
                images_placeholder = tf.placeholder(
                    tf.float32,
                    shape=(config.BATCH_SIZE, config.image_size,
                           config.image_size, config.channels))

                inpaint_loss, gradient = inpaint.get_losses(
                    mask_placeholder, images_placeholder, g_in, g_out, g_loss,
                    l2)
                bests = []
                for i in range(iters):
                    # yield Label(self, text="Inpainting Progress:" + str(i)).place(x=40, y=280)
                    feed_dict = {
                        mask_placeholder: masks,
                        images_placeholder: images,
                        g_in: z
                    }
                    loss, grad, gen_images = sess.run(
                        (inpaint_loss, gradient, g_out), feed_dict=feed_dict)

                    grad = grad[0]

                    v_prev = vel
                    vel = v_prev * momentum - r * grad
                    # z += vel
                    z += vel * (
                        1 + momentum) - v_prev * momentum  # dampening momentum

                    z = np.clip(z, -1, 1)

                    # debugging -- save best gen img of ea. iteration
                    if savegenerated:
                        best = inpaint.get_best_generated(gen_images, loss)
                        bests.append(best)
                        for b in bests:
                            im = toimage(b)
                            im.save("generated/z_" + str(i) + ".jpg")

                    self.progressbar['value'] = i + 1
                    self.progressbar.update_idletasks()

            best_image = inpaint.get_best_generated(gen_images, loss)

            # poisson blending
            blend_src = np.asarray(toimage(best_image))

            mask = preinpaint.bin_inv_mask(self.msk)
            mask = np.asarray(toimage(mask))

            self.completed_img = postinpaint.blend(self.blend_tar, blend_src,
                                                   mask)
            # print(self.blend_tar.shape, blend_src.shape, mask.shape)
            # self.completed_img = inpaint.inpaint(img, best_image, self.msk)
            disp_img = toimage(self.completed_img)
            disp_img = disp_img.resize((128, 128), Image.ANTIALIAS)
            imgtk = ImageTk.PhotoImage(disp_img)
            txt_lbl = Label(self, text="Completed Image: ")
            txt_lbl.place(x=250, y=330)
            dis_img = Label(self, image=imgtk)
            dis_img.image = imgtk
            dis_img.place(x=250, y=347)

    def clickHelp(self):
        toplevel = Toplevel(root)
        toplevel.title("Help")
        with open("files/about.txt", "r") as f:
            Label(toplevel, text=f.read(), height=20, width=100).pack()

        def closetl():
            toplevel.destroy()

        Button(toplevel, text="Close", command=closetl).pack()

    def setParams(self):
        tl = Toplevel(root)
        tl.title("Set Parameters")
        Label(tl, text="Iterations: ").grid(row=0,
                                            column=0,
                                            sticky=W,
                                            padx=5,
                                            pady=3)
        self.iters = Entry(tl, width=10)
        self.iters.grid(row=0, column=1, padx=5, pady=3)
        Label(tl, text="Use weighted mask?: ").grid(row=1,
                                                    column=0,
                                                    padx=5,
                                                    pady=3)
        self.maskedbool = BooleanVar()
        Radiobutton(tl, text="Yes", variable=self.maskedbool,
                    value=True).grid(row=1, column=1)
        Radiobutton(tl, text="No", variable=self.maskedbool,
                    value=False).grid(row=1, column=2)
        # Checkbutton(tl, text="Use weighted mask?", variable=self.maskedbool).grid(row=1, column=3)
        ch1 = Checkbutton(tl, text="Save mask?", variable=self.saveMask)
        ch1.grid(row=2, column=0, padx=5, pady=7)
        ch2 = Checkbutton(tl,
                          text="Save masked image?",
                          variable=self.saveMaskedIm)
        ch2.grid(row=2, column=1, padx=5, pady=7)

        def closetl():
            tl.destroy()

        def changeParams():
            try:
                if int(self.iters.get()) > 0:
                    self.nitrs = int(self.iters.get())
                else:
                    messagebox.showwarning("Error",
                                           "You need at least 1 iteration.")
                self.weighted_mask = self.maskedbool.get()
                if self.mask_type.get() != "Select Mask Type":
                    self.display_mask(self.mask_type.get())
                    if self.show_mskedim:
                        self.display_masked_img()

                tl.destroy()
            except ValueError:
                self.weighted_mask = self.maskedbool.get()
                if self.mask_type.get() != "Select Mask Type":
                    self.display_mask(self.mask_type.get())
                tl.destroy()

        Button(tl, text="Ok", command=changeParams).grid(row=3,
                                                         column=2,
                                                         padx=5,
                                                         pady=3)
        Button(tl, text="Cancel", command=closetl).grid(row=3,
                                                        column=3,
                                                        padx=5,
                                                        pady=3)
コード例 #28
0
ファイル: gui.py プロジェクト: SamoJT/photo_sorter
class Gui:
    def __init__(self):
        self.CANVAS_WIDTH = 550
        self.CANVAS_HEIGHT = 250
        self.master = Tk()

        self.options_radio_btn = IntVar()
        self.settings_radio_btn = IntVar()
        self.settings = {'Files': 'Default', 'Hashing': False, 'Output': False}
        self.default_files = [
            'JPG', 'JPEG', 'PNG', 'GIF', 'RAW', 'MP4', 'MOV', 'AVI'
        ]
        self.target_dir = ''
        self.num_files = 0
        self.default = True
        self.out_list = []
        self._canvas_init()

    def main_loop(self):
        mainloop()

    def _run_logic(self, run):
        self.output_lb['state'] = NORMAL
        self.output_lb.insert(END, '*' * 20)
        while True:
            try:
                self.output_lb['state'] = NORMAL
                out = next(run)
                self.output_lb.insert(END, out)
                self.out_list.append(out)
                self.output_lb.see(END)
                self.output_lb['state'] = DISABLED
                self.progress_bar['value'] += 10
            except:
                break

        if self.settings['Output']:
            self._output(self.out_list)

        self.progress_bar['value'] = 100
        self.output_lb['state'] = NORMAL
        self.output_lb.insert(END, '-- Done --')
        self.out_list.append('-- Done --')
        self.output_lb.see(END)
        self.output_lb['state'] = DISABLED

    def _rename_1(self, allowed_files):
        self.output_lb['state'] = NORMAL
        self.output_lb.insert(END, '-- Renaming --')
        self.out_list.append('-- Renaming --')
        n_f = name_format.main(self.target_dir, allowed_files)
        self._run_logic(n_f)

    def _move_2(self, allowed_files):
        self.output_lb['state'] = NORMAL
        self.output_lb.insert(END, '-- Moving --')
        self.out_list.append('-- Moving --')
        d_m = date_move.main(self.target_dir, allowed_files,
                             self.settings['Hashing'])
        self._run_logic(d_m)

    def _both_3(self, allowed_files):
        self._rename_1(allowed_files)
        self._move_2(allowed_files)

    def _call_run(self):
        options = {1: self._rename_1, 2: self._move_2, 3: self._both_3}

        if self.settings['Files'] == 'Default':
            allowed_files = self.default_files
        else:
            allowed_files = 'All'

        options[self.options_radio_btn.get()](allowed_files)

    def _output(self, out_list):
        with open('output.txt', 'w') as f:
            for o in out_list:
                f.write(f'{o}\n')
        self.output_lb['state'] = NORMAL
        self.output_lb.insert(END, 'Output written to file: out.txt')
        self.output_lb.see(END)
        self.output_lb['state'] = DISABLED

    def _clear_frames(self, *f):
        for frame in f:
            for w in frame.winfo_children():
                w.destroy()

    def _output_labels(self):
        pass

    def _count_files(self, d):
        # pth, ds, fs = next(os.walk(d))  # Can be used if only current dir file tot is required
        f_tot = 0
        for pth, ds, fs in os.walk(d):
            for n in fs:
                f_tot += 1
        return f_tot

    def _get_dir(self):
        self.target_dir = askdirectory()
        if self.target_dir == '':
            self.default = True
            self._dynamic_labels(self.default, self.target_dir, self.num_files,
                                 self.settings)
            return
        self.num_files = self._count_files(self.target_dir)
        self.default = False
        self.progress_bar['value'] = 0
        self._dynamic_labels(self.default, self.target_dir, self.num_files,
                             self.settings)

    def _update_settings(self):
        if self.settings_radio_btn.get() == 4:
            f = 'Default'
        else:
            f = 'All'
        tmp = [f, self.h_var.get(), self.o_var.get()]
        c = 0
        for i in tmp:
            k = list(self.settings)[c]
            self.settings[k] = i
            c += 1

    def _apply_settings(self):
        self._clear_frames(self.settings_frame)
        self._dynamic_labels(self.default, self.target_dir, self.num_files,
                             self.settings)

    def _settings_window(self):
        win = Toplevel(self.master)
        win.title("Settings")
        win.geometry(f'{self.CANVAS_WIDTH-20}x{self.CANVAS_HEIGHT-60}')

        h_info = "Enables file hashing to check for duplicates. Enabling will increase run-time."
        o_info = "Outputs log info into a text file in current directory."
        default_info = f"{self.default_files}"
        all_info = "All file types. (Caution: ALL files will be renamed based on modified date)"
        custom_info = "Enter file types seperated by commas."
        self.h_var, self.o_var = BooleanVar(), BooleanVar()

        LabelFrame(win, text="Optional").place(x=15, y=5, height=70, width=500)
        hash_btn = Checkbutton(win,
                               text=f"Hashing - {h_info}",
                               var=self.h_var,
                               command=self._update_settings)
        hash_btn.place(x=20, y=20)
        out_btn = Checkbutton(win,
                              text=f"Output - {o_info}",
                              var=self.o_var,
                              command=self._update_settings)
        out_btn.place(x=20, y=40)

        LabelFrame(win, text="Allowed Files").place(x=15,
                                                    y=80,
                                                    height=70,
                                                    width=450)
        default_btn = Radiobutton(win,
                                  text=f"Default - {default_info}",
                                  var=self.settings_radio_btn,
                                  value=4,
                                  command=self._update_settings)
        default_btn.place(x=20, y=95)
        all_btn = Radiobutton(win,
                              text=f"All - {all_info}",
                              var=self.settings_radio_btn,
                              value=5,
                              command=self._update_settings)
        all_btn.place(x=20, y=115)
        if self.options_radio_btn.get() == 1:
            self.settings['Hashing'] = False
            hash_btn.deselect()
            hash_btn['state'] = DISABLED
            self._dynamic_labels(self.default, self.target_dir, self.num_files,
                                 self.settings)
            self._apply_settings()
        if self.settings['Files'] == 'Default':
            default_btn.select()
        elif self.settings['Files'] == 'All':
            all_btn.select()
        if self.settings['Hashing']:
            hash_btn.select()
        if self.settings['Output']:
            out_btn.select()

        Button(win, text="Apply",
               command=lambda: self._apply_settings()).place(x=15, y=150)
        # Potential future feature
        # Radiobutton(win, text=f"Custom - {custom_info}", var=self.radio_btn, value=3).place(x=20, y=105)

    def _frames(self):
        LabelFrame(self.master, text="Options").place(x=15,
                                                      y=5,
                                                      height=85,
                                                      width=90)
        LabelFrame(self.master).place(x=15, y=65, height=35,
                                      width=90)  # Both divider

        self.dir_frame = LabelFrame(self.master, text="Directory")
        self.dir_frame.place(x=150, y=5, height=45, width=300)

        self.out_frame = LabelFrame(self.master, text="Output")
        self.out_frame.place(x=300, y=55, height=105, width=200)

        self.settings_frame = LabelFrame(self.master, text="Enabled Settings")
        self.settings_frame.place(x=150, y=55, height=105, width=135)

        self.numF_frame = Frame(self.master)
        self.numF_frame.place(x=79, y=190, height=20, width=30)

    def _dynamic_labels(self, default, working_dir, file_num,
                        enabled_settings):
        if default:
            working_dir = "No directory selected"
            file_num = 0
        self._clear_frames(self.dir_frame, self.numF_frame)
        Label(self.dir_frame, text=working_dir).place(x=5, y=0)
        Label(self.numF_frame, text=file_num).place(x=0, y=0)

        y = 3
        for k in enabled_settings:
            if enabled_settings[k]:
                out = f"{k} - {enabled_settings[k]}"
                tmp = Label(self.settings_frame, text=out).place(x=5, y=y)
                y += 20

    def _static_labels(self):
        Label(self.master, text="Total Files: ").place(x=15, y=190)

    def _listbox(self):
        sb = Scrollbar(self.out_frame)
        sb.pack(side=RIGHT, fill=Y)
        self.output_lb = Listbox(self.out_frame,
                                 width=29,
                                 height=5,
                                 yscrollcommand=sb.set)
        self.output_lb.place(x=0, y=0)
        sb.config(command=self.output_lb.yview)
        self.output_lb['state'] = DISABLED

    def _radio_buttons(self):
        Radiobutton(self.master,
                    text="Rename",
                    var=self.options_radio_btn,
                    value=1).place(x=20, y=20)
        Radiobutton(self.master,
                    text="Move",
                    var=self.options_radio_btn,
                    value=2).place(x=20, y=40)
        bth = Radiobutton(self.master,
                          text="Both",
                          var=self.options_radio_btn,
                          value=3)
        bth.place(x=20, y=70)
        bth.select()

    def _push_buttons(self):
        Button(self.master,
               text="Settings",
               command=self._settings_window,
               width=11).place(x=15, y=105)
        Button(self.master,
               text="Go!",
               command=lambda: self._call_run(),
               width=11).place(x=15, y=135)
        Button(self.master, text="Select dir", command=self._get_dir,
               width=7).place(x=455, y=17)

    def _progress_bar(self):
        self.progress_bar = Progressbar(self.master,
                                        orient=HORIZONTAL,
                                        length=300,
                                        mode="determinate")
        self.progress_bar.place(x=150, y=190)

    def _canvas_init(self):
        self.master.resizable(width=False, height=False)
        self.master.title("Photo Sorter")
        # self.master.iconbitmap('../imgs/icon.ico')  # Throws not defined error.
        self.master.geometry(f'{self.CANVAS_WIDTH}x{self.CANVAS_HEIGHT}')

        self._frames()
        self._dynamic_labels(self.default, None, None, self.settings)
        self._static_labels()
        self._listbox()
        self._radio_buttons()
        self._push_buttons()
        self._progress_bar()

        # self.test_btn()

    def test_btn(self):
        Button(self.master, text="DEBUG",
               command=lambda: self.test()).place(x=470, y=200)

    def test(self):
        print("TESTING")
        print(
            f"Settings: {self.settings}\nOption: {self.options_radio_btn.get()}\nDir: {self.target_dir}"
        )

        self.output_lb['state'] = NORMAL
        i = ('test', '\n', 'test2')
        self.output_lb.insert(END, i)
コード例 #29
0
class LoadingPage(tk.Frame):

	def __init__(self, parent, controller):
		tk.Frame.__init__(self, parent)
		self.label = Label(self, text="")
		self.test_button = Button(self, text="Run", command=lambda: self.holder(controller))
		self.home_button = Button(self, text="Go to Metrics", command=lambda: [controller.show_frame(MetricsPage), self.reset(controller)])
		self.barVar = tk.DoubleVar()
		self.barVar.set(0)
		self.bar = Progressbar(self, length=400, variable=self.barVar)


		self.label.place(x=260, y=220)
		self.bar.place(x=100, y=240)
		self.test_button.place(x=260, y=270)
		self.home_button.pack(side=BOTTOM)

	def logic(self, controller):
		try:
			# print(StartPage.file)
			print(FILENAME)
			tweets = import_dataset(FILENAME)
			data_lemmatized = preprocess(tweets)
			lda(data_lemmatized)
		except Exception as e:
			print(FILENAME)
			raise e
			print("error")
			controller.show_frame(StartPage)

	def holder(self, controller):
		t1 = threading.Thread(target=self.logic, args=(controller, ))
		t1.start()
		t2 = threading.Thread(target=self.update_progressbar, args=(controller, ))
		t2.start()
		self.test_button.config(state=DISABLED)
		self.home_button.config(state=DISABLED)

	def update_progressbar(self, controller):
		print("test")
		x = self.barVar.get()
		if x < 100:
			time.sleep(1)
			if (x <= 25):
				self.label.place(x=240, y=220)
				self.label['text'] = 'Removing Stopwords...'
			elif (x > 25 and x <= 50):
				self.label.place(x=220, y=220)
				self.label['text'] = 'Correcting misspelled words...'
			elif (x > 50 and x <= 60):
				self.label.place(x=260, y=220)
				self.label['text'] = 'Lemmatizing...'
			elif (x > 60):
				self.label.place(x=260, y=220)
				self.label['text'] = 'Running LDA...'

			self.barVar.set(x+0.5)
			self.update_progressbar(controller)
		else:
			print("Complete")
			self.label.place(x=265, y=220)
			self.label['text'] = 'Finalizing...'
			self.home_button.config(state=NORMAL)

	def reset(self, controller):
		self.label['text'] = ''
		self.barVar.set(0)
		self.test_button.config(state=NORMAL)
コード例 #30
0
ファイル: Core.py プロジェクト: omaghd/wistia-downloader
class WistiaDownloaderCore():
    def __init__(self, master, videos, resolution, downloadFolder, btnBorderX,
                 btnBorderY):
        self.master = master
        self.videos = videos
        self.resolution = resolution
        self.resolution_list = ["224p", "360p", "540p", "720p", "Best Quality"]
        self.downloadFolder = downloadFolder
        self.URL = "http://fast.wistia.net/embed/iframe/"
        self.videoIndex = 1
        self.logs = ""

        self.btnBorderX = btnBorderX
        self.btnBorderY = btnBorderY

        if self.dataCheck():
            for video in self.videos:
                videoURL = self.URL + video.get('id')
                html_file = self.download_HTML_file(videoURL)
                self.html_page_handle_and_download(html_file, self.resolution,
                                                   video.get('name'))
            try:
                self.downloadLable.configure(text='Download Completed')
            except:
                pass
            messagebox.showinfo(
                "Wistia Downloader",
                "Download completed, check logs for any error.")

    def dataCheck(self):
        if not self.videos:
            messagebox.showinfo("Wistia Downloader",
                                "You need to enter at least one ID.")
            return 0
        if not self.resolution in self.resolution_list:
            messagebox.showinfo(
                "Wistia Downloader",
                "You have to select a resolution from the list.")
            return 0
        if not self.downloadFolder:
            messagebox.showinfo("Wistia Downloader",
                                "You need to select the download folder.")
            return 0
        return 1

    def download_HTML_file(self, url):
        local_filename = url.split('/')[-1]
        r = requests.get(url, stream=True)
        with open(local_filename, 'wb') as f:
            for chunk in r.iter_content(chunk_size=1024):
                if chunk:
                    f.write(chunk)
        return local_filename

    def html_page_handle_and_download(self, file_name, resolution, viedo_name):
        with open(file_name, "r") as file:
            i = 1
            for con in file:
                # ERROR
                if i == 1 and con == '{"error":true,"iframe":true}':
                    video_data = con
                if i == 63:
                    video_data = con
                    break
                i += 1
            if video_data == '{"error":true,"iframe":true}':
                self.logs += '{} ID {}, is not valid.\n'.format(
                    viedo_name, self.videoIndex)
                self.showLogs(self.logs)
                self.videoIndex += 1
            else:
                video_data = video_data.split('[')[1].split(']')[0]
                video_data = video_data.replace('},{', '}abdlalisalmi{')
                video_data_list = video_data.split('abdlalisalmi')

                video_url = None
                for video in video_data_list:
                    video_data_json = json.loads(video)
                    if video_data_json['display_name'] == resolution:
                        video_url = video_data_json['url']

                self.showProgressBar()
                self.downloadLable.configure(
                    text='{} is Downloading...'.format(viedo_name))

                if (video_url):
                    video_file_name = self.download_video(video_url)

                    video_name_and_index = "{}-{}".format(
                        str(self.videoIndex), viedo_name)
                    self.videoIndex += 1
                    os.rename(video_file_name, video_name_and_index)
                else:
                    video_url = json.loads(video_data_list[0])['url']
                    print(json.loads(video_data_list[0]))
                    video_file_name = self.download_video(video_url)

                    video_name_and_index = "{}-{}".format(
                        str(self.videoIndex), viedo_name)
                    self.videoIndex += 1
                    os.rename(video_file_name, video_name_and_index)

        os.remove(file_name)

    def download_video(self, url):
        video_name = url.split('/')[-1]
        reponse = requests.get(url, stream=True)
        with open(video_name, 'wb') as video:
            total_length = int(reponse.headers.get('content-length'))
            total_received = 0
            for chunk in reponse.iter_content(chunk_size=1024):
                if chunk:
                    progress = ((total_received / total_length) * 100) + 1
                    self.progressBar['value'] = progress
                    self.progressLabel.configure(
                        text='{}%'.format(int(progress)))
                    self.progressBar.update()

                    video.write(chunk)
                    total_received += 1024

        return video_name

    def showProgressBar(self):
        self.progressBar = Progressbar(self.master, length=300)
        self.progressBar['value'] = 0

        self.downloadLable = Label(self.master,
                                   text="Downloading...",
                                   fg='#2c3e50',
                                   font=("Arial Bold", 9))
        self.downloadLable.place(x=self.btnBorderX + 10,
                                 y=self.btnBorderY + 187)

        self.progressLabel = Label(self.master,
                                   text='0%',
                                   fg='#2c3e50',
                                   font=("Arial Bold", 10))
        self.progressLabel.place(x=self.btnBorderX + 10,
                                 y=self.btnBorderY + 210)
        Label(self.master, text="100%", fg='#2c3e50',
              font=("Arial Bold", 10)).place(x=self.btnBorderX + 340,
                                             y=self.btnBorderY + 210)

        self.progressBar.place(x=self.btnBorderX + 40, y=self.btnBorderY + 210)

    def showLogs(self, error):
        self.errorLabel = Label(self.master,
                                text='Logs:',
                                fg='#2c3e50',
                                font=("Arial Bold", 10))
        self.errorLabel.place(x=self.btnBorderX + 10, y=self.btnBorderY + 245)

        self.errorField = Text(self.master,
                               background="#ff7979",
                               borderwidth=2,
                               height=3,
                               width=52,
                               font=("Arial Bold", 8))
        self.errorField.place(x=self.btnBorderX + 10, y=self.btnBorderY + 265)
        self.errorField.insert(END, error)
        self.errorField.config(state=DISABLED)
コード例 #31
0
ファイル: views.py プロジェクト: Sciprios/Anonymizer
class MainForm(Tk, Observer):
    """ Defines a form object based from Tk in tkinter. """

    def __init__(self):
        """ Initializes the control object and controls of the form. """
        Tk.__init__(self)
        Observer.__init__(self)
        self.ctrl_anon = None
        self.resizable(0, 0)
        self._reset_controls()

        # Center window
        width = 800
        height = 500
        scr_width = self.winfo_screenwidth()
        scr_height = self.winfo_screenheight()

        # Calculate dimensions
        x = (scr_width/2) - (width/2)
        y = (scr_height/2) - (height/2)

        # Set window dimensions
        geo = str(width) + "x" + str(height) + "+" + str(x)[:-2] + "+" + str(y)[:-2]
        self.geometry(geo)
    
    def _reset_controls(self):
        """ Resets the controls on the form. """
        image = ImageTk.PhotoImage(file="bg.png")
        
        # Initialize controls
        self.lbl_bg = Label(self, image=image)
        self.lbl_dir = Label(self, bg="white", fg="#668FA7", font=("Courier", 14))
        self.lbl_anon = Label(self, bg="white", fg="#668FA7", font=("Courier", 14))
        self.lbl_id = Label(self, bg="white", fg="#668FA7", font=("Courier", 14))
        self.btn_dir_select = Button(self, text="Select data folder", command=self._btn_dir_press)
        self.btn_id = Button(self, text="Identify data", command=self._btn_id_press)
        self.btn_anon = Button(self, text="Anonymize data", command=self._btn_anon_press)
        self.tb_study = Entry(self, bg="#668FA7", fg="white")
        self.prg_id = Progressbar(self, orient="horizontal", length=200, mode="determinate")
        self.prg_anon = Progressbar(self, orient="horizontal", length=200, mode="determinate")

        # Place controls
        self.lbl_bg.place(x=0, y=0, relwidth=1, relheight=1)
        self.lbl_anon.place(x=400, y=400)
        self.lbl_id.place(x=400, y=325)
        self.btn_dir_select.place(x=250, y=250)
        self.btn_id.place(x=250, y=325)
        self.btn_anon.place(x=250, y=400)
        self.tb_study.place(x=250, y=175)
        self.prg_id.place(x=410, y=290)
        self.prg_anon.place(x=410, y=370)

        # Other formatting
        self.lbl_bg.image = image
        self.btn_id['state'] = "disabled"
        self.btn_anon['state'] = "disabled"
        self.prg_id['maximum'] = 100
        self.prg_anon['maximum'] = 100

    def _btn_dir_press(self):
        """ Allows user to select their data folder. """
        self.ctrl_anon.reset()
        dir = filedialog.askdirectory(initialdir='.')
        if len(dir) > 0:
            self.lbl_dir.config(text=dir)
            self.btn_id['state'] = "active"
            self.btn_anon['state'] = "disabled"
        else:
            self.btn_id['state'] = "disabled"
            self.btn_anon['state'] = "disabled"
    
    def _btn_id_press(self):
        """ Calls the controller to identify data set. """
        self.ctrl_anon.identify(self.lbl_dir['text'])
        self.btn_anon['state'] = "active"
    
    def _btn_anon_press(self):
        """ Calls the controller to anonymize the data set. """
        if len(self.tb_study.get()) == 0:
            self.lbl_anon.config(text="Please enter a study name..")
        elif not self.tb_study.get().isalnum():
            self.lbl_anon.config(text="Please enter a valid study name..")
        else:
            self.ctrl_anon.anonymize(self.tb_study.get(), self.lbl_dir['text'])
    
    def notify(self):
        """ Updates the progress of the anonymization and identification processes. """
        self.prg_id['value'] = self.ctrl_anon.id_progress
        if self.prg_id['value'] == 100:
            self.lbl_id.config(text="Identification compelete")
        elif self.prg_id['value'] > 0:
            self.lbl_id.config(text="Identification in progress..")
        
        self.prg_anon['value'] = self.ctrl_anon.anon_progress
        if self.prg_anon['value'] == 100:
            self.lbl_anon.config(text="Anonymization compelete")
        elif self.prg_anon['value'] > 0:
            self.lbl_anon.config(text="Anonymization in progress..")
        
    def add_controller(self, control_anon):
        """ Adds a control anonymizer object to this gui. """
        self.ctrl_anon = control_anon
        self.ctrl_anon.subscribe(self)