Advertisement
cmiN

sub-gui

Apr 11th, 2012
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.30 KB | None | 0 0
  1. #! /usr/bin/env python
  2. # Subtitle Config Editor
  3. # 11.04.2012 cmiN
  4. # Tkinter GUI used to insert data into files
  5.  
  6.  
  7. from Tkinter import *
  8. from tkMessageBox import showinfo
  9. from tkFileDialog import askopenfilename
  10. from os.path import isdir, isfile
  11. from subprocess import call # better than os.system
  12.  
  13.  
  14. # constants
  15. TITLE = "Config Editor" # window title # modify as you wish
  16. RES = (300, 150) # resolution # width, height
  17.  
  18.  
  19. class GUI(Frame):
  20.     """Self-sustained frame.
  21.    Constructor does all the job.
  22.    """
  23.  
  24.     def __init__(self, master=None, margin=10):
  25.         """Same as Frame's plus some links."""
  26.         Frame.__init__(self, master, padx=margin, pady=margin)
  27.         self.master.title(TITLE)
  28.         self.master.minsize(*RES)
  29.         self.master.maxsize(*RES)
  30.         self.grid()
  31.         self.widgets()
  32.         self.mainloop()
  33.  
  34.     def __update(self, string):
  35.         self.statusVar.set(string)
  36.  
  37.     def help_command(self):
  38.         """Show this."""
  39.         strings = ["1) Load a configuration file.",
  40.                    "2) Fill the entries.",
  41.                    "3) Click `Add` to append them.",
  42.                    "4) Click `Start` to process them."]
  43.         showinfo(parent=self.helpButton, title="Help", message="\n".join(strings))
  44.         self.__update("Ready.")
  45.  
  46.     def load_command(self):
  47.         """User dialog for selecting a file."""
  48.         # build available types
  49.         ftypes = [("Text", "*.txt"), ("Config", "*.cfg"), ("All", "*")]
  50.         # get path to that file
  51.         fpath = askopenfilename(parent=self.loadButton, title="Open config", filetypes=ftypes)
  52.         if fpath == "" or type(fpath) is tuple: # mothafucka clicked cancel
  53.             self.__update("Nothing loaded.")
  54.             return
  55.         # try to open it
  56.         try:
  57.             self.fobj = open(fpath, "a") # create file object
  58.             self.fpath = fpath
  59.             # substract the name
  60.             index = max(fpath.rfind("/"), fpath.rfind("\\")) # win/posix
  61.             fname = fpath[index + 1:]
  62.             # update accordingly
  63.             self.master.title(TITLE + " - " + fname)
  64.             self.__update("Loaded %s." % fname)
  65.         except IOError:
  66.             self.fobj = None
  67.             self.master.title(TITLE)
  68.             self.__update("Cannot open the file.")
  69.  
  70.     def add_command(self):
  71.         # check for exceptions
  72.         if self.fobj is None: # file not ok
  73.             self.__update("Select a configuration file first. See Help.")
  74.             return
  75.         if self.fobj.closed:
  76.             try:
  77.                 self.fobj = open(self.fpath, "a") # reopen
  78.             except IOError:
  79.                 self.fobj = None
  80.                 self.master.title(TITLE)
  81.                 self.__update("Cannot reopen the file.")
  82.                 return
  83.         strings = [self.mainVar.get(), self.subVar.get(), self.movieVar.get()]
  84.         valid = True # all strings must be directories
  85.         if not isdir(strings[0]):
  86.             valid = False
  87.             self.mainEntry.config(bg="pink")
  88.         if not isdir(strings[1]):
  89.             valid = False
  90.             self.subEntry.config(bg="pink")
  91.         if not isdir(strings[2]):
  92.             valid = False
  93.             self.movieEntry.config(bg="pink")
  94.         if not valid:
  95.             self.__update("Invalid directories.")
  96.             return
  97.         # concatenate the lines
  98.         data = "\n".join(strings)
  99.         # write them
  100.         self.fobj.write(data + "\n")
  101.         self.fobj.flush()
  102.         self.__update("Successfully added.")
  103.  
  104.     def start_command(self):
  105.         """Start a process to take care of the configuration file."""
  106.         if self.toExec is None: # not defined
  107.             self.toExec = askopenfilename(parent=self.startButton, title="Open engine", filetypes=[("All", "*")])
  108.             if self.toExec == ""  or type(self.toExec) is tuple:
  109.                 self.toExec = None
  110.                 self.__update("Canceled.")
  111.                 return
  112.             if not isfile(self.toExec):
  113.                 self.toExec = None
  114.                 self.__update("Invalid engine.")
  115.                 return
  116.         if self.fobj:
  117.             self.fobj.close() # you're not in custody anymore :)
  118.         self.__update("Started.")
  119.         self.update() # because `call` is called before `statusLabel` is updated
  120.         try:
  121.             ret = call([self.toExec])
  122.             self.__update("Completed with return code %d." % ret)
  123.         except OSError:
  124.             self.toExec = None
  125.             self.__update("File busy or not runnable.")
  126.  
  127.     def handle_event(self, event):
  128.         """Can't touch this xD."""
  129.         if event.widget == self.mainEntry:
  130.             self.mainEntry.config(bg="white")
  131.         elif event.widget == self.subEntry:
  132.             self.subEntry.config(bg="white")
  133.         elif event.widget == self.movieEntry:
  134.             self.movieEntry.config(bg="white")
  135.  
  136.     def widgets(self):
  137.         """Create entries and buttons."""
  138.         # simple "global" variables
  139.         self.fobj = None
  140.         self.toExec = None
  141.         # object-like variables
  142.         self.mainVar = StringVar()
  143.         self.subVar = StringVar()
  144.         self.movieVar = StringVar()
  145.         self.statusVar = StringVar(value="Ready.")
  146.         # create pairs of "Label: [_____________]"
  147.         self.mainLabel = Label(self, text="Main: ", fg="darkgreen")
  148.         self.mainEntry = Entry(self, textvariable=self.mainVar, width=25)
  149.         self.subLabel = Label(self, text="Subtitles: ", fg="darkgreen")
  150.         self.subEntry = Entry(self, textvariable=self.subVar, width=25)
  151.         self.movieLabel = Label(self, text="Movie: ", fg="darkgreen")
  152.         self.movieEntry = Entry(self, textvariable=self.movieVar, width=25)
  153.         # create buttons
  154.         self.helpButton = Button(self, text="Help", command=self.help_command, width=4)
  155.         self.loadButton = Button(self, text="Load", command=self.load_command, width=4)
  156.         self.addButton = Button(self, text="Add", command=self.add_command, width=4)
  157.         self.startButton = Button(self, text="Start", command=self.start_command, width=4,
  158.                                   fg="red", activeforeground="red")
  159.         # status bar
  160.         self.statusLabel = Label(self, textvariable=self.statusVar, relief="sunken", bd=2, anchor="w", padx=10, width=30)
  161.         # make them visible
  162.         self.mainLabel.grid(row=0, column=0, sticky="w")
  163.         self.mainEntry.grid(row=0, column=1)
  164.         self.subLabel.grid(row=1, column=0, sticky="w")
  165.         self.subEntry.grid(row=1, column=1)
  166.         self.movieLabel.grid(row=2, column=0, sticky="w")
  167.         self.movieEntry.grid(row=2, column=1)
  168.         self.helpButton.grid(row=3, column=0, sticky="sw", pady=10)
  169.         self.loadButton.grid(row=3, column=1, sticky="sw", pady=10)
  170.         self.addButton.grid(row=3, column=1, sticky="s", pady=10)
  171.         self.startButton.grid(row=3, column=1, sticky="se", pady=10)
  172.         self.statusLabel.grid(row=4, column=0, columnspan=2, sticky="nswe")
  173.         # events for resetting the pink "error level"
  174.         self.mainEntry.bind("<KeyRelease>", self.handle_event)
  175.         self.subEntry.bind("<KeyRelease>", self.handle_event)
  176.         self.movieEntry.bind("<KeyRelease>", self.handle_event)
  177.  
  178.  
  179. if __name__ == "__main__":
  180.     # only if not imported
  181.     # create the main window with a frame in it
  182.     GUI(Tk())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement