Python for dummies, Part III
Ah, the GUI at last. This wasn't really a requirement but I'd rather have something that looks more like a proper application than a command line interface -command line interfaces are sooo eighties. To combine this with my previous sections, I just need to import them and 'call' their functionality from within this class.
The code to create the user interface is listed below.
from Tkinter import *
class TemplateGUI(Frame):
# the outermost frame
def __init__(self, parent=0):
Frame.__init__(self,parent)
self.type = 2
self.master.title('GUI Template')
self.buildUI()
def buildUI(self):
fFile = Frame(self)
Label(fFile, text="Filename: ").pack(side="left")
self.eName = Entry(fFile)
self.eName.insert(INSERT,"example.txt")
self.eName.pack(side=LEFT, padx=5)
# example of radio buttons to get gender data
fType = Frame(fFile, borderwidth=1, relief=SUNKEN)
self.rMale = Radiobutton(fType, text="Male", variable = self.type, value=2, command=self.doMale)
self.rMale.pack(side=TOP, anchor=W)
self.rFemale = Radiobutton(fType, text="Female", variable=self.type, value=1, command=self.doFemale)
self.rFemale.pack(side=TOP, anchor=W)
# 'Male' is the default radio button selection
self.rMale.select()
fType.pack(side=RIGHT, padx=3)
fFile.pack(side=TOP, fill=X)
self.txtBox = Text(self, width=60, height=10)
self.txtBox.pack(side=TOP, padx=3, pady=3)
# buttons to execute application functionality
fButts = Frame(self)
self.bStart = Button(fButts, text="Start", command=self.doStart)
self.bStart.pack(side=LEFT, anchor=W, padx=50, pady=2)
self.bReset = Button(fButts, text="Reset", command=self.doReset)
self.bReset.pack(side=LEFT, padx=10)
self.bQuit = Button(fButts, text="Quit", command=self.doQuit)
self.bQuit.pack(side=RIGHT, anchor=E, padx=50, pady=2)
fButts.pack(side=BOTTOM, fill=X)
self.pack()
def doQuit(self):
self.quit()
def doReset(self):
self.txtBox.delete(1.0, END)
self.eName.delete(0, END)
self.rMale.select()
def doMale(self):
self.type = 2
def doFemale(self):
self.type = 1
def doStart(self):
filename = self.eName.get()
if filename == "":
self.txtBox.insert(END,"\nNo filename provided!\n")
return
self.txtBox.insert(END, "\nStarted application...\n")
resultStr = "Success"
self.txtBox.insert(END, resultStr)
myApp = TemplateGUI()
myApp.mainloop()
When run, the code above produces the GUI below:
Neat, huh?