Presentation is loading. Please wait.

Presentation is loading. Please wait.

WEEK 12-13 Introduction to GUI programming. Introduction Each data type can represent a certain set of values, and each had a set of associated operations.

Similar presentations


Presentation on theme: "WEEK 12-13 Introduction to GUI programming. Introduction Each data type can represent a certain set of values, and each had a set of associated operations."— Presentation transcript:

1 WEEK 12-13 Introduction to GUI programming

2 Introduction Each data type can represent a certain set of values, and each had a set of associated operations. The traditional programming view is that data is passive – it ’ s manipulated and combined with active operations.

3 Introduction Modern computer programs are built using an object-oriented approach. Most applications you ’ re familiar with have Graphical User Interfaces (GUI) that provide windows, icons, buttons and menus.

4 Introduction Python provides various options for developing graphical user interfaces (GUIs). Most important are listed below: Tkinter: Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. We would look this option in this tutorial. wxPython: This is an open-source Python interface for wxWindows http://wxpython.org.http://wxpython.org JPython: JPython is a Python port for Java which gives Python scripts seamless access to Java class libraries on the local machine http://www.jython.org.http://www.jython.org

5 Graphic User Interface Tkinter is the standard GUI library for Python. Python when combined with Tkinter provides a fast and easy way to create GUI applications. Tkinter provides a powerful object-oriented interface to the Tk GUI toolkit.

6 Graphic User Interface Creating a GUI application using Tkinter is an easy task. All you need to do is perform the following steps: Import the Tkinter module. Create the GUI application main window. Add one or more of the above-mentioned widgets to the GUI application. Enter the main event loop to take action against each event triggered by the user.

7 Example1 #!/usr/bin/python import tkinter top = tkinter.Tk() # Code to add widgets will go here... top.mainloop()

8 Example2 #!/usr/bin/python import tkinter top = tkinter.Tk() def helloCallBack(): tkinter.messagebox.showinfo( "Hello Python", "Hello World") B = tkinter.Button(top, text ="Hello", command = helloCallBack) B.pack() top.mainloop()

9 Tkinter Widgets Tkinter provides various controls, such as buttons, labels and text boxes used in a GUI application. These controls are commonly called widgets. There are currently 15 types of widgets in Tkinter. We present these widgets as well as a brief description in the following table:

10 Tkinter Widgets OperatorDescription ButtonThe Button widget is used to display buttons in your application. CanvasThe Canvas widget is used to draw shapes, such as lines, ovals, polygons and rectangles, in your application. CheckbuttonThe Checkbutton widget is used to display a number of options as checkboxes. The user can select multiple options at a time. EntryThe Entry widget is used to display a single-line text field for accepting values from a user.

11 Button The Button widget is used to add buttons in a Python application. These buttons can display text or images that convey the purpose of the buttons. You can attach a function or a method to a button which is called automatically when you click the button.

12 Syntax Here is the simple syntax to create this widget: w = Button ( master, option=value,... ) Parameters: master: This represents the parent window. options: Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.

13 Button Example Example2 shows the code for creating a Button and click it.

14 Canvas The Canvas is a rectangular area intended for drawing pictures or other complex layouts. You can place graphics, text, widgets or frames on a Canvas. Syntax Here is the simple syntax to create this widget: w = Canvas ( master, option=value,... )

15 Parameters master: This represents the parent window. options: Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.

16 Options OptionDescription bdBorder width in pixels. Default is 2. bgNormal background color. confineIf true (the default), the canvas cannot be scrolled outside of the scrollregion.

17 Example3 import tkinter top = tkinter.Tk() C = tkinter.Canvas(top, bg="blue", height=250, width=300) coord = 10, 50, 240, 210 arc = C.create_arc(coord, start=0, extent=150, fill="red") C.pack() top.mainloop()

18 CheckButton The Checkbutton widget is used to display a number of options to a user as toggle buttons. The user can then select one or more options by clicking the button corresponding to each option. You can also display images in place of text.

19 CheckButton Syntax Here is the simple syntax to create this widget: w = Checkbutton ( master, option,... ) Parameters: master: This represents the parent window. options: Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.

20 CheckButton OptionDescription activebackgroun d Background color when the checkbutton is under the cursor. activeforegroundForeground color when the checkbutton is under the cursor. bg The normal background color displayed behind the label and indicator. bitmapTo display a monochrome image on a button. bdThe size of the border around the indicator. Default is 2 pixels. ommand A procedure to be called every time the user changes the state of this checkbutton. cursor If you set this option to a cursor name (arrow, dot etc.), the mouse cursor will change to that pattern when it is over the checkbutton. disabledforegrou nd The foreground color used to render the text of a disabled checkbutton. The default is a stippled version of the default foreground color. fontThe font used for the text.

21 CheckButton Following are commonly used methods for this widget: MethodDescription deselect()Clears (turns off) the checkbutton. flash() Flashes the checkbutton a few times between its active and normal colors, but leaves it the way it started. invoke() You can call this method to get the same actions that would occur if the user clicked on the checkbutton to change its state. select()Sets (turns on) the checkbutton. toggle()Clears the checkbutton if set, sets it if cleared.

22 Example4 import tkinter top = tkinter.Tk() CheckVar1 = tkinter.IntVar() CheckVar2 = tkinter.IntVar() C1 = tkinter.Checkbutton(top, text = "Music", variable = CheckVar1, onvalue = 1, offvalue = 0, height=5, width = 20) C2 = tkinter.Checkbutton(top, text = "Video", variable = CheckVar2, onvalue = 1, offvalue = 0, height=5, width = 20) C1.pack() C2.pack() top.mainloop()

23 Entry The Entry widget is used to accept single-line text strings from a user. If you want to display multiple lines of text that can be edited, then you should use the Text widget. If you want to display one or more lines of text that cannot be modified by the user, then you should use the Label widget.

24 Entry Syntax Here is the simple syntax to create this widget: w = Entry( master, option,... ) Parameters master: This represents the parent window. options: Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.

25 Entry OptionDescription bg The normal background color displayed behind the label and indicator. bdThe size of the border around the indicator. Default is 2 pixels. command A procedure to be called every time the user changes the state of this checkbutton. cursor If you set this option to a cursor name (arrow, dot etc.), the mouse cursor will change to that pattern when it is over the checkbutton. fontThe font used for the text. exportselection By default, if you select text within an Entry widget, it is automatically exported to the clipboard. To avoid this exportation, use exportselection=0. fgThe color used to render the text. highlightcolorThe color of the focus highlight when the checkbutton has the focus. justify If the text contains multiple lines, this option controls how the text is justified: CENTER, LEFT, or RIGHT.

26 Entry Methods The following are commonly used methods for this widget:

27 Entry MedthodDescription delete ( first, last=None ) Deletes characters from the widget, starting with the one at index first, up to but not including the character at position last. If the second argument is omitted, only the single character at position first is deleted. get()Returns the entry's current text as a string. icursor ( index ) Set the insertion cursor just before the character at the given index. index ( index ) Shift the contents of the entry so that the character at the given index is the leftmost visible character. Has no effect if the text fits entirely within the entry. insert ( index, s )Inserts string s before the character at the given index. select_adjust ( index ) This method is used to make sure that the selection includes the character at the specified index.

28 Example5 Try the following for yourself: from Tkinter import * top = Tk() L1 = Label(top, text="User Name") L1.pack( side = LEFT) E1 = Entry(top, bd =5) E1.pack(side = RIGHT) top.mainloop()

29 Event driven programming Graphical interfaces can be used for input as well as output. In a GUI environment, users typically interact with their applications by clicking on buttons, choosing items from menus, and typing information into on-screen text boxes. These applications use technique called event- driven programming.

30 Event driven programming Basically, the program draws a set of interface elements (often called widgets) on the screen, and then waits for the user to do something. When the user moves the mouse, clicks a button, or types a key on a keyboard, his generates an event. Basically, an event is an object that encapsulates data about what just happened. The event object is then sent to an appropriate part of the program to be processed.

31 Events and Bindings a Tkinter application spends most of its time inside an event loop (entered via the mainloop method). Events can come from various sources, including key presses and mouse operations by the user, and redraw events from the window manager (indirectly caused by the user, in many cases).

32 Events and Bindings Tkinter provides a powerful mechanism to let you deal with events yourself. For each widget, you can bind Python functions and methods to events. widget.bind(event, handler) If an event matching the event description occurs in the widget, the given handler is called with an object describing the event. Here is an example:

33 Getting Mouse Clicks from tkinter import * top = Tk() def callback(event): print('You clicked at: ', event.x, event.y) frame = Frame(top, width=100, height=100) frame.bind(" ", callback) frame.pack() top.mainloop()

34 Getting Mouse Click In this example, we use the bind method of the frame widget to bind a callback function to an event called. Run this program and click in the window that appears. Each time you click, a message like “clicked at 44 63” is printed to the console window.

35 Getting Keyboard Events Keyboard events are sent to the widget that currently owns the keyboard focus. You can use the focus_set method to move focus to a widget: If you run this script, you’ll find that you have to click in the frame before it starts receiving any keyboard events.

36 Getting Keyboard Events from tkinter import * top = Tk() def key(event): print ("pressed", repr(event.char)) def callback(event): frame.focus_set() print("clicked at", event.x, event.y) frame = Frame(top, width=100, height=100) frame.bind(" ", key) frame.bind(" ", callback) frame.pack() top.mainloop()

37 Events Events are given as strings, using a special event syntax: The type field is the most important part of an event specifier. It specifies the kind of event that we wish to bind, and can be user actions like Button, and Key, or window manager events like Enter, Configure, and others.

38 Events The modifier and detail fields are used to give additional information, and can in many cases be left out. There are also various ways to simplify the event string; for example, to match a keyboard key, you can leave out the angle brackets and just use the key as is. Unless it is a space or an angle bracket, of course.

39 Event Formats A mouse button is pressed over the widget. Button 1 is the leftmost button, button 2 is the middle button (where available), and button 3 the rightmost button. When you press down a mouse button over a widget, Tkinter will automatically “grab” the mouse pointer, and subsequent mouse events (e.g. Motion and Release events) will then be sent to the current widget as long as the mouse button is held down, even if the mouse is moved outside the current widget.

40 Event Formats The current position of the mouse pointer (relative to the widget) is provided in the x and y members of the event object passed to the callback. You can use ButtonPress instead of Button, or even leave it out completely:,, and are all synonyms. For clarity, I prefer the syntax.

41 Event Formats The mouse is moved, with mouse button 1 being held down (use B2 for the middle button, B3 for the right button). The current position of the mouse pointer is provided in the x and y members of the event object passed to the callback. Button 1 was released. The current position of the mouse pointer is provided in the x and y members of the event object passed to the callback.

42 Events Formats Button 1 was double clicked. You can use Double or Triple as prefixes. Note that if you bind to both a single click ( ) and a double click, both bindings will be called. The mouse pointer entered the widget (this event doesn’t mean that the user pressed the Enter key!). The mouse pointer left the widget.

43 Event Formats Keyboard focus was moved to this widget, or to a child of this widget. Keyboard focus was moved from this widget to another widget. The user pressed the Enter key. You can bind to virtually all keys on the keyboard. For an ordinary 102-key PC-style keyboard, the special keys are Cancel (the Break key), BackSpace, Tab, Return(the Enter key), Shift_L (any Shift key), Control_L (any Control key), Alt_L (any Alt key), Pause, Caps_Lock, Escape, Prior (Page Up), Next (Page Down), End, Home, Left, Up, Right, Down, Print, Insert, Delete, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, Num_Lock, and Scroll_Lock.

44 Event Formats The user pressed any key. The key is provided in the char member of the event object passed to the callback (this is an empty string for special keys). a The user typed an “a”. Most printable characters can be used as is. The exceptions are space ( ) and less than ( ). Note that 1 is a keyboard binding, while is a button binding. The user pressed the Up arrow, while holding the Shift key pressed. You can use prefixes like Alt, Shift, and Control. The widget changed size (or location, on some platforms). The new size is provided in the width and height attributes of the event object passed to the callback.

45 Creating GUI using class import tkinter as tk class Application(tk.Frame): def __init__(self, master=None): tk.Frame.__init__(self, master) self.pack() self.createWidgets() def createWidgets(self): self.hi_there = tk.Button(self) self.hi_there["text"] = "Hello World\n(click me)" self.hi_there["command"] = self.say_hi self.hi_there.pack(side="top") self.QUIT = tk.Button(self, text="QUIT", fg="red", command=root.destroy) self.QUIT.pack(side="bottom") def say_hi(self): print("hi there, everyone!") root = tk.Tk() app = Application(master=root) app.mainloop()


Download ppt "WEEK 12-13 Introduction to GUI programming. Introduction Each data type can represent a certain set of values, and each had a set of associated operations."

Similar presentations


Ads by Google