CSCI/CMPE 4341 Topic: Programming in Python Chapter 8: Graphical User Interface Components Xiang...

34
CSCI/CMPE 4341 Topic: CSCI/CMPE 4341 Topic: Programming in Python Programming in Python Chapter 8: Graphical User Chapter 8: Graphical User Interface Components Interface Components Xiang Lian The University of Texas – Pan American Edinburg, TX 78539 [email protected] 1

Transcript of CSCI/CMPE 4341 Topic: Programming in Python Chapter 8: Graphical User Interface Components Xiang...

  • CSCI/CMPE 4341 Topic: Programming in PythonChapter 8: Graphical User Interface ComponentsXiang LianThe University of Texas Pan AmericanEdinburg, TX [email protected] *

  • ObjectivesIn this chapter, you will:Become aware of using Tkinter module to build graphical user interfacesCreate and manipulate labels, text fields, buttons, check boxes, and radio buttonsLearn to use mouse events and keyboard events

    *

  • IntroductionGraphical user interface (GUI) enables user interaction via mouse or keyboard with programGUIs built from components called widgets

    *

  • An Example of GUI Components in an Internet Explorer*

  • Python GUIs*

  • Event HandlingGUI components generate events due to user interactionEvents drive the program to perform a taskClickChangeTimeEvent handler is what you write*

  • tkinter ModulePythons standard GUI package tkinter moduletkinter library provides object-oriented interface to Tk GUI toolkitEach GUI component class inherits from class WidgetGUI consists of top-level (or parent) component that can contain children componentsClass Frame serves as a top-level component*try:from Tkinter import * # for Python2 except ImportError: from tkinter import * # for Python3

  • Python 2.X Python 3.XTkinter tkintertkMessageBox tkinter.messageboxtkColorChooser tkinter.colorchoosertkFileDialog tkinter.filedialogtkCommonDialog tkinter.commondialogtkSimpleDialog tkinter.simpledialogtkFont tkinter.fontTkdnd tkinter.dndScrolledText tkinter.scrolledtextTix tkinter.tixttk tkinter.ttk*

  • *tkinter OverviewWidget subclasses:

  • Label Component LabelLabels Display text or imagesProvide instructions and other informationCreated by tkinter class Label

    *

    2002 Prentice Hall. All rights reserved.Outline

    *fig10_04.py# Fig. 10.4: fig10_04.py# Label demonstration. from tkinter import * class LabelDemo( Frame ):"""Demonstrate Labels""" def __init__( self ):"""Create three Labels and pack them""" Frame.__init__( self ) # initializes Frame object

    # frame fills all available spaceself.pack( expand = YES, fill = BOTH )self.master.title( "Labels" )

    self.Label1 = Label( self, text = "Label with text" )

    # resize frame to accommodate Labelself.Label1.pack()

    self.Label2 = Label( self,text = "Labels with text and a bitmap" ) # insert Label against left side of frameself.Label2.pack( side = LEFT )

    # using default bitmap image as labelself.Label3 = Label( self, bitmap = "warning" )self.Label3.pack( side = LEFT )

    def main():LabelDemo().mainloop() # starts event loopif __name__ == "__main__":main()

  • Python Program GUI*

  • *Bitmap Images for Labels

    Bitmap image name

    Image

    Bitmap image name

    Image

    error

    hourglass

    gray75

    info

    gray50

    questhead

    gray25

    question

    gray12

    warning

    Fig. 10.5Bitmap images available.

  • Entry Component TextBoxTextboxAreas in which users can enter text or programmers can display a line of textCreated by Entry class event occurs when user presses Enter key inside Entry component

    *

    2002 Prentice Hall. All rights reserved.Outline

    *fig10_06.py# Fig. 10.6: fig10_06.py# Entry components and event binding demonstration. from tkinter import *from tkinter.messagebox import * class EntryDemo( Frame ):"""Demonstrate Entrys and Event binding""" def __init__( self ):"""Create, pack and bind events to four Entries""" Frame.__init__( self )self.pack( expand = YES, fill = BOTH )self.master.title( "Testing Entry Components" )self.master.geometry( "325x100" ) # width x length self.frame1 = Frame( self )self.frame1.pack( pady = 5 ) self.text1 = Entry( self.frame1, name = "text1" ) # bind the Entry component to eventself.text1.bind( "", self.showContents )self.text1.pack( side = LEFT, padx = 5 )

    self.text2 = Entry( self.frame1, name = "text2" )

    # insert text into Entry component text2self.text2.insert( INSERT, "Enter text here" )self.text2.bind( "", self.showContents )self.text2.pack( side = LEFT, padx = 5 ) self.frame2 = Frame( self )self.frame2.pack( pady = 5 )

    2002 Prentice Hall. All rights reserved.Outline

    *fig10_06.py

    self.text3 = Entry( self.frame2, name = "text3" )self.text3.insert( INSERT, "Uneditable text field" ) # prohibit user from altering text in Entry component text3self.text3.config( state = DISABLED )self.text3.bind( "", self.showContents )self.text3.pack( side = LEFT, padx = 5 )

    # text in Entry component text4 appears as *self.text4 = Entry( self.frame2, name = "text4", show = "*" )self.text4.insert( INSERT, "Hidden text" )self.text4.bind( "", self.showContents )self.text4.pack( side = LEFT, padx = 5 ) def showContents( self, event ):"""Display the contents of the Entry""" # acquire name of Entry component that generated eventtheName = event.widget.winfo_name()

    # acquire contents of Entry component that generated eventtheContents = event.widget.get()showinfo( "Message", theName + ": " + theContents ) def main():EntryDemo().mainloop() if __name__ == "__main__":main()

  • *

  • Button Component ButtonButtonsGenerates events when selectedFacilitate selection of actionsCreated with class ButtonDisplays text or image called button labelEach should have unique label

    *

    2002 Prentice Hall. All rights reserved.Outline

    *fig10_07.py# Fig. 10.7: fig10_07.py# Button demonstration. from tkinter import *from tkinter.messagebox import * class PlainAndFancy( Frame ):"""Create one plain and one fancy button""" def __init__( self ):"""Create two buttons, pack them and bind events""" Frame.__init__( self )self.pack( expand = YES, fill = BOTH )self.master.title( "Buttons" )

    # create button with textself.plainButton = Button( self, text = "Plain Button",command = self.pressedPlain )self.plainButton.bind( "", self.rolloverEnter )self.plainButton.bind( "", self.rolloverLeave )self.plainButton.pack( side = LEFT, padx = 5, pady = 5 )

    # create button with imageself.myImage = PhotoImage( file = "logotiny.gif" )self.fancyButton = Button( self, image = self.myImage,command = self.pressedFancy )self.fancyButton.bind( "", self.rolloverEnter )self.fancyButton.bind( "", self.rolloverLeave )self.fancyButton.pack( side = LEFT, padx = 5, pady = 5 )

    def pressedPlain( self ):showinfo( "Message", "You pressed: Plain Button" )

    2002 Prentice Hall. All rights reserved.Outline

    *fig10_07.pydef pressedFancy( self ):showinfo( "Message", "You pressed: Fancy Button" )

    def rolloverEnter( self, event ):event.widget.config( relief = GROOVE )

    def rolloverLeave( self, event ):event.widget.config( relief = RAISED ) def main():PlainAndFancy().mainloop() if __name__ == "__main__":main()

    eventtrigger pressed eventshowinfo(.., ..) event

  • Checkbutton and Radiobutton ComponentsCheckboxSmall white square Either blank or contains a checkmarkDescriptive text referred to as checkbox labelAny number of boxes selected at a timeCreated by class CheckbuttonRadio buttonMutually excusive options only one radio button selected at a timeCreated by class RadiobuttonBoth have on/off or True/False values and two states selected and not selected (deselected)*

    2002 Prentice Hall. All rights reserved.Outline

    *fig10_08.py# Fig. 10.8: fig10_08.py# Checkbuttons demonstration. from tkinter import * class CheckFont( Frame ):"""An area of text with Checkbutton controlled font""" def __init__( self ):"""Create an Entry and two Checkbuttons""" Frame.__init__( self )self.pack( expand = YES, fill = BOTH )self.master.title( "Checkbutton Demo" ) self.frame1 = Frame( self )self.frame1.pack() self.text = Entry( self.frame1, width = 40,font = "Arial 10" )self.text.insert( INSERT, "Watch the font style change" )self.text.pack( padx = 5, pady = 5 ) self.frame2 = Frame( self )self.frame2.pack() # create boolean variableself.boldOn = BooleanVar()

    # create "Bold" checkbuttonself.checkBold = Checkbutton( self.frame2, text = "Bold", variable = self.boldOn, command = self.changeFont )self.checkBold.pack( side = LEFT, padx = 5, pady = 5 )

    2002 Prentice Hall. All rights reserved.Outline

    *fig10_08.py# create boolean variableself.italicOn = BooleanVar()

    # create "Italic" checkbuttonself.checkItalic = Checkbutton( self.frame2, text = "Italic", variable = self.italicOn, command = self.changeFont )self.checkItalic.pack( side = LEFT, padx = 5, pady = 5 )

    def changeFont( self ):"""Change the font based on selected Checkbuttons""" desiredFont = "Arial 10"

    if self.boldOn.get():desiredFont += " bold"

    if self.italicOn.get():desiredFont += " italic" self.text.config( font = desiredFont ) def main():CheckFont().mainloop() if __name__ == "__main__":main()

    2002 Prentice Hall. All rights reserved.Outline

    *fig10_08.py

    2002 Prentice Hall. All rights reserved.Outline

    *fig10_09.py# Fig. 10.9: fig10_09.py# Radiobuttons demonstration. from tkinter import * class RadioFont( Frame ):"""An area of text with Radiobutton controlled font""" def __init__( self ):"""Create an Entry and four Radiobuttons""" Frame.__init__( self )self.pack( expand = YES, fill = BOTH )self.master.title( "Radiobutton Demo" )

    self.frame1 = Frame( self )self.frame1.pack() self.text = Entry( self.frame1, width = 40,font = "Arial 10" )

    self.text.insert( INSERT, "Watch the font style change" )self.text.pack( padx = 5, pady = 5 ) self.frame2 = Frame( self )self.frame2.pack() fontSelections = [ "Plain", "Bold", "Italic", "Bold/Italic" ]

    self.chosenFont = StringVar() # initial selectionself.chosenFont.set( fontSelections[ 0 ] )

    2002 Prentice Hall. All rights reserved.Outline

    *fig10_09.py# create group of Radiobutton components with same variablefor style in fontSelections:aButton = Radiobutton( self.frame2, text = style,variable = self.chosenFont, value = style,command = self.changeFont )aButton.pack( side = LEFT, padx = 5, pady = 5 ) def changeFont( self ):"""Change the font based on selected Radiobutton""" desiredFont = "Arial 10"

    if self.chosenFont.get() == "Bold":desiredFont += " bold"elif self.chosenFont.get() == "Italic":desiredFont += " italic"elif self.chosenFont.get() == "Bold/Italic":desiredFont += " bold italic"

    self.text.config( font = desiredFont )

    def main():RadioFont().mainloop() if __name__ == "__main__":main()

  • *

  • Mouse Event HandlingEvents that occur as a result of user interaction with a mousetkinter events described by strings following pattern type specifies kind of event (e.g. Button and Return)Button here is mouse button!Specific mouse button is example of a detailPrefix Double is example of a modifier

    *

  • Mouse Event Handling (cont'd)*

    Event format

    Description

    Mouse button n has been selected while the mouse pointer is over the component. n may be 1 (left button), 2 (middle button) or 3 (right button). (e.g., ).

    ,

    Shorthand notations for .

    Mouse button n has been released.

    Mouse is moved with button n held down.

    Mouse button n has been Prefix clicked over the component.

    Prefix may be Double or Triple.

    Mouse pointer has entered the component.

    Mouse pointer has exited the component.

    Fig. 10.10Mouse event formats.

    2002 Prentice Hall. All rights reserved.Outline

    *fig10_11.py# Fig. 10.11: fig10_11.py# Mouse events example. from tkinter import * class MouseLocation( Frame ):"""Demonstrate binding mouse events""" def __init__( self ):"""Create a Label, pack it and bind mouse events""" Frame.__init__( self )self.pack( expand = YES, fill = BOTH )self.master.title( "Demonstrating Mouse Events" )self.master.geometry( "275x100" ) self.mousePosition = StringVar() # displays mouse positionself.mousePosition.set( "Mouse outside window" )self.positionLabel = Label( self,textvariable = self.mousePosition )self.positionLabel.pack( side = BOTTOM ) # bind mouse events to windowself.bind( "", self.buttonPressed )self.bind( "", self.buttonReleased ) self.bind( "", self.enteredWindow )self.bind( "", self.exitedWindow )self.bind( "", self.mouseDragged )

    def buttonPressed( self, event ):"""Display coordinates of button press""" self.mousePosition.set( "Pressed at [ " + str( event.x ) +", " + str( event.y ) + " ]" )

    2002 Prentice Hall. All rights reserved.Outline

    *fig10_11.pydef buttonReleased( self, event ):"""Display coordinates of button release""" self.mousePosition.set( "Released at [ " + str( event.x ) +", " + str( event.y ) + " ]" )

    def enteredWindow( self, event ):"""Display message that mouse has entered window""" self.mousePosition.set( "Mouse in window" )

    def exitedWindow( self, event ):"""Display message that mouse has left window""" self.mousePosition.set( "Mouse outside window" ) def mouseDragged( self, event ):"""Display coordinates of mouse being moved""" self.mousePosition.set( "Dragged at [ " + str( event.x ) +", " + str( event.y ) + " ]" ) def main():MouseLocation().mainloop() if __name__ == "__main__":main()

  • *

  • Keyboard Event HandlingKeyboard events generated when users press and release keys

    *

    Event format

    Description of Event

    Any key has been selected.

    Any key has been released.

    key has been selected or released.

    ,

    Shorthand notation for

    and .

    Shorthand notation for . This format works only for printable characters (excluding space and less-than sign).

    key has been selected while Prefix is held down. Possible prefixes are Alt, Shift and Control. Note that multiple prefixes are also possible (e.g., ).

    Fig. 10.13Keyboard event formats.

  • *

    Some slides are borrowed and revised from lecture slides of the textbook***http://stackoverflow.com/questions/673174/file-dialogs-of-tkinter-in-python-3***