lolamontes69

CheckButton Tk-GUI for sentimental phrase dataset creation

Jan 6th, 2014
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.28 KB | None | 0 0
  1. """ A simple Tkinter Gui for creating a Sentimental Dataset.
  2.    This version uses Checkbuttons because most phrases can be
  3.    assigned to more than one emotion :)
  4.  
  5.    The dictionaries are loaded from and persisted with cPickle.
  6.  
  7.    The imported dictionaries are in the format:
  8.        {7875: 'the story is gripping, and of extreme importance.', 7876: ...}
  9.    The resultant dataset is in the format:
  10.        {'this story is great' : [0, 1, 1, 0, 0, 1, 0, 0, 0], 'humbug': ...}
  11.                   --lolamontes69
  12. """
  13.  
  14. from Tkinter import *
  15. from tkFileDialog import *
  16. import cPickle
  17. from time import sleep
  18. from tkMessageBox import askyesno
  19.  
  20. class HoldingClass:
  21.     pass
  22.  
  23. hc=HoldingClass()
  24.  
  25. hc.tempDic = {"frog": "croak", "cat": "meow", "dog": "woof", "sheep": "baa"}
  26. hc.tempKeys = hc.tempDic.keys()
  27. hc.newDataset = {}
  28.  
  29. class CheckB:
  30.     ''' A class of checkbuttons '''
  31.     def __init__(self, master, r=0, c=0, rsp=1):
  32.         textlist = [["POSITIVE\nSURPRISE","HAPPY","NEUTRAL","SAD","NEGATIVE\nSURPRISE"],
  33.                     ["AROUSAL","LOVE\nAFFECTION","NEUTRAL","FEAR","ANGER\nDISGUST"]]
  34.         self.text = textlist[r][c]
  35.         self.var = DoubleVar()
  36.         self.i = Checkbutton(master, text=self.text,
  37.                        fg="blue", bg="black", height=3, width=9, font=('Verdana', 14, "bold"),
  38.                        padx=5, pady=5)
  39.         self.i.bind("<Button-1>", self.colorChange)
  40.         self.var.set(0)
  41.         self.i.grid(row=r,column=c,rowspan=rsp)
  42.  
  43.     def colorChange(self,*args):
  44.         ''' Change textcolor of button and do var.set() '''
  45.         if int(self.var.get())==0:
  46.              self.var.set(1)
  47.              self.i.config(fg="red")
  48.         else:
  49.              self.var.set(0)
  50.              self.i.config(fg="blue")
  51.  
  52.     def resetVar(self,*args):
  53.         ''' reset checkbutton '''
  54.         self.var.set(0)
  55.         self.i.config(fg="blue")
  56.         self.i.deselect()
  57.  
  58. def loadcPks(filename):
  59.     ''' Load dictionary from cPickle '''
  60.     fr = open(filename)
  61.     pickledDic = cPickle.load(fr)
  62.     fr.close()
  63.     return pickledDic
  64.  
  65. def loadDict():
  66.     ''' Get name of dict to load '''
  67.     filename=askopenfilename(filetypes=[("All Files", "*")])
  68.     hc.tempDic = loadcPks(filename)
  69.     hc.tempKeys = hc.tempDic.keys()
  70.     # Add first quote to textframe
  71.     hc.quote=hc.tempDic[hc.tempKeys[0]]
  72.     updateTextframe()
  73.  
  74. def makeCommandMenu():
  75.     ''' Make top menu '''
  76.     CmdBtn = Menubutton(hc.mBar, text='File', bg="black", fg="red", underline=0)
  77.     CmdBtn.pack(side=LEFT, padx="2m")
  78.     CmdBtn.menu = Menu(CmdBtn)
  79.     for lab, cmd in [('Load dictionary...',loadDict),
  80.                      ('Save original dictionary...',saveOrigDict),
  81.                      ('Save classified dictionary...',saveDict),('Quit',quitGui)]:
  82.         CmdBtn.menu.add_command(label=lab, underline=0, foreground="red",
  83.                                 background='black', activebackground='green',
  84.                                 command=cmd)
  85.     CmdBtn['menu'] = CmdBtn.menu
  86.     return CmdBtn
  87.  
  88. def processResults(*args):
  89.     ''' Process and update '''
  90.     resList = []
  91.     #get results and reset checkbuttons
  92.     for a in hc.slist:
  93.         resList.append(int(a.var.get()))
  94.         a.resetVar()
  95.     # add results to dictionary and update textframe with new phrase
  96.     if len(hc.tempKeys)>1:
  97.         hc.newDataset[hc.tempDic[hc.tempKeys[0]]] = resList
  98.         print hc.tempDic[hc.tempKeys[0]],":",resList
  99.         del hc.tempDic[hc.tempKeys[0]]
  100.         del hc.tempKeys[0]
  101.         hc.quote=hc.tempDic[hc.tempKeys[0]]
  102.         updateTextframe()
  103.     # if we have ran out of phrases....
  104.     else:
  105.         hc.newDataset[hc.tempDic[hc.tempKeys[0]]] = resList
  106.         print hc.tempDic[hc.tempKeys[0]],":",resList
  107.         hc.tempDic = None
  108.         hc.tempKeys = None
  109.         hc.quote="End of dictionary"
  110.         updateTextframe("red")
  111.         hc.frm2.destroy()
  112.         hc.xf1.destroy()
  113.         hc.b1.config(text="EXIT")
  114.         hc.b1.unbind("<Button-1>")
  115.         hc.b1.bind("<Button-1>",quitGui)
  116.         hc.root.update_idletasks()
  117.         saveDict()
  118.  
  119. # add do you want to save your progress dialogs on window shut too
  120. def quitGui(*args):
  121.     ''' Close the GUI '''
  122.     a=askyesno(message="Do you want to save\nyour progress?")
  123.     if not a:
  124.         try: hc.root.destroy()
  125.         except: pass
  126.     else:
  127.         try:
  128.             saveDict()
  129.             hc.root.destroy()
  130.         except: pass
  131.  
  132. def saveDict():
  133.     ''' Persist the classifier in cPickles '''
  134.     try:
  135.         filename=asksaveasfilename(filetypes=[("All Files", "*")])
  136.         f = open(filename, 'w')
  137.         cPickle.dump(hc.newDataset, f)   # a list
  138.         f.close()
  139.     except:
  140.         prev = hc.text1.get(0.0,END).strip()
  141.         sleep(0.5)
  142.         hc.quote="Dictionary not saved"
  143.         updateTextframe("red")
  144.         hc.root.update()
  145.         sleep(4)
  146.         hc.quote=prev
  147.         updateTextframe()
  148.         hc.root.update_idletasks()
  149.  
  150. def saveOrigDict():
  151.     ''' Persist the classifier in cPickles '''
  152.     filename=asksaveasfilename(filetypes=[("All Files", "*")])
  153.     try:
  154.         f = open(filename, 'w')
  155.         cPickle.dump(hc.tempDic, f)   # a list
  156.         f.close()
  157.     except:
  158.         prev = hc.text1.get(0.0,END).strip()
  159.         sleep(0.5)
  160.         hc.quote="Dictionary not saved"
  161.         updateTextframe("red")
  162.         hc.root.update()
  163.         sleep(3)
  164.         hc.quote=prev
  165.         updateTextframe("red")
  166.         hc.root.update_idletasks()
  167.  
  168. def updateTextframe(fore="green"):
  169.     hc.text1.config(fg=fore)
  170.     hc.text1.delete(0.0,END)
  171.     hc.text1.insert(END,hc.quote)
  172.  
  173. def mainGui():
  174.     hc.root = Tk()
  175.     hc.root.title('Phrase Classifier')
  176.     hc.root.config(borderwidth=10, background="black")
  177.     # Menubar
  178.     hc.mBar = Frame(hc.root, bg="black", borderwidth=2)
  179.     hc.mBar.pack(fill=X)
  180.     CmdBtn = makeCommandMenu()
  181.     hc.mBar.tk_menuBar(CmdBtn)
  182.     # Label above textframe
  183.     hc.xf1 = Frame(hc.root, borderwidth=2, pady=5, background="black")
  184.     Label(hc.xf1, text="Which emotions are contained in this phrase? ",
  185.           font=('Verdana', 14, "bold"), width=76, bg="black", fg="white",
  186.           justify=CENTER).grid(row=0, padx=0, pady=15)
  187.     hc.xf1.pack(side="top")
  188.     # Textframe
  189.     xf2 = Frame(hc.root, borderwidth=2, pady=30, background="black")
  190.     hc.quote=hc.tempDic[hc.tempKeys[0]]
  191.     hc.text1 = Text(xf2, height=5, width=50, bg="black", fg="green",font=('Verdana', 18, "bold"))
  192.     hc.text1.grid(row=1, padx=5, pady=15)
  193.     hc.text1.insert(END,hc.quote)
  194.     xf2.pack(side="top")
  195.     # Process data button
  196.     hc.frm3 = Frame(hc.root, borderwidth=2, pady=10, background="black")
  197.     hc.b1 = Button(hc.frm3, text="NEXT PHRASE",height=1,fg="white", bg="black",
  198.                    relief=RAISED, border=5, font=('Verdana', 18, "bold"))
  199.     hc.b1.grid(row=2, column=2, padx=5, pady=5)
  200.     hc.b1.bind("<Button-1>",processResults)
  201.     hc.frm3.pack(side=BOTTOM)
  202.     # Checkbuttons
  203.     hc.frm2 = Frame(hc.root, borderwidth=2, pady=30, background="black")
  204.     hc.slist = []
  205.     for i in range(2):
  206.         for j in range(5):
  207.             if j==2:
  208.                 if i==0: hc.slist.append(CheckB(hc.frm2,i,j,2))
  209.             else: hc.slist.append(CheckB(hc.frm2,i,j))
  210.     hc.frm2.pack(side=BOTTOM)
  211.     hc.root.mainloop()
  212.  
  213.  
  214. if __name__ == "__main__":
  215.     mainGui()
Advertisement
Add Comment
Please, Sign In to add comment