12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 19Case study: Tkinter19.1 GUIMost of the programs we have seen so far are text-based, but many programs use graphical userinterfaces, alsoknown as GUIs.<strong>Python</strong>providesseveralchoicesforwritingGUI-basedprograms,includingwx<strong>Python</strong>,Tkinter,andQt. Each has pros and cons, which iswhy <strong>Python</strong> has not converged on astandard.The one I will present in this chapter is Tkinter because I think it is the easiest to get started with.Most ofthe concepts inthischapter apply totheother GUI modules, too.There are several books and web pages about Tkinter. One of the best online resources is An IntroductiontoTkinter by Fredrik Lundh.I have written a module called Gui.py that comes with Swampy. It provides a simplified interfacetothefunctions and classes inTkinter. The examples inthischapter arebased on thismodule.Here isasimpleexample that creates and displays a Gui:To create aGUI, you have toimportGuiand instantiate aGui object:from Gui import *g = Gui()g.title('Gui')g.mainloop()When you run this code, a window should appear with an empty gray square and the title Gui.mainloop runs the event loop, which waits for the user to do something and responds accordingly.Itisaninfiniteloop;itrunsuntiltheuserclosesthewindow,orpressesControl-C,ordoessomethingthat causes theprogram toquit.ThisGuidoesn’tdomuchbecauseitdoesn’thaveanywidgets. Widgetsaretheelementsthatmakeup aGUI;they include:Button: A widget, containing text or an image, that performs an action when pressed.Canvas: A region that can display lines,rectangles, circles and other shapes.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!