GUI Programming Using Tkinter2

3y ago
101 Views
20 Downloads
552.17 KB
62 Pages
Last View : 15d ago
Last Download : 3m ago
Upload by : Jenson Heredia
Transcription

1GUI PROGRAMMINGUSING TKINTERCuauhtémoc CarbajalITESM CEMApril 17, 2013

2Agenda Introduction Tkinter and Python Programming Tkinter Examples

3INTRODUCTION

4Introduction In this lecture, we will give you a brief introduction to the subject of graphical user interface (GUI) programming.We cannot show you everything about GUI applicationdevelopment in just one lecture, but we will give you a verysolid introduction to it.The primary GUI toolkit we will be using is Tk, Python’s defaultGUI. We’ll access Tk from its Python interface called Tkinter(short for “Tk interface”).Tk is not the latest and greatest, nor does it have the mostrobust set of GUI building blocks, but it is fairly simple to use,and with it, you can build GUIs that run on most platforms.Once you have completed this lecture, you will have the skillsto build more complex applications and/or move to a moreadvanced toolkit. Python has bindings or adapters to most ofthe current major toolkits, including commercial systems.

5What Are Tcl, Tk, and Tkinter? Tkinter is Python’s default GUI library. It is based on the Tk toolkit, originally designed for the Tool Command Language (Tcl). Due to Tk’spopularity, it has been ported to a variety of other scripting languages,including Perl (Perl/Tk), Ruby (Ruby/Tk), and Python (Tkinter).The combination of Tk’s GUI development portability and flexibilityalong with the simplicity of a scripting language integrated with thepower of systems language gives you the tools to rapidly design andimplement a wide variety of commercial-quality GUI applications.Python, along with Tkinter, provides a fast and exciting way to builduseful applications that would have taken much longer if you had toprogram directly in C/C with the native windowing system’slibraries.Once you have designed the application and the look and feel thatgoes along with your program, you will use basic building blocksknown as widgets to piece together the desired.Once you get Tkinter up on your system, it will take less than 15minutes to get your first GUI application running.

6Getting Tkinter Installed and Working Tkinter is not necessarily turned on by default on your system.You can determine whether Tkinter is available for your Pythoninterpreter by attempting to import the Tkinter module (inPython 1 and 2; renamed to tkinter in Python 3). If Tkinter isavailable, then no errors occur, as demonstrated in thefollowing: import tkinter If your Python interpreter was not compiled with Tkinterenabled, the module import fails. You might need to recompileyour Python interpreter to gain access to Tkinter. This usuallyinvolves editing the Modules/Setup file and then enabling allthe correct settings to compile your Python interpreter withhooks to Tkinter, or choosing to have Tk installed on yoursystem.

7Getting Tkinter Installed and Working onthe RPi Type the following line into a terminal window: sudo apt-get install python-tk Open a Python Shell: idle3 Import the Tkinter module: import tkinter

8The Tkinter Module: Adding Tk to yourApplications Do you need to do to have Tkinter as part of your application? First, it is not necessary to have an application already. You cancreate a pure GUI if you want, but it probably isn’t too usefulwithout some underlying software that does somethinginteresting. There are basically five main steps that are required to get yourGUI up and running:1.2.3.4.5.Import the Tkinter module (or from Tkinter import *).Create a top-level windowing object that contains your entire GUIapplication.Build all your GUI components (and functionality) on top (or within)of your top-level windowing object.Connect these GUI components to the underlying application code.Enter the main event loop.

9Introduction to GUI Programming Before going to the examples, we will give you a briefintroduction to GUI application development. This will provideyou with some of the general background you need to moveforward. Setting up a GUI application is similar to how an artist producesa painting. Conventionally, there is a single canvas onto whichthe artist must put all the work. Here’s how it works: you startwith a clean slate, a “top-level” windowing object on which youbuild the rest of your components. Think of it as a foundation to a house or the easel for an artist.In other words, you have to pour the concrete or set up youreasel before putting together the actual structure or canvas ontop of it. In Tkinter, this foundation is known as the top-levelwindow object.

10Windows and Widgets In GUI programming, a top-level root windowing objectcontains all of the little windowing objects that will be part ofyour complete GUI application. These can be text labels,buttons, list boxes, etc. These individual little GUI componentsare known as widgets. So when we say create a top-level window, we just mean thatyou need a place where you put all your widgets. In Python,this would typically look like this line: top Tkinter.Tk() # or just Tk() with "from Tkinter import *" The object returned by Tkinter.Tk() is usually referred toas the root window; hence, the reason why some applicationsuse root rather than top to indicate as such. Top-level windowsare those that show up stand-alone as part of your application.You can have more than one top-level window for your GUI, butonly one of them should be your root window.

11Windows and Widgets (2) You can choose to completely design all your widgetsfirst, and then add the real functionality, or do a little of thisand a little of that along the way. Widgets can be stand-alone or be containers. If a widgetcontains other widgets, it is considered the parent ofthose widgets. Accordingly, if a widget is contained inanother widget, it’s considered a child of the parent, theparent being the next immediate enclosing containerwidget. Usually, widgets have some associated behaviors, suchas when a button is pressed, or text is filled into a textfield. These types of user behaviors are called events,and the GUI’s response to such events are known ascallbacks.

12Event-Driven Processing Events can include the actual button press (and release),mouse movement, hitting the Return or Enter key, etc. Theentire system of events that occurs from the beginning until theend of a GUI application is what drives it. This is known asevent-driven processing. One example of an event with a callback is a simple mousemove. Suppose that the mouse pointer is sitting somewhere ontop of your GUI application. If you move the mouse to anotherpart of your application, something has to cause the movementof the mouse to be replicated by the cursor on your screen sothat it looks as if it is moving according to the motion of yourhand. These are mouse move events that the system mustprocess portray your cursor moving across the window. Whenyou release the mouse, there are no more events to process,so everything just remains idle on the screen again.

13Event-Driven Processing (2) The event-driven processing nature of GUIs fits right inwith client/server architecture. When you start a GUI application, it must perform some setupprocedures to prepare for the core execution, just as how a networkserver must allocate a socket and bind it to a local address. The GUI application must establish all the GUI components, thendraw (a.k.a. render or paint) them to the screen. This is theresponsibility of the geometry manager (more about this in amoment). When the geometry manager has completed arrangingall of the widgets, including the top-level window, GUI applicationsenter their server-like infinite loop. This loop runs forever waiting for GUI events, processing them, andthen going to wait for more events to process.

14Geometry ManagersGeometry managers allow us to organize widgets inside of a containerPlace geometry managerhttp://effbot.org/tkinterbook/place.htmPack geometry managerhttp://effbot.org/tkinterbook/pack.htmGrid geometry managerhttp://effbot.org/tkinterbook/grid.htm

15Geometry Managers Tk has three geometry managers that help withpositioning your widgetset: Placer: You provide the size of the widgets and locations to placethem; the manager then places them for you. The problem is thatyou have to do this with all the widgets, burdening the developerwith coding that should otherwise take place automatically. Packer: it packs widgets into the correct places (namely thecontaining parent widgets, based on your instruction), and for everysucceeding widget, it looks for any remaining “real estate” intowhich to pack the next one. The process is similar to how youwould pack elements into a suitcase when traveling. Grid: It is used to specify GUI widget placement, based on gridcoordinates. The Grid will render each object in the GUI in their gridposition. We will stick with the Packer.

16Packer Once the Packer has determined the sizes and alignments ofall your widgets, it will then place them on the screen for you. When all the widgets are in place, we instruct the application toenter the aforementioned infinite main loop. In Tkinter, the codethat does this is: Tkinter.mainloop() This is normally the last piece of sequential code your programruns. When the main loop is entered, the GUI takes over executionfrom there. All other actions are handled via callbacks, even exiting yourapplication. When you select the File menu and then click theExit menu option or close the window directly, a callback mustbe invoked to end your GUI application.

17Top-Level Window: Tkinter.Tk() We mentioned earlier that all main widgets are built on thetop-level window object. This object is created by the Tkclass in Tkinter and is instantiated as follows: import Tkinter top Tkinter.Tk() Within this window, you place individual widgets ormultiple-component pieces together to form your GUI.

18Hello Worldfrom Tkinter import Labelwidget Label(None, text 'Hello World')widget.pack()widget.mainloop()parent widgetoptions# get a widget# make a Label# arrange it in its parent# start the event loop1. Load a widget class from Tkinter2. Make an instance of it(repeat 1 and 2 as needed)3. Arrange the widget in its parent widget4. Enter the event looppython3from tkinter import Labelpythonfrom Tkinter import Label

19Tkinter Events and Binding Button‐1 ‐ left mouse button Button‐2 ‐ middle mouse button (on 3 button mouse) Button‐3 ‐ rightmost mouse button B1‐Motion ‐ mouse moved with left button depressed ButtonRelease‐1 ‐ left button released Double‐Button‐1 ‐ double click on button 1 Enter ‐ mouse pointer entered widget Leave ‐ mouse pointer left the widget FocusIn ‐ Keyboard focus moved to a widget FocusOut ‐ Keyboard focus moved to another widget Return ‐ Enter key depressed Key ‐ A key was depressed Shift‐Up ‐ Up arrow while holding Shift key Configure ‐ widget changed size or ents‐and‐bindings.htmMouseeventsKeyboardevents

20Event Handling Event sources (widgets) can specify their handlers command handlers callbacks

21Command Handlersuse the 'command ' keyword followed by the command you want executedex:from Tkinter import *root Tk()Button (root, text 'Press Me', command root.quit).pack(side LEFT)root.mainloop()

22Callbacks A callback is the name of the function that is to be run in response ofan event Callbacks can be defined as a free standing function in our program oras a class member.ex.from Tkinter import *def quit():print 'Hello, getting out of here'import sys; sys.exit()widget Button(None, text 'Press me to quit' , command quit)widget.pack()widget.mainloop()

23Bound Method CallbacksLet’s make a Hello Class and use it:from Tkinter import *class HelloClass:# create the window in the class constructordef init (self):widget Button(None, text 'Press Me to quit', command self.quit)widget.pack()def quit(self):print 'leaving now'import sys ; sys.exit()HelloClass()mainloop()# create a HelloClass object

24Binding Eventsfrom Tkinter import *def hello(event):print 'Double click to exit'def quit(event):print 'caught a double click, leaving'import sys ; sys.exit()widget Button(None, text 'Hello Event World')widget.pack()widget.bind(' Button‐1 ', hello)widget.bind(' Double‐1 ' , quit)widget.mainloop()

25TKINTER WIDGETS

26Tk WidgetsWidgetDescriptionButtonSimilar to a Label but provides additional functionality for mouse-overs, presses, and releases,as well as keyboard activity/eventsCanvasProvides ability to draw shapes (lines, ovals, polygons, rectangles); can contain images orbitmapsCheckbuttonSet of boxes, of which any number can be “checked”EntrySingle-line text field with which to collect keyboard inputFramePure container for other widgetsLabelUsed to contain text or imagesLabelFrameCombo of a label and a frame but with extra label attributesListboxPresents the user with a list of choices from which to chooseMenuActual list of choices “hanging” from a Menubutton from which the user can chooseMenubuttonProvides infrastructure to contain menus (pulldown, cascading, etc.)MessageSimilar to a Label, but displays multiline textPanedWindow A container widget with which you can control other widgets placed within itRadiobuttonSet of buttons, of which only one can be “pressed”ScaleLinear “slider” widget providing an exact value at current setting; with defined starting andending valuesScrollbarProvides scrolling functionality to supporting widgets, for example, Text, Canvas, Listbox, andEntrySpinboxTextToplevelCombination of an entry with a button letting you adjust its valueMultiline text field with which to collect (or display) text from userSimilar to a Frame, but provides a separate window container

27Standard attributes Dimensions Colors Fonts Anchors used to define where text is positionedrelative to a reference point. Relief styles refers to certain simulated 3-D effectsaround the

Python 1 and 2; renamed to tkinter in Python 3). If Tkinter is available, then no errors occur, as demonstrated in the following: import tkinter If your Python interpreter was not compiled with Tkinter enabled, the module import fails. You might need to recompile your Python interpreter to gain access to Tkinter. This usually

Related Documents:

layout and the components of the GUI Changes to this file are made in the Layout Editor - .m file - contains the code that controls the GUI You can program the callbacks in this file using the M-file Editor 28 Creating a GUI Typical stages of creating a GUI are: 1. Designing the GUI 2. Laying out the GUI - Using the Layout Editor 3.

In Java, GUI programming is object-oriented programming. This chapter covers the basics of GUI programming. The discussion will continue in Chap-ter 12 with more details and with more advanced techniques. 6.1 The Basic GUI Application There are two basic types of GUI program in Java: stand-alone applications and applets.

User Interface Programming in C#: Basics and Events Chris North CS 3724: HCI GUI Development: Goals 1. General GUI pro grammin concepts GUI components, layouts Event-based programming Graphics D irec tM a npul o,Am MVC architectures Data-driven UIs 2. C#, .NET Windows Forms Events, delegates GDI Threads .

Java GUI libraries Swing: the main Java GUI library – Benefits: Features; cross-platform compatibility; OO design – Paints GUI controls itself pixel-by-pixel Does not delegate to OS’s window system Abstract Windowing Toolkit (AWT): Sun's initial GUI library – Maps Java code to each operating system's real GUI system

No change in API which Apps refer to Apps can use API of each GUI-lib. Each GUI-lib has layer to adapt to PF Can have many different GUI-libs without change of PF. HMI Apps App FW Layer Service Layer AppLayer GUI-library GUI-lib PAL(*) ForAGL PF *PF Adaptation Layer HMI-Server (e.g.

the GUI toolkit for Tcl/Tk. Tcl (pronounced "tickle" and is an acronym for Tool Command Language) is a popular scripting language in the domains of embedded applications, testing, prototyping, and GUI development. Tk on the other hand is an open source, multiplatform widget toolkit that is used by many different languages for building GUI programs.

Programming a GUIDE GUI.2-8 About the Simple GUIDE GUI Example.2-9 Simple GUIDE GUI Components.2-9 View Simple GUIDE GUI Layout and Code File . Designing for Cross-Platform Compatibility.6-137 Default System Font.6-137 viii Contents. Standard Background .

approachablemusic.com Of course, learning the basic guitar chords is only the first step to learning guitar. To take your guitar playing to the next level, you also need to gain a rock-solid strum and learn how to use a capo.