Advertisement
TrashRat

Grabbit! YT downloader GUI

Mar 22nd, 2019
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 29.00 KB | None | 0 0
  1. #! /usr/bin/env python
  2. #  -*- coding: utf-8 -*-
  3. #
  4. # GUI module generated by PAGE version 4.20
  5. #  in conjunction with Tcl version 8.6
  6. #    Feb 26, 2019 03:41:37 AM PST  platform: Windows NT
  7.  
  8. import sys
  9. import subprocess
  10. import io
  11. import os
  12. import threading
  13. import webbrowser
  14. import requests
  15. import random
  16.  
  17. from tkinter import filedialog
  18. from tkinter import messagebox
  19.  
  20. try:
  21.     import Tkinter as tk
  22. except ImportError:
  23.     import tkinter as tk
  24.  
  25. try:
  26.     import ttk
  27.  
  28.     py3 = False
  29. except ImportError:
  30.     import tkinter.ttk as ttk
  31.  
  32.     py3 = True
  33.  
  34.  
  35. def vp_start_gui():
  36.     '''Starting point when module is the main routine.'''
  37.     global val, w, root
  38.     root = tk.Tk()
  39.     root.iconbitmap("grabbitbunny.ico")
  40.  
  41.     top = MainWindow(root)
  42.  
  43.     root.mainloop()
  44.  
  45.  
  46. w = None
  47.  
  48.  
  49. def create_MainWindow(root, *args, **kwargs):
  50.     '''Starting point when module is imported by another program.'''
  51.     global w, w_win, rt
  52.     rt = root
  53.     w = tk.Toplevel(root)
  54.  
  55.     top = MainWindow(w)
  56.  
  57.     return (w, top)
  58.  
  59.  
  60. def destroy_MainWindow():
  61.     global w
  62.     w.destroy()
  63.     w = None
  64.  
  65.  
  66. class MainWindow:
  67.     def __init__(self, top=None):
  68.         currentDirectory = os.getcwd()
  69.         defFolder = os.path.normpath(os.path.expanduser("~/Documents/Grabbit Downloads"))
  70.         settings = []
  71.         folders = []
  72.         folders.append(defFolder)
  73.         try:
  74.             with open("settings.txt","r") as file:
  75.                 for line in file:
  76.                     settings.append(line)
  77.             dirs = settings[0]
  78.             if not os.path.exists(dirs):
  79.                 os.makedirs(dirs)
  80.             folders = [dirs]
  81.  
  82.         except FileNotFoundError as e:
  83.             dirs = os.path.normpath(os.path.expanduser("~/Documents/Grabbit Downloads"))
  84.             if not os.path.exists(dirs):
  85.                 os.makedirs(dirs)
  86.         except IndexError as e:
  87.             dirs = os.path.normpath(os.path.expanduser("~/Documents/Grabbit Downloads"))
  88.             if not os.path.exists(dirs):
  89.                 os.makedirs(dirs)
  90.             folders = [dirs]
  91.  
  92.         def DownVid(button, *argv):
  93.  
  94.             def ProcCom(commands):
  95.  
  96.                 process = subprocess.Popen(commands, startupinfo=startupinfo, stdout=subprocess.PIPE, stderr=subprocess.PIPE,stdin=subprocess.DEVNULL,  cwd=folders[0]) # pipes commands from if statements into youtube-dl.exe Popen
  97.                 for line in io.TextIOWrapper(process.stdout, encoding="utf-8"):
  98.  
  99.                     if len(line) >= 70:
  100.                         thl = [line[i:i + 67] for i in range(0, len(line), 67)]
  101.                         for bit in thl:
  102.                             self.DownloadHistory.insert(tk.END,bit)
  103.                             self.DownloadHistory.see(tk.END)
  104.                     else:
  105.                         self.DownloadHistory.insert(tk.END, line) #line
  106.                         self.DownloadHistory.see(tk.END)
  107.  
  108.             link = self.UrlBox.get()
  109.  
  110.             startupinfo = None
  111.             if os.name == 'nt':
  112.                 startupinfo = subprocess.STARTUPINFO()
  113.                 startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  114.  
  115.             #TODO move all commands into one central list, each button appends or removes certain entries
  116.             if button == "UP":
  117.                 command = ["youtube-dl","--update"]
  118.                 ProcCom(command)
  119.  
  120.             if button == "PV":  # PLAYLIST VIDEOS
  121.                 reso = str(self.ResoList.get()).replace("p", "")
  122.  
  123.                 if reso == "Best":
  124.                     command = ["youtube-dl","--restrict-filenames","--retries","30","--fragment-retries","30","--format", "bestvideo+bestaudio[ext=m4a]",
  125.                                "--merge-output-format", "mp4","-o","%(playlist_index)s-%(title)s.%(ext)s",
  126.                                link]
  127.                 else:
  128.                     command = ["youtube-dl","--restrict-filenames","--retries","30","--fragment-retries","30","--format", "bestvideo[height<=%s]+bestaudio[ext=m4a]"%reso,
  129.                                "--merge-output-format", "mp4","-o","%(playlist_index)s-%(title)s.%(ext)s",
  130.                                link]
  131.  
  132.                 try:
  133.                     ProcCom(command)
  134.                     self.DownloadHistory.insert(tk.END,
  135.                                             "---------------------------------------------------------------------")
  136.                 except Exception as e:
  137.                     self.DownloadHistory.insert(tk.END,e)
  138.                     self.DownloadHistory.see(tk.END)
  139.  
  140.  
  141.             if button == "PM":  # PLAYLIST MUSIC
  142.                 command = ["youtube-dl","--restrict-filenames", "--retries", "30", "--fragment-retries", "30", "--add-metadata",
  143.                            "--extract-audio", "--audio-format", "mp3", "-o", "%(playlist_index)s-%(title)s.%(ext)s",
  144.                            link]
  145.                 try:
  146.                     ProcCom(command)
  147.                     self.DownloadHistory.insert(tk.END,
  148.                                             "---------------------------------------------------------------------")
  149.                 except Exception as e:
  150.                     self.DownloadHistory.insert(tk.END,e)
  151.                     self.DownloadHistory.see(tk.END)
  152.  
  153.  
  154.             if button == "JV":  # VIDEO
  155.  
  156.                 reso = str(self.ResoList.get()).replace("p","")
  157.                 if reso == "Best":
  158.                     command = ["youtube-dl","--restrict-filenames", "--retries", "30", "--fragment-retries", "30", "--format",
  159.                                "bestvideo+bestaudio[ext=m4a]/bestvideo+bestaudio",
  160.                                "--merge-output-format", "mp4",
  161.                                r"-o %(title)s.%(ext)s", link]
  162.                 else:
  163.                     command = ["youtube-dl","--restrict-filenames", "--retries", "30", "--fragment-retries", "30", "--format",
  164.                                "bestvideo[height<=%s]+bestaudio[ext=m4a]"%reso, "--merge-output-format", "mp4",
  165.                                r"-o %(title)s.%(ext)s", link]
  166.  
  167.                 try:
  168.                     ProcCom(command)
  169.                     self.DownloadHistory.insert(tk.END,
  170.                                             "---------------------------------------------------------------------")
  171.                 except Exception as e:
  172.                     self.DownloadHistory.insert(tk.END,e)
  173.                     self.DownloadHistory.see(tk.END)
  174.  
  175.  
  176.             if button == "JM":  # MUSIC
  177.                 command = ["youtube-dl","--restrict-filenames", "--retries", "30", "--fragment-retries", "30", "--add-metadata",
  178.                            "--extract-audio", "--audio-format", "mp3", "-o", "%(title)s.%(ext)s", link]
  179.                 try:
  180.                     ProcCom(command)
  181.                     self.DownloadHistory.insert(tk.END,
  182.                                             "---------------------------------------------------------------------")
  183.                 except Exception as e:
  184.                     self.DownloadHistory.insert(tk.END,e)
  185.                     self.DownloadHistory.see(tk.END)
  186.  
  187.  
  188.  
  189.  
  190.         def TDownVid(button):
  191.             threading.Thread(target=DownVid(button)).start()
  192.  
  193.         def GetVideo():
  194.             TDownVid("JV")
  195.  
  196.         def TGetVideo():
  197.             threading.Thread(target=GetVideo).start()
  198.  
  199.         def GetSong():
  200.             TDownVid("JM")
  201.  
  202.         def TGetSong():
  203.             threading.Thread(target=GetSong).start()
  204. #TODO fix update youtube-dl in executable
  205.         def UpdateYT():
  206.  
  207.             startupinfo=None
  208.             doit=["Youtube-dl","--update"]
  209.             response = messagebox.askyesno("Please confirm","Are you sure you would like to update youtube-dl?")
  210.  
  211.             if response == True:
  212.  
  213.                 process = subprocess.Popen(doit, startupinfo=startupinfo, stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=subprocess.DEVNULL,
  214.                                            cwd=os.getcwd())  # pipes commands from if statements into youtube-dl.exe
  215.                 for line in io.TextIOWrapper(process.stdout, encoding="utf-8"):
  216.                     self.DownloadHistory.insert(tk.END, line)
  217.                     self.DownloadHistory.see(tk.END)
  218.             else:
  219.                 pass
  220.  
  221.         def FileDirec(*argv):
  222.             my_filetypes = [('all files', '.*'), ('text files', '.txt')]
  223.             answer = filedialog.askdirectory(parent=root,
  224.                                              initialdir=os.path.join(folders[0]),
  225.                                              title="Please select a folder:")
  226.             del folders[:]
  227.             folders.append(answer)
  228.             self.DownloadHistory.insert(tk.END,"Saving to %s"%answer)
  229.             self.DownloadHistory.insert(tk.END,
  230.                                         "---------------------------------------------------------------------")
  231.             self.DownloadHistory.see(tk.END)
  232.  
  233.         def FileDirecDef(*argv):
  234.             folder = filedialog.askdirectory(parent=root,
  235.                                              initialdir=os.path.join(defFolder),
  236.                                              title="Please select default save location")
  237.             with open("settings.txt","w") as file:
  238.                 file.seek(0)
  239.                 file.write(folder)
  240.                 file.close
  241.  
  242.             del folders[:]
  243.             folders.append(folder)
  244.             self.DownloadHistory.insert(tk.END, folder)
  245.             self.DownloadHistory.insert(tk.END,
  246.                                         "---------------------------------------------------------------------")
  247.         def OpenFolder(*argv):
  248.             answers = r"%s" % folders[0]
  249.             os.startfile(answers)
  250.  
  251.         def GrabGitHub(*argv):
  252.             webbrowser.open_new_tab("https://github.com/TrashRat/Grabbit")
  253.  
  254.         def YTDLGitHub(*argv):
  255.             webbrowser.open_new_tab("https://github.com/ytdl-org/youtube-dl")
  256.  
  257.         def SupportedWebsites(*argv):
  258.             webbrowser.open_new_tab("http://ytdl-org.github.io/youtube-dl/supportedsites.html")
  259.  
  260.         def UpdateGrabbit(*argv):
  261.  
  262.             def download_file_from_google_drive(id, destination):
  263.                 URL = "https://docs.google.com/uc?export=download"
  264.  
  265.                 session = requests.Session()
  266.  
  267.                 response = session.get(URL, params={'id': id}, stream=True)
  268.                 token = get_confirm_token(response)
  269.  
  270.                 if token:
  271.                     params = {'id': id, 'confirm': token}
  272.                     response = session.get(URL, params=params, stream=True)
  273.  
  274.                 save_response_content(response, destination)
  275.  
  276.             def get_confirm_token(response):
  277.                 for key, value in response.cookies.items():
  278.                     if key.startswith('download_warning'):
  279.                         return value
  280.  
  281.                 return None
  282.  
  283.             def save_response_content(response, destination):
  284.                 CHUNK_SIZE = 32768
  285.  
  286.                 with open(destination, "wb") as f:
  287.                     for chunk in response.iter_content(CHUNK_SIZE):
  288.                         if chunk:  # filter out keep-alive new chunks
  289.                             f.write(chunk)
  290.  
  291.             file_id = '1trxQXYtcNGfZQZbno96TK5ZUYJgaTsra'
  292.             destination = os.getcwd() + "\\Grabbit-{}.exe".format(random.randint(0,999))
  293.             response = messagebox.askyesno("Please confirm","Are you sure you would like to update Grabbit?")
  294.  
  295.             if response == True:
  296.                 self.DownloadHistory.insert(tk.END,"Updating Grabbit...this window will freeze as the update is downloaded")
  297.                 download_file_from_google_drive(file_id, destination)
  298.                 self.DownloadHistory.insert(tk.END,"Grabbit Updated! Please close this window and delete old executable")
  299.  
  300.             else:
  301.                 pass
  302.  
  303.         def popupmsg(*argv):
  304.             def vp_start_gui():
  305.                 '''Starting point when module is the main routine.'''
  306.                 global val, w, roott
  307.                 roott = tk.Tk()
  308.                 top = PlaylistMenu(roott)
  309.  
  310.                 roott.mainloop()
  311.  
  312.             w = None
  313.  
  314.             class PlaylistMenu:
  315.                 def __init__(self, top=None):
  316.                     def DestroyWinV():
  317.                         roott.destroy()
  318.                         TDownVid("PV")  # FLAGS TO CALL WHICH BUTTON IS BEING PRESSED
  319.  
  320.                     def TDestroyWinV():
  321.                         threading.Thread(target=DestroyWinV).start()
  322.  
  323.                     def DestroyWinM():
  324.                         roott.destroy()
  325.                         TDownVid("PM")
  326.  
  327.                     def TDestroyWinM():
  328.                         threading.Thread(target=DestroyWinM).start()
  329.  
  330.                     '''This class configures and populates the toplevel window.
  331.                       top is the toplevel containing window.'''
  332.                     _bgcolor = '#d9d9d9'  # X11 color: 'gray85'
  333.                     _fgcolor = '#000000'  # X11 color: 'black'
  334.                     _compcolor = '#d9d9d9'  # X11 color: 'gray85'
  335.                     _ana1color = '#d9d9d9'  # X11 color: 'gray85'
  336.                     _ana2color = '#ececec'  # Closest X11 color: 'gray92'
  337.  
  338.                     top.geometry("136x89+713+366")
  339.                     top.title("")
  340.                     top.configure(background="#d9d9d9")
  341.  
  342.                     self.VidPlaylist = tk.Radiobutton(top)
  343.                     self.VidPlaylist.place(relx=0.147, rely=0.112, relheight=0.393
  344.                                            , relwidth=0.721)
  345.                     self.VidPlaylist.configure(activebackground="#ececec")
  346.                     self.VidPlaylist.configure(activeforeground="#000000")
  347.                     self.VidPlaylist.configure(background="#d9d9d9")
  348.                     self.VidPlaylist.configure(disabledforeground="#a3a3a3")
  349.                     self.VidPlaylist.configure(foreground="#000000")
  350.                     self.VidPlaylist.configure(highlightbackground="#d9d9d9")
  351.                     self.VidPlaylist.configure(highlightcolor="black")
  352.                     self.VidPlaylist.configure(justify='left')
  353.                     self.VidPlaylist.configure(text='''Video Playlist''')
  354.                     self.VidPlaylist.configure(width=98)
  355.                     self.VidPlaylist.configure(command=TDestroyWinV)
  356.  
  357.                     self.MusicPlaylist = tk.Radiobutton(top)
  358.                     self.MusicPlaylist.place(relx=0.147, rely=0.449, relheight=0.393
  359.                                              , relwidth=0.735)
  360.                     self.MusicPlaylist.configure(activebackground="#ececec")
  361.                     self.MusicPlaylist.configure(activeforeground="#000000")
  362.                     self.MusicPlaylist.configure(background="#d9d9d9")
  363.                     self.MusicPlaylist.configure(disabledforeground="#a3a3a3")
  364.                     self.MusicPlaylist.configure(foreground="#000000")
  365.                     self.MusicPlaylist.configure(highlightbackground="#d9d9d9")
  366.                     self.MusicPlaylist.configure(highlightcolor="black")
  367.                     self.MusicPlaylist.configure(justify='left')
  368.                     self.MusicPlaylist.configure(text='''Music Playlist''')
  369.                     self.MusicPlaylist.configure(width=100)
  370.                     self.MusicPlaylist.configure(command=TDestroyWinM)
  371.  
  372.             if __name__ == '__main__':
  373.                 vp_start_gui()
  374.  
  375.  
  376.  
  377.         '''This class configures and populates the toplevel window.
  378.           top is the toplevel containing window.'''
  379.         _bgcolor = '#d9d9d9'  # X11 color: 'gray85'
  380.         _fgcolor = '#000000'  # X11 color: 'black'
  381.         _compcolor = '#d9d9d9'  # X11 color: 'gray85'
  382.         _ana1color = '#d9d9d9'  # X11 color: 'gray85'
  383.         _ana2color = '#ececec'  # Closest X11 color: 'gray92'
  384.         self.style = ttk.Style()
  385.         if sys.platform == "win32":
  386.             self.style.theme_use('winnative')
  387.         self.style.configure('.', background=_bgcolor)
  388.         self.style.configure('.', foreground=_fgcolor)
  389.         self.style.configure('.', font="TkDefaultFont")
  390.         self.style.map('.', background=
  391.         [('selected', _compcolor), ('active', _ana2color)])
  392.  
  393.         top.geometry("584x280+769+298")
  394.         top.title("Grabbit - Downloading made easy")
  395.         top.configure(background="#d9d9d9")  # BG COLOR
  396.         top.configure(highlightbackground="#d9d9d9")
  397.         top.configure(highlightcolor="black")
  398.  
  399.         self.DownloadHistory = ScrolledListBox(top)
  400.         self.DownloadHistory.place(relx=0.017, rely=0.268, relheight=0.696
  401.                                    , relwidth=0.962)
  402.         self.DownloadHistory.configure(background="white")
  403.         self.DownloadHistory.configure(disabledforeground="#a3a3a3")
  404.         self.DownloadHistory.configure(font="TkFixedFont")
  405.         self.DownloadHistory.configure(foreground="black")
  406.         self.DownloadHistory.configure(highlightbackground="#d9d9d9")
  407.         self.DownloadHistory.configure(highlightcolor="#d9d9d9")
  408.         self.DownloadHistory.configure(selectbackground="#c4c4c4")
  409.         self.DownloadHistory.configure(selectforeground="black")
  410.         self.DownloadHistory.configure(width=10)
  411.  
  412.         self.menubar = tk.Menu(top, font="TkMenuFont", bg=_bgcolor, fg=_fgcolor)
  413.         top.configure(menu=self.menubar)
  414.         self.sub_menu = tk.Menu(top, tearoff=0)
  415.         self.menubar.add_cascade(menu=self.sub_menu,
  416.                                  activebackground="#ececec",
  417.                                  activeforeground="#000000",
  418.                                  background="#d9d9d9",
  419.                                  compound="left",
  420.                                  font="TkMenuFont",
  421.                                  foreground="#000000",
  422.                                  label="Settings")
  423.         self.sub_menu.add_command(
  424.             activebackground="#d9d9d9",
  425.             activeforeground="#000000",
  426.             background="#ececec",
  427.             compound="left",
  428.             font="TkMenuFont",
  429.             foreground="#000000",
  430.             label="Set default save location",
  431.             command=FileDirecDef)
  432.         self.sub_menu.add_command(
  433.             activebackground="#d9d9d9",
  434.             activeforeground="#000000",
  435.             background="#ececec",
  436.             compound="left",
  437.             font="TkMenuFont",
  438.             foreground="#000000",
  439.             label="Update Grabbit",
  440.             command=UpdateGrabbit)
  441.         self.sub_menu.add_command(
  442.             activebackground="#d9d9d9",
  443.             activeforeground="#000000",
  444.             background="#ececec",
  445.             compound="left",
  446.             font="TkMenuFont",
  447.             foreground="#000000",
  448.             label="Update youtube-dl",
  449.             command=UpdateYT)
  450.  
  451.         self.about_menu = tk.Menu(top, tearoff=0)
  452.         self.menubar.add_cascade(menu=self.about_menu,
  453.                                  activebackground="#ececec",
  454.                                  activeforeground="#000000",
  455.                                  background="#d9d9d9",
  456.                                  compound="left",
  457.                                  font="TkMenuFont",
  458.                                  foreground="#000000",
  459.                                  label="About")
  460.         self.about_menu.add_command(
  461.             activebackground="#d9d9d9",
  462.             activeforeground="#000000",
  463.             background="#ececec",
  464.             compound="left",
  465.             font="TkMenuFont",
  466.             foreground="#000000",
  467.             label="Supported websites",
  468.             command=SupportedWebsites)
  469.         self.about_menu.add_command(
  470.             activebackground="#d9d9d9",
  471.             activeforeground="#000000",
  472.             background="#ececec",
  473.             compound="left",
  474.             font="TkMenuFont",
  475.             foreground="#000000",
  476.             label="Grabbit GitHub",
  477.             command=GrabGitHub)
  478.         self.about_menu.add_command(
  479.             activebackground="#d9d9d9",
  480.             activeforeground="#000000",
  481.             background="#ececec",
  482.             compound="left",
  483.             font="TkMenuFont",
  484.             foreground="#000000",
  485.             label="Youtube-dl GitHub",
  486.             command=YTDLGitHub)
  487.  
  488.         self.UrlBox = ttk.Entry(top)
  489.         self.UrlBox.place(relx=0.017, rely=0.018, relheight=0.075
  490.                           , relwidth=0.725)
  491.         self.UrlBox.configure(takefocus="")
  492.         self.UrlBox.configure(cursor="ibeam")
  493.  
  494.         self.ResoList = ttk.Combobox(root,values=("144p", "240p", "480p", "720p", "1080p", "Best"))
  495.         self.ResoList.place(relx=0.736, rely=0.018, relheight=0.075
  496.                             , relwidth=0.108)
  497.         self.ResoList.configure(takefocus="",state="readonly")
  498.         self.ResoList.current(5)
  499.  
  500.         self.DVideo = tk.Button(top)
  501.         self.DVideo.place(relx=0.017, rely=0.125, height=34, width=147)
  502.         self.DVideo.configure(activebackground="#ececec")
  503.         self.DVideo.configure(activeforeground="#000000")
  504.         self.DVideo.configure(background="#d9d9d9")
  505.         self.DVideo.configure(disabledforeground="#a3a3a3")
  506.         self.DVideo.configure(foreground="#000000")
  507.         self.DVideo.configure(highlightbackground="#d9d9d9")
  508.         self.DVideo.configure(highlightcolor="black")
  509.         self.DVideo.configure(pady="0")
  510.         self.DVideo.configure(relief='groove')
  511.         self.DVideo.configure(text='''Download Video''')
  512.         self.DVideo.configure(width=147)
  513.         self.DVideo.configure(command=TGetVideo)
  514.  
  515.         self.DSong = tk.Button(top)
  516.         self.DSong.place(relx=0.291, rely=0.125, height=34, width=147)
  517.         self.DSong.configure(activebackground="#ececec")
  518.         self.DSong.configure(activeforeground="#000000")
  519.         self.DSong.configure(background="#d9d9d9")
  520.         self.DSong.configure(disabledforeground="#a3a3a3")
  521.         self.DSong.configure(foreground="#000000")
  522.         self.DSong.configure(highlightbackground="#d9d9d9")
  523.         self.DSong.configure(highlightcolor="black")
  524.         self.DSong.configure(pady="0")
  525.         self.DSong.configure(relief='groove')
  526.         self.DSong.configure(text='''Download Song''')
  527.         self.DSong.configure(command=TGetSong)
  528.  
  529.         self.DPlaylist = tk.Button(top)
  530.         self.DPlaylist.place(relx=0.565, rely=0.125, height=34, width=147)
  531.         self.DPlaylist.configure(activebackground="#ececec")
  532.         self.DPlaylist.configure(activeforeground="#000000")
  533.         self.DPlaylist.configure(background="#d9d9d9")
  534.         self.DPlaylist.configure(disabledforeground="#a3a3a3")
  535.         self.DPlaylist.configure(foreground="#000000")
  536.         self.DPlaylist.configure(highlightbackground="#d9d9d9")
  537.         self.DPlaylist.configure(highlightcolor="black")
  538.         self.DPlaylist.configure(pady="0")
  539.         self.DPlaylist.configure(relief='groove')
  540.         self.DPlaylist.configure(text='''Download Playlist''')
  541.         self.DPlaylist.configure(command=popupmsg)
  542.  
  543.         self.OpnFoldr = tk.Button(top)
  544.         self.OpnFoldr.place(relx=0.856, rely=0.125, height=34, width=77)
  545.         self.OpnFoldr.configure(activebackground="#ececec")
  546.         self.OpnFoldr.configure(activeforeground="#000000")
  547.         self.OpnFoldr.configure(background="#d9d9d9")
  548.         self.OpnFoldr.configure(disabledforeground="#a3a3a3")
  549.         self.OpnFoldr.configure(foreground="#000000")
  550.         self.OpnFoldr.configure(highlightbackground="#d9d9d9")
  551.         self.OpnFoldr.configure(highlightcolor="black")
  552.         self.OpnFoldr.configure(pady="0")
  553.         self.OpnFoldr.configure(relief='groove')
  554.         self.OpnFoldr.configure(text='''Open Folder''')
  555.         self.OpnFoldr.configure(width=77)
  556.         self.OpnFoldr.configure(command=OpenFolder)
  557.  
  558.         self.SaveTo = tk.Button(top)
  559.         self.SaveTo.place(relx=0.856, rely=0.018, height=24, width=77)
  560.         self.SaveTo.configure(activebackground="#ececec")
  561.         self.SaveTo.configure(activeforeground="#000000")
  562.         self.SaveTo.configure(background="#d9d9d9")
  563.         self.SaveTo.configure(disabledforeground="#a3a3a3")
  564.         self.SaveTo.configure(foreground="#000000")
  565.         self.SaveTo.configure(highlightbackground="#d9d9d9")
  566.         self.SaveTo.configure(highlightcolor="black")
  567.         self.SaveTo.configure(pady="0")
  568.         self.SaveTo.configure(relief='groove')
  569.         self.SaveTo.configure(text='''Save to...''')
  570.         self.SaveTo.configure(width=77)
  571.         self.SaveTo.configure(command=FileDirec)
  572.  
  573.  
  574. # The following code is added to facilitate the Scrolled widgets specified.
  575. class AutoScroll(object):
  576.     '''Configure the scrollbars for a widget.'''
  577.  
  578.     def __init__(self, master):
  579.         #  Rozen. Added the try-except clauses so that this class
  580.         #  could be used for scrolled entry widget for which vertical
  581.         #  scrolling is not supported. 5/7/14.
  582.         try:
  583.             vsb = ttk.Scrollbar(master, orient='vertical', command=self.yview)
  584.         except:
  585.             pass
  586.         hsb = ttk.Scrollbar(master, orient='horizontal', command=self.xview)
  587.  
  588.         # self.configure(yscrollcommand=_autoscroll(vsb),
  589.         #    xscrollcommand=_autoscroll(hsb))
  590.         try:
  591.             self.configure(yscrollcommand=self._autoscroll(vsb))
  592.         except:
  593.             pass
  594.         self.configure(xscrollcommand=self._autoscroll(hsb))
  595.  
  596.         self.grid(column=0, row=0, sticky='nsew')
  597.         try:
  598.             vsb.grid(column=1, row=0, sticky='ns')
  599.         except:
  600.             pass
  601.         hsb.grid(column=0, row=1, sticky='ew')
  602.  
  603.         master.grid_columnconfigure(0, weight=1)
  604.         master.grid_rowconfigure(0, weight=1)
  605.  
  606.         # Copy geometry methods of master  (taken from ScrolledText.py)
  607.         if py3:
  608.             methods = tk.Pack.__dict__.keys() | tk.Grid.__dict__.keys() \
  609.                       | tk.Place.__dict__.keys()
  610.         else:
  611.             methods = tk.Pack.__dict__.keys() + tk.Grid.__dict__.keys() \
  612.                       + tk.Place.__dict__.keys()
  613.  
  614.         for meth in methods:
  615.             if meth[0] != '_' and meth not in ('config', 'configure'):
  616.                 setattr(self, meth, getattr(master, meth))
  617.  
  618.     @staticmethod
  619.     def _autoscroll(sbar):
  620.         '''Hide and show scrollbar as needed.'''
  621.  
  622.         def wrapped(first, last):
  623.             first, last = float(first), float(last)
  624.             if first <= 0 and last >= 1:
  625.                 sbar.grid_remove()
  626.             else:
  627.                 sbar.grid()
  628.             sbar.set(first, last)
  629.  
  630.         return wrapped
  631.  
  632.     def __str__(self):
  633.         return str(self.master)
  634.  
  635.  
  636. def _create_container(func):
  637.     '''Creates a ttk Frame with a given master, and use this new frame to
  638.    place the scrollbars and the widget.'''
  639.  
  640.     def wrapped(cls, master, **kw):
  641.         container = ttk.Frame(master)
  642.         container.bind('<Enter>', lambda e: _bound_to_mousewheel(e, container))
  643.         container.bind('<Leave>', lambda e: _unbound_to_mousewheel(e, container))
  644.         return func(cls, container, **kw)
  645.  
  646.     return wrapped
  647.  
  648.  
  649. class ScrolledListBox(AutoScroll, tk.Listbox):
  650.     '''A standard Tkinter Text widget with scrollbars that will
  651.    automatically show/hide as needed.'''
  652.  
  653.     @_create_container
  654.     def __init__(self, master, **kw):
  655.         tk.Listbox.__init__(self, master, **kw)
  656.         AutoScroll.__init__(self, master)
  657.  
  658.  
  659. import platform
  660.  
  661.  
  662. def _bound_to_mousewheel(event, widget):
  663.     child = widget.winfo_children()[0]
  664.     if platform.system() == 'Windows' or platform.system() == 'Darwin':
  665.         child.bind_all('<MouseWheel>', lambda e: _on_mousewheel(e, child))
  666.         child.bind_all('<Shift-MouseWheel>', lambda e: _on_shiftmouse(e, child))
  667.     else:
  668.         child.bind_all('<Button-4>', lambda e: _on_mousewheel(e, child))
  669.         child.bind_all('<Button-5>', lambda e: _on_mousewheel(e, child))
  670.         child.bind_all('<Shift-Button-4>', lambda e: _on_shiftmouse(e, child))
  671.         child.bind_all('<Shift-Button-5>', lambda e: _on_shiftmouse(e, child))
  672.  
  673.  
  674. def _unbound_to_mousewheel(event, widget):
  675.     if platform.system() == 'Windows' or platform.system() == 'Darwin':
  676.         widget.unbind_all('<MouseWheel>')
  677.         widget.unbind_all('<Shift-MouseWheel>')
  678.     else:
  679.         widget.unbind_all('<Button-4>')
  680.         widget.unbind_all('<Button-5>')
  681.         widget.unbind_all('<Shift-Button-4>')
  682.         widget.unbind_all('<Shift-Button-5>')
  683.  
  684.  
  685. def _on_mousewheel(event, widget):
  686.     if platform.system() == 'Windows':
  687.         widget.yview_scroll(-1 * int(event.delta / 120), 'units')
  688.     elif platform.system() == 'Darwin':
  689.         widget.yview_scroll(-1 * int(event.delta), 'units')
  690.     else:
  691.         if event.num == 4:
  692.             widget.yview_scroll(-1, 'units')
  693.         elif event.num == 5:
  694.             widget.yview_scroll(1, 'units')
  695.  
  696.  
  697. def _on_shiftmouse(event, widget):
  698.     if platform.system() == 'Windows':
  699.         widget.xview_scroll(-1 * int(event.delta / 120), 'units')
  700.     elif platform.system() == 'Darwin':
  701.         widget.xview_scroll(-1 * int(event.delta), 'units')
  702.     else:
  703.         if event.num == 4:
  704.             widget.xview_scroll(-1, 'units')
  705.         elif event.num == 5:
  706.             widget.xview_scroll(1, 'units')
  707.  
  708.  
  709. if __name__ == '__main__':
  710.     vp_start_gui()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement