15. Go exploring: Some pointers for applications of Python beyond this course
15.3 User interfaces: windows dialog boxes, pull-down menus, etc
windows interface with pull-down menus and everything. There are several options to do this. Whichever you like or find easy to use really depends on your taste. Some prefer an intuitive editor like provided with PyQt (but with messy code), others like the straightforward typing of Tkinter (with clearer, simple code). Here is the list options:
15.3.1 Tkinter
Already provided with Python, builds on Tcl/Tk library. The TkInter module is an easy way to use the standard window dialog boxes, e.g. the File Open dialog box (named:
tkFileDialog.askopenfilename ) in the example below: import os,sys
from Tkinter import * import tkFileDialog
# Tkinter File Open Dialog for Mazefile
os.chdir('data') # Move to the subfolder named data master = Tk()
master.withdraw() # Hiding tkinter app window
file_path = tkFileDialog.askopenfilename(title="Open file", filetypes=[("Text files",".txt"),("All files",".*")] ) # Quit when user selects Cancel or No file
if file_path == "": sys.exit("Ready.")
# Close Tk, return to working directory master.quit()
os.chdir('..') # Move back to the main folder
Even though the Python source will look the same, the OS determines the actual look of these standard dialogboxes
Some documentation can be found in Python Reference, but more can be found in the pdf file at
http://www.pythonware.com/media/data/an-introduction-to-tkinter.pdf. It contains basic functions to build dialog boxes with many controls as well as the handle to call most standard windows dialogs. Easy to use but requires hand-coding and is rather basic in terms of graphics. Still, the IDLE shell and editor you are using, were made in Tkinter. Tcl/Tk has a long-standing record in the Unix world from times far
before Python even existed.
An example calculator (see figure below) of which the soruce code is given below the figure (made by Eline ter Hofstede):
from Tkinter import
StringVar,Tk,Label,Entry,OptionMenu ,Button,PhotoImage
# Change operation according to selection
def changeLabel():
radioValue = optvar.get()
if radioValue == '*':
name = str(float(str(yourName.get())) * float(str(yourName2.get())))
if radioValue == '+':
name = str(float(str(yourName.get())) + float(str(yourName2.get())))
if radioValue == '-':
name = str(float(str(yourName.get())) - float(str(yourName2.get())))
if radioValue == '/':
name = str(float(str(yourName.get())) / float(str(yourName2.get()))) labelText.set(name)
# Set up window app = Tk()
app.title('Rekenmachine') app.grid()
app.resizable(False,False) # Create an entry field custName = StringVar(None)
yourName = Entry(app, textvariable=custName) yourName.grid(row = 0, column = 0, padx = 8) # Create an entry field
custName2 = StringVar(None)
yourName2 = Entry(app, textvariable=custName2) yourName2.grid(row = 0, column = 2)
# Option menu, select the operator optvar = StringVar()
optvar.set("+")
optionm = OptionMenu(app, optvar, "+","-","/","*").grid(row = 0, column = 1) # Create an equal to button
button1 = Button(app, text='=',command=changeLabel) button1.grid(row = 0, column = 3, padx = 8)
# Create a field for the results labelText = StringVar()
labelText.set('Result')
label1 = Label(app, textvariable=labelText, height=4, bg='white') label1.grid(row = 1, column = 0,columnspan=3 )
# TUDelft logo
image = PhotoImage(file='tud.gif') label2 = Label(app, image = image)
label2.grid(column=0,row=2,columnspan=8,pady=8) app.configure(background='white')
# Run Tkinter main event loop app.mainloop()
15.3.2 PyQt
Qt from Riverbank Computing (: http://www.riverbankcomputing.co.uk/software/pyqt/intro) provides an environment similar to Tkinter. Comes with many extras, like a QtDesigner, allowing you to graphically draw the dialog boxes. The Spyder editor and IDE were built using PyQt. Builds on Nokia's Qt application framework and runs on all platforms supported by Qt including Windows, MacOS/X and Linux. As a result of using QtDesigner the code is
autogenerated and looks less nice. The programming effrot then comes down to connecting the right functions to hooks provided by the automatically generated code.
15.3.4 wxPython
Can be found at http://wxpython.org/ Also one of the classics in the Python community, wxPython is fully Open Source, cross-platform (Windows/Linux/Mac OS). I would say it’s something in between Tkinter and PyQt in terms of funtionality.
To given an impression of the code, a simple Hello world example is given below. It shows a window called Hello world and catches the Close event when the user closes the window to ask for a verification with an OK/Cancel Messagebox.
import wx
class Frame(wx.Frame):
def __init__(self, title):
wx.Frame.__init__(self, None, title=title, size=(350,200)) self.Bind(wx.EVT_CLOSE, self.OnClose)
def OnClose(self, event):
dlg = wx.MessageDialog(self,
"Are you sure? Do you really want to close this application?", "Confirm Exit", wx.OK|wx.CANCEL|wx.ICON_QUESTION)
result = dlg.ShowModal() dlg.Destroy()
if result == wx.ID_OK:
self.Destroy() app = wx.App(redirect=True) top = Frame("Hello World") top.Show()
app.MainLoop() 15.3.5 GLUT
GLUT, which is a part of OpenGL, is the good old user interface system used by all Open GL fans. Robust, does the job on all platforms, but not always very easy to use.
15.3.6 Glade Designer for Gnome
Glade is, like Qt Designer, a tool to graphically edit your dialog boxes and your GUI. It is built on the Gnome desktop and uses the PyGTK library.
PyGTK is not included in python(x,y) but can be downloaded from www.pygtk.org . The Glade program can be found at: http://glade.gnome.org/
As with all of these editor, it results in a mix of generated code (XML data in this case, read by the PyGTK module) and e.g. Python code you edit yourself. You connect buttons or fields to functions for which you can add the source to add functionality: