0% found this document useful (0 votes)
22 views47 pages

App Un-3

First of all I really thankful to my Lovely Professional University because of them 1 could achieve the target. I express my sincere thanks to my project guide Mrs. Deepika Dhall who had guide to me throughout my project.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
22 views47 pages

App Un-3

First of all I really thankful to my Lovely Professional University because of them 1 could achieve the target. I express my sincere thanks to my project guide Mrs. Deepika Dhall who had guide to me throughout my project.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 47
CHAPTER 22 person who interacts with a software or application is called a ‘user’. There aze two svays for a user to interact with any application. The first way is where the user es some commands to perform the work. For example, if he wants to print a he can type PRINT command, Here the user should know the syntax and covieage of PRINT command. Only then he can interact with the application. This et Environment where the user Uses commands or characters to interact with the -Sigon is called CUI (Character User Interface|.One example for CU! is MS-DOS a ‘ing system. The disadvantage of CUI is that the user has to remember several orevinds and their usage with correct syntax. A person who does not know anything in puters ‘will find CUI very difficult, cond way to interact with an application is through graphics, pictures or images. ser need not remember any commands. He can perform the task just by vrfig on relevant images. For example, to send data to printer, the user will simply ‘ine onthe Printer image (or picture). Then he has to tell how many copies he wants and the printing will continue, This environment where the user can interact with an tppleation through graphics or images is called GUI (Graphical User Interface). One ‘tape for GUL is Windows operating system. GUI offers the following advantages: ws contents, ‘he se Here the Us Itis user-friendly. The user need not worry about any commands. Even a layman will a be able to work with the application developed using GUI. a Itadds attraction and beauty to any application by adding pictures, colors, menus, animation, etc. For example, all websites on Internet are developed using GUI to lure their visitors and improve their business. 2 tis possible to simulate the real life objects using GUI. For example, a calculator Program may actually display a real calculator on the screen. The user feels that he is interacting with a real calculator and he would be able to use it without any difficulty "special training, So, GUI eliminates the need of user training. © Scanned with OKEN Scanner 570 | Chapter 22 aphical components like push buttons, radio Q GUI helps to create gr y bot ctively. ns buttons, menus, etc. and use them effectively. Seg GUI in Python Fers tkinter module to create graphics programs, The tkinter re ae GUI. This is an interface for Python programmers that enabie ge “oot the classes of TK module of TCL/TK language. Let's see what this TCL 7K jo° 0 tug (Tool Command Language) is & powerful dynam ae langua, + Th desktop appli networking, administration, testing and mar fe open source and hence can be used by any one freely. TCL language uses TE, Itig lenguage to generate graphics. TK provides standard GUI not only for TCL Hut oot Ki many other dynamic programming languages like Python. Hence, this Tk ig ya°? Python programmers in developing GUI applications through Python's tkinter et y e Be, sultabye Ct The following are the general steps involved in basic GUI programs: 1. First of all, we should create the root window. The root window is the to, window that provides rectangular space on the screen where we can displ colors, images, components, etc. P level lay text, v In the root window, we have to allocate space for our use. This is done by cre, canvas or frame. So, canvas and frame are child windows in the root window. 3. Generally, we use canvas for displaying drawings like lines, arcs, circles, shapes, ee We use frame for the purpose of displaying components like push buttons, check buttons, menus, etc. These components are also called ‘widgets’. ating @ 4. When the user clicks on a widget like push button, we have to handle that event. It means we have to respond to the events by performing the desired tasks. Now, let’s proceed further with the top level window or root window and learn to create it. The Root Window To display the graphical output, we need space on the screen. This space that is initially allocated to every GUI program is called ‘top level window’ or ‘root window’. We can say that the root window is the highest level GUI component in any tkinter application. We can reach this root window by creating an object to Tk class. This is shown in Program |. The root window will have a title bar that contains minimize, resize and close option’: When you click on close ‘X’ option, the window will be destroyed. Pregpem Program 1: / Python program to create root window or top level window. 4 import all components from tkinter from tkinter import * ry © Scanned with OKEN Scanner Graphical User Inter ce} 571 «e and watch for any events that may take place vatgye root window oe # yeamaintoop Guus Figure 22.1: Output of Program | Program 1 can be improved to display our own title in the root window's title bar. We can also set the size of the window to something like 400 pixels X 300 pixels. It is also possible to replace the TK’s leaf image with an icon of our choice. For this, we need to use the ‘co file that contains an image. These improvements are shown in Program 2. Python program to create root window with some options. from tkinter import * # create t i root ae £9P Jevel window # set window title Foot.title"My window") # set window si ze Foot. geometry("400x300") fo set window icon F.¥m_iconbitmap¢' image. ico") roots lay window and wait for any events ot. mainToopC) © Scanned with OKEN Scanner 572 Chapter 22 | Output Aaa acumen Figure 22.2: Output of Program 2 Fonts and Colors A font represents a type of displaying letters and numbers, mentioned using a tuple that contains font family name, fnt =('Times', In tkinter, fonts are size and font style as: ~40,. "bold itali¢ underline overstrike’) Here, the font family name is ‘Times’ and font size is 40 pixels, If the size is a positive number, it indicates size in points. If the size is a ne ive number, it indicates size in Pixels. The style of the font can be ‘bold’, ‘italic’, ‘underline’, overstrike’, We can mention any one or more styles as a string. The following program is useful to know the available font families in your system. All fonts are available in tkinter font modiule inside tkinter module. Program 3: A Python program to know the available font families, from tkinter import * from tkinter import font # create root window : root = Tk() # get all the supported font families 4aSt_fonts = listCfont, families) # display them pri ntClistefonts) 4 & Scanned with OKEN Scanner Chis) Se id BS cunpeab Cen aaa een : rar a el eee ee EEN Lelie escheat eer ea RIS hey neers Conch Ke Ta Maecenas aca Ta : ke ore oN ai a ek " f Renee Eee tn uae rans Pera iment ces ersesio PEL CLS Serer ee EN a a Pa ra Perens CUT UEC te eer cea oe ee i Shae DNase ar a Spal dike en uM ere ACRetro ca SUM IN CD Rae POSE Pei Krteel TH Olarteaan a Ss TORS man ue Lic alt aaa Se 5 RAR uA el eich SR Ct ate or eR Re a aM ea Tec tere Eo rig Une Eagan ar aera TR at Bean anes Peet oa aaron gee eet Trae EM A tee LaLa sea Er eae Oo a PRN UP eNeTTaTsRe SaTrera ce cnarT aN i SCM Mn Sh CoE Mehr any tt 7c SOUR OMe ocr ca Cece Re ee oa Bra Oro ee OnE isons kin nar Hea Kerra roa SNS ac RCo SLL Ma Marae a a Part pee aC LA tect ea ert DAR RSi rr coe OU amin mera eer Neer ae Pavarerd rd HNC Teas ORO aL Sane eo tenet Figure 22.3: Output of Program 3 Colors in tkinter can be displayed directly by mentioning their names as: blue, lightblue, darkblue, red, lightred, darkred, black, white, yellow, magenta, cyan, etc. We can also specify colors using the hexadecimal numbers in the format: #rrggbb# 8 bits per color #rrrgggbbb# 12 bits per color For example, #000000 represents black and #ff0000 represents red. In the same way, £000H1000 represents puregreenand#OOffffis c yan(greenplusblue). Table 22.1 gives some standard color names: Table 22.4: Colors to be used in tkinter AliceBIue DeepPink! to LemonChiffon1 to RoyalBlue DeepPink4 LemonChiffon4 AntiqueWhite DeepSkyBlue magenta RoyalBluel to RoyalBluet AntiqueWhite1 to DeepSkyBlue! to magental salmon i tad AntiqueWhiteg DeepSkyBlue4+ tamagent “Quamarine DodgerBlue maroon salmon to salmon4 | © Scanned with OKEN Scanner 574 | Chapter 22 aquamarine! to DodgerBlue! to maroon! to | seca aquamarinet DodgerBlue¢ maroon4 azure firebrick MistyRose | sacra SeaGreeng azurel to firebrick to MistyRosel to e azuret firebrick MistyRose¢ beige gold NavajoWhite fae tanq bisque gold! to NavajoWhite1 to thistle gold4 NavajoWhitet bisquel to goldenrod OliveDrab : thistlel to bisquet oe : | thistles BlanchedAlmond goldenrod! to OliveDrab1 to tomato goldenrod4 OliveDrab4 blue gray / grey | orange | tomatol to : ze zZ tomatot BlueViolet grayO to gray100 / orangel to turquoise greyO to grey100 orange4 | biuel t0 ‘green a OrangeRed ‘turquoise! f0 blue4 turquoise? brown green! 10 OrangeRed1 to VioletRed green4 OrangeRed4 11 10 ‘brown! to GreenYellow orchid, VioletRed! brown : VioletRed# burlywood honeydew orchid! to wheat orchid4 ad © Scanned with OKEN Scanner Graphical User Interface | 575 purlywood! f0 Bone Ve ane PeachPut | wheat to purlywood4 honeydew4 Sioa Hp | wheat a a cadetBlue lotPink PeachPuffl to white PeachPuff4 CadetBluel 10 HotPink1 to ; cadetBIuet HotPink4 i chocolate IndianRed pink1 to yellowl to pink4 yellow4 r chocolatel. to IndianRed1 to © | YeiowGreen chocolates IndianRed4 | light/dark blue coral ivory plum! to light/dark cyan plum4 t corall to, ivoryi to “purple” light/dark one ios goldenrod cornsilk khaki purple! fo light/dark gray ' purplet cornsilk1 to khakil to red light/dark e comsilke4 khaki4 a tf a LavenderBlush red1 to light/dark grey 1 i red4 sranitio TavenderBlushi to | RosyBrown ght) der es salmon ¥ LavenderBlush4 De light/dark sea ‘epPink LemonChiffon. RosyBrown! to oa RosyBrown4 © Scanned with OKEN Scanner 576 | Chapter 22 Working with Containers A container is a component that is used as a place where drawin displayed. In short, a container is a space that displays the output two important containers: 88 OF Widgets oa to the user. There tn Q Canvas: This is a container that is generally used to draw sh pes like lines, curyy ares and circles, | Q Frame: This is a container that is generally used to display widgets like buttons, check buttons or menus. . After creating the root window, we have to create space, i.e. the Container in the roo, ‘window so that we can use this space for displaying any drawings or widgets, Canvas A canvas is a rectangular area which can be used for drawing pictures like lines, circles, Polygons, arcs, etc, To create a canvas, we should create an object to Canvas class as: © =iCanvas (rootybg="'blue""height=500;" widths600; cursor="penci1') Here, ‘c’ is the Canvas class object. ‘root? Tepresents background color, ‘height’ canvas in pixels. A pixel (picture ele: pictures on the monitor are compos: is the name of the parent window. and ‘width’ represent the height and width of the ment) is a minute dot with which all the text and ed. When the monitor screen resolution is 1360 X The option ‘cursor’ represents the shapes are: arrow, box_spiral, cent crosshair, diamond _cross, dot, di mouse, pencil, plus, xterm, X_cursor, Shape of the cursor in the canvas, Important cursor ‘cr_plr, circle, clock, coffee_mug, cross, cross reverse: louble_arrow, exchange, hand1, hand2, heart, leftpt question_arrow, right_ptr, star, tcross, top_side, umbrella, watch, © Scanned with OKEN Scanner Figure 22.4: The pixels and screen coordinates Colors in the canvas can be displayed directly by mentioning thelr names as: blue, lghblue, dariblue, red, lightred, darkred, black, white, yellow, magenta, cyan, ete, We can also specify colors using hexadecimal numbers in the format: #rrggbb# 8 bits per color #rergggbbb# 12 bits per color For example, #000000 represents black and #{f0000 rey presents red. In the same way, #000f1000 represents pu regreenand#00fiffis cyan(greenplusblue). Once the canvas is created, it should be added to the root wi ‘sible. This is done using the pack) method, as follows: C.packQ) After the canvas is created, we can draw any shapes on the canvas, For example, to Sreate a line, we can use create_line() method, as: 1d’ ccreatetine(50, 50, 200) '50) 200; 150) Widthedy F118" White") meseates 4 line with the connecting points (50, 50), (200, 50) and (200, 150), Svidth’ ne, The oe Width of the line, The default width is 1 pixel, il specifies the color. of the “MS create_line() method returns an identification number, To cteate an oval indow. Then only it will be |, we cay 1 in use the create_oval() method. An oval is also called ellipse, d= cer eate ai a ", out Tfnes Tree 22442904, 400) (300, widths FiM1="ye Tou 8 an oval in the rectangular area defined by the top left coordinates (100,100) ‘ower coordinates (400, 300), If the rectangle has same width and height, will become a circle. ‘width’ represents the width of the oval in pixels, ‘fill’ ‘acti e Color to fill and ‘outline’ represents the color to be used for the border, The All represents the color to be filled when the mouse is placed on the oval. bh is Creates the bottoy tthe oval "resent ion at © Scanned with OKEN Scanner i | 578 | Chapter 22 A polygon represents several points connected by either straight lines or smooth lin, create a polygon, we can use the create_polygon() method as: id= 10, 10, 200, 200,” 300, 200; width a STS eeea sencT ihe "ted", ‘smooth=1, activefi 11 €8, To Tghtblue") Here, the polygon is created using the points (10, 10), (200, 200), (300, 200) and then the last point is again connected to the first point, i.e. (10, 10). The option ‘smooth’ can become 0 or 1. If 0, it indicates a polygon with sharp edges and 1 indicates a polygon with smooth edges. Similarly, to create a rectangle or square shaped box, we can use the create_rectangle) method as: id/= ¢.create-rectangle(500;, 2005::700,"600, width=2, fi11="gray", _outline="black", activefil1="yeltow") Here, the rectangle will be formed with the top left coordinate at (500, 200) pixels and the lower bottom coordinate at (700, 600). The color of the rectangle will change from gray to yellow when the mouse is placed on the rectangle. It is also possible to display some text in the canvas. For this purpose, we should use the create_text() method as: id = C.create_text (500,100, text="My: canvas", font= fnt; FiTl="yeTlon", activefil]="green") Here, the font’ option is showing ‘int’ object that can be created as: fnt =('Times', 40,°"bold') fi ft <('Times', -40, ‘bold italic underline’) The first option Times’ represents the font family name. This can be ‘Times’, Helvetica’, ‘Courier’, etc. The second option represents a number (40) that indicates the size of the font in points. If we want to mention the size of the font in pixels, we should use minus sign before the size (-40). The third option indicates the style of the font. There are 3 styles: bold, italic and underline. We can mention any one or all the styles. If do not want any style, we need not mention this option. Whatever we discussed so far can be shown in Program4. (Program 4: A GUI program that demonstrates the creation of various shapes in canvas: from tkinter import * # create root window root = Tk() # create Canvas as a child to ro i € = Canvas (root, bg="blue", heioreaanoew. height=700, width=1200, cursor="pencil' # create a Tine in the canvas i id = c.create_line(s0, 50, 200, 50, 200, 150, widthad, fi1l="white") # create an oval in the canvas i © Scanned with OKEN Scanner > Graphical User Interface] 579 id = cvereate_ova](100, 100, 400, 300, width=s, F111 id= Cffines"red", activef{]1="green") i ate a polygon in the canvas far crereatepolygon(10, 10, 260, 200, 300, 200, widtha3, Fill="green", outline="ted", ‘smootha1, ‘activefili="11ghtblue" # create a rectangle in the canvas id= c.create-rectangle(500, 200, 700, 600, widthe2, fill="gray", outline="black", activefil1="yel low") # create some text in the canvas fnt =('Times', 40, "bold italic underline’) id = c,create_text(500, 100, text="My canvas", font= fnt, fills"yellow", activefill="green") # add canvas to the root window c.pack() # wait for any events root.mainloop() Output: ® Figure 22.5:Output of Program 4 other im Fat of 7 portant shape that we can draw in the canvas is an are, An ar ellipse or ci ; 'Pse or circle, Arcs can be created using the create_are() method as: id = ug gate,are (100, 100, 400, 300, width=3, start=270, extent#180, tline="red", style="arc") represents a 0, doo. created in the rectangular space defined by the coordinates (100, 100) Sand 0); ThE Width of the are will be 3 pixels. at an_angle 270 63), Tye teh for another 180 degrees (i.e. up to 450, “ONS outline of the arc will be in red color. ‘sty! 7, 4 © Scanned with OKEN Scanner 580 | Chapt arcs, ‘stile’ can be “pie slice” and‘chord”, Arcs drawn with these styles are shown in Figure 22.6: ~~ chord arc pie slice Figure 22.6: Different Styles of Arc As mentioned, the option ‘start’ represents an angle of the arc where it has to start and ‘extent’ represents the angle further which the arc should extend. These angles should be taken in counter clock-wise direction, taking the 3 0’ clock position as 0 degrees. Thus, the 12 0’ clock position will show 90 degrees, the 9 O’ clock will be 180 and the 6 0’ clock will represent 270 degrees. Consider Figure 22.7: > 270) Start = 270, extent = 180 start = 90, extent = 180 start = 0, extent = 180 start = 180, extent = 190 start = 90, extent = 90 Figure 22.7: Understanding Start and Extent of Ares The value of the extent should be added to the srstand where the are will atop. For exam o the starting angle so that we can unde le, id = c. creat oudsnest rede SEC¢00;,209, 800; 300, wideha3, starte90, extent=280) YAARaLS © Scanned with OKEN Scanner Graphical User Interface] 581 Here, the arc is created in the rectangular space defined by the coordinates (500, 100) 4 (800, 300). The arc starts at 90 d degrees and extends by 180 degrees. So, the arc’s ending position will be at 90+180 = 270 degrees, a Program 5: A Python program to create arcs in different shapes. from tkinter import * # create root window root = Tk() # create Canvas as a child to root wind c= Canvas(root, bg="white", heighta7005"\ width=1200) ‘ create arcs in the canvas id = c. Lt ee an 300, 409. 300, width=3, start=270, extent=180, outline="red", style="a, id=c. create_arc($00, 100, “B00, 300, width=3, start=90, extent=180, outline="red", style="ari id = c.create_arc(i00, 400, “0, 600, width=3, start=0, extent=180, outline="blue", style=" id = c.create_arc(500, 400, 805, 600, width=3, start=180, extent=180, outline="blue", style="arc) id = c.createarc(900, 400, 1200, 600, width=3 outline="black", 'style="arc") » Start=90, extent=90, # add canvas to the root c.pack() # wait for any events root.mainloop() Output: Figure 22.6: Output of Program 5 © Scanned with OKEN Scanner —= 582 | Chapter 22 We can display an image in the canvas with the help of create_image() method. Using this method, we can display the images with the formats .gif,.pgm,or-ppm. We should frst load the image into a file using Photolmage class as: FileLi=iphotormage(Files"cat.gif")# load cat-gif into filer Now, the image is available in ‘ilel’, This image can be displayed in the canvas using create_image() method as: id = cicreate-image(SQ0}/ 2005) anchor=Ne,image=fi1e1; activeimage=File2) z s Here, the image is displayed relative to the point represented by the coordinates (500, 200). The image can be placed in any direction from this point indicated by ‘anchor option. The directions are represented by actual 8 directions on the earth: NW, N, NE, E, SE, S, SW, W and CENTER. The positions of the directions are shown in Figure 22.9.4mage’ represents the image file name that should be displayed in the canvas, ‘activeimage’ represents the image file name that should be displayed when the mouse is placed on the image. Program 5 shows these concepts. Figure 22.9: Directions that ‘can be used in Anchor Option Program 6: A Python program to display images in the canvas. from tkinter import * # create root window root = Tk() # create Canvas as a child to root ¢ = Canvas(root, bg="white", netghta700>"widthe1200) # copy images into files filel = Photormage(files"cat, gif File2 = PhotormagecFi tos "puppy ote") # display the image in t 5 4 when mouse 1s "placed onecqa"Yasi” NE direction d= c.create image(spo° je, We can see puppy image sckivetmages#isesg' 200" anchofoNe, mages He” © Scanned with OKEN Scanner the Graphical User Interface] 583 fre c,create_text(500, 500, text="Thi isa thrilling photo", font= Cinelvetica’, 30,''bold'), fill="blue") ing photo", fon # add canvas to the root c.packO # wait for any events root.mainloop() ‘output: This is a thrilling photo Figure 22.10: Output of Program 6 - Program 7, we use polygon and rectangle to create a house. Then we create green shes using arcs at left and right sides of the house. A Moon image (.gif file) is shown at * top left corner and text is displayed below the house. 7: A Python program to display drawing in the canvas. from tkinter import * # create root roseeatg, ra0t window 4 Gfeate canvas as a child to root window. Background color is dark © = Canvas(root, bg="#091e42", height=700, width=1200) E,cheate the house “FETTER y90n 600,250 700,200, 800,250, 800,400,600,400, width=2, Srcreate TiZeCiOe 5sURI UME Tee > fille"red") ¢ - 1250, widthe "re Sreate_rectanglé(650,275,750,375, fiil="red") Ho Teate 3 bushes at left side of house © Scanned with OKEN Scanner 584 [Chapter22 x1,y1=0,350 x2, y2=200,450 3): Fort tentevaretkLyL.x2,y2, starte0, extent=180, F111="green") x1+=200 x2+=200 create 2 bushes at right side of house create_arc(800,350,1000,450, start-0 i extent=180, 171 c.create_arc(1000, 350,1200,450, star # , extent=180, fi11 reen™ agreen~) display Moon image em Filel = Phototnage(filen"maon. gif"). c.create_image(10, 100, anchor=Nw,’ imag ile1) # display some text below the image = id = C.create_text(600, 600, text="My Happy Home!", font= ('Helvetica' 30, "bold"), fi11="magenta") 2 # add canvas to the root c.pack() # wait for any events root. mainloop() Output: Figure 22.11: Output of Program 7 Frame A ane) ces C crnvas that represents a rectangular area where some text oF splayed. Our root window is i create an object of Frame class as: sin ashe Game, Ta create fame, we oe f= Frame(root, height=400, widtha500, bge" peer n the object of Frame class, The frame is created as a child of ‘root’ window. The tions ; igh i ‘width’ represent the height and width of the frame’ in pixels. ‘be’ represents the back ground color to be displayed and ‘cursor’ indicates the type of the cursor to be displayed in the frame. mr ineeeanes BE OP "yellow", cursors" © Scanned with OKEN Scanner Graphical User Interface once the frame is created, it should be added to the root window using the pack() method os fallows fipackQ, Program 8: A GUI program to display a frame in the root window. fron tkinter “iniport * # create root window Foot = TKC # oive.a title for root window root.titlec"My Frame"). # create a frame as child to root window # cpeare(root, height=400, width=500, bg="yellow", cursor="cross") # attach the frame to root window f.pack() # let the root window wait for any events root.mainloop() Output: Figure 22.12: Output of Program 8 Widgets perform a task as button is a widget Widget devine @ GUL component that is displayed on the soreen and cal ted IP play’ n object cP Satis gout User. We create widgets as objects. For example, a push button © ing but an object of Button class. Similarly, label is a widget that is ~~ : © Scanned with OKEN Scanner ON 586 | Chapter 22 Of Label class, Once a widget is created, it should be added to canvas or frame, The following are important widgets in Python: SF Button J label 2 Message OA Text A. Scrollbar @ Checkbutton # Radiobutton Entry 4 Spinbox A. Listbox a Menu, In general, working with widgets takes the following four steps: Create the widgets that are needed in the is represented as an object of a class. For represented as Button class object. program. A widget is a GUI component that example, a push button is a widget that is As an example, Button class as: bo= ButtonCfy tex Here, f is Frame object to which the button displayed on the button, Suppose we want to create a push button, we can create an object to is added. ‘My Button’ is the text that is When the user interacts with a widget, he will generate an event. For example, clicking on a push button is an event. Such events should be handled by writing functions or routines. These functions are called in response to the events. Hence ee —_——= i‘“‘é$R9RARA ,)@EF sh, hr Pressing the Enter button, right clicking the mouse button, etc. As an example, let's write a function that def buttonclick(self); print(*You have clicked me') 3. When the user clicks on the push button, t the ‘callback handler’ function.Then only performing some task. may be called in response to button click. hat ‘clicking’ event should be linked with the button widget will appear as if it is As an example, let’s bind the button click wi ith the function as: b.bind('", buttonclick) © Scanned with OKEN Scanner Here, ‘b’ represents the push button. indicates the left mouse button, when the user presses the left mouse button, the ‘buttonClick’ function is called as fe are linked by bind() method in the preceding code. thes: ‘the preceding 3 steps make the widgets ready for the user, Now, the user has to interact with the widgets. This is done by entering text from the keyboard or pressing mouse button. These are called events. These events are continuously monitored by our program with the help of a loop, called ‘event loop’. ‘As an example, we can use the mainloop() method that waits and processes the events as: root.mainloop@ Here, ‘root’ is the object of root window in Python GUI. The events in root window are continuously observed by the mainloop() method, It means clicking the mouse or pressing a button on the keyboard are accepted by mainloop() and then the mainloop() falls the corresponding even handler function. ‘The preceding steps will become clearer once we get into the actual programming, Hence, let’s proceed further to create a push button widget and handle the event generated by the user when the button is clicked. Button Widget A push button is a component that performs some action when clicked. These buttons are created as objects of Button class as: bes bytton(f, texte'my sutton’) width=15; heighte2) bos! yellow | fg='blue', activebackground="green’, activeforeground='red!) Here, ‘b’ is the object of Button class. ‘f represents the frame for which the button is created as a child. It means the button is shown in the frame. The ‘text’ option represents the text to be displayed on the button. ‘width’ represents the width of the button in characters. If an image is displayed on the button instead of text, then ‘width’ represents the width in pixels. ‘height’ represents the height of the button in textual lines. If an image is displayed on the button, then ‘height’ represents the height of the button in Pixels, ‘bg’ represents the foreground color and ‘fg’ represents the back ground color of the button. ‘activebackground’ represents the background color when the button is es Similarly, ‘activeforeground’ represents the foreground color when the button is licked, Weean also display an image on the button as: # first load the image into file filel = Phototmagecti 1e=" cat.gif") f create a push button with image st b = 'puttoncPy Ymagesti lel, widthe150, height=100, bgs'yel ow, fge'blue! | aceivebackground='green', activeforeground=" red") a © Scanned with OKEN Scanner os In the preceding statement, observe that the width and height of the 4 588 | Chapter 22 Utton mentioned in pixels. os In Program 9, we create a frame first and then create a push button with some and add the button to the frame. Then we link the mouse left button mith ee buttonClick() method using bind() method as: the b.bind(' <8utton=15", buttonclick) Here, represents the mouse left button that is linked withbuttonoy eg method. It means when the mouse left button is clicked, the buttonClickt) methog called. This method is called event handler. is In the place of , we can also use . In this case, mouse mide button is linked with the event handler method. The middle button is not found in most of the mouses now-a-days. represents the mouse right button. similar, represents that the event handler method should be executed when the mouse pointer is placed on the push button. Program 9: A Python program to create a push button and bind it with an event handler function. from.tkinter import * # method to_be called when the button is clicked def buttonclick(self): print('You have clicked me') # create root window root = TkO # create frame as child to root window ¥ = Frame(root, height=200, width=300) # let the frame will not shrink #.propagate(0) # attach the frame to root wi FpackO ndow # create a push button as child to frame , b = Button(f, text="My Button’, width=15, height=2, bg-"yel]ow, 1, fg='blue', activebackground="green', activeforeground='r‘ # attach button to the frame 2 Bind the tert led ‘ind ‘the left mouse button with be calle b.bind(" © Scanned with OKEN Scanner 92 | Chapter 22 Output: Figure 22.14: Output of Program I! Arranging Widgets in the Frame Once we create widgets or components, we can arrange them in the frame in a particular manner. Arranging the widgets in the frame is called ‘layout management’. There ar three types of layout managers. Q Pack layout manager Q Grid layout manager Q Place layout manager We will discuss about these layout managers one by one. Pack layout manager USS pack() method. This method is useful to associate a widget with its parent component Whife using the pack() method, we can mention the position of the widget using ‘fl! ‘side’ options. b. pack¢fi11=x) Bibackerit avs The fill’ option can take the values: X,Y, BOTH, NONE, The value X represents that tt widget should occupy the frame horizontally and the value Y represents that the #8 © Scanned with OKEN Scanner yr pul 0COOPY vertically. BOTH represents th Sections. NONE represents that the widget See ieee ce aie is NONE: Alone with ‘fll’ option, we can use ‘padx’ and ee eee vee much space ‘Should be left around the component hi eee ire oe jrizontally and vertically. For spspocectl ie ce yeaxis 15, DX 10 PRCA T =x, padk= = pate te jade pady-1S)# occupy horizontally. Space on x- bsteck 4 occupy horizontally. No space’ outsid i p occupy horizontally. No. space peg de ee Widhet ‘re output in this case is shown in Figure 22.15: Graphical User Interface} 593 jadx=10 z > pady215)# occupy’ vertically: ‘space on x-axis Blue Yellow vons using pack() method wi ch is used to Pl P or BOTTOM. 7! ith ‘fill’ option lace the widgets side the default value is . Figure 22.15: Arrangement of but ee es can take another option ‘side’ whi Toa le. ‘side’ can take the values ‘LEFT, RIGHT, TO! For example, 15)# align towards left w bi.pack(sidesLErT; padx=10, pady= un x aces 1 ba pated padeet0, pady=15)# ali ¢ with 0 PX space ith 10 px gn towards Jeft with 10px and around the #15 px spaces - 03 pack sfdecnictT)# align towards righ Beer with 0 px space around the widget b4.packQ# align towards tol ~ — © Scanned with OKEN Scanner a 594 | Chapter 22 ‘The preceding statements will produce the following output, as shown in Figure 22.16; Figure 22.16: Arrangement of buttons using pack() method with ‘side’ option Grid layout manager uses the grid() method to arrange the widgets in a two dimensional table that contains rows and columns. We know that the horizontal arrangement of data is called ‘row’ and vertical arrangement is called ‘column’. The Position of a widget is defined by a row and a column number. The size of the table is determined by the grid layout manager depending on the widgets size. as = = . & EUR CEy Pe Ue SNe PEaaEL DY Pady=15)# display in Oth row, 0" b2.grid(row=0, column=1, padx=10, i i is . # column with spaces’ around” P*/-159# display in 0% row - b3.gridCrow=0, ‘colunn=2)# display in Om row, 2n4 column without spaces b Sorid Cron column=3)# display in ast row, 3r4 column without spaces The preceding statements will produce wn in Figure 22.17: the following output, as sho Figure 22.17: Arrangement of buttons using grid() method © Scanned with OKEN Scanner — Graphical User Interface] 595 ce Iayout manager uses the place() method to arrange the widgets. The place() method Phat sx and y coordinates of the widget along with width and height of the window where widget has to be displayed. For example, dl ce(x=20, y=30,, width=100, height=50)# display at (20, 30) mPa ecoranates. in the: wivctow Ger eo and $0 Pxheghe wa.place(x=20, y=i00, widthe100, height=50)# display at. (£0, 100) p3:place(x=200, y=100, width=100, helghe-s0)4 display’ at (200, 100) b4cplace(x=200, Y=200, width=100, height=30)# display at ¢200; 1003 ‘The preceding statements will produce the following output, shown in Figure 22.18: Red Green, Blue Yelow , Figure 22.18: Arrangement of buttons using the place() method Label Widget Alabel represents constant text that is displayed in the frame or container. A label can display one or more lines of text that cannot be modified. A label is created as an object fLabel class as: 1b] = Label(f, texts"welcome to Python", width=20, height=2, , font=('Courier', -30, ‘bold underline "), fg='blue', bg="yellow') cma fePtesents the frame object to which the label is created as a child. ‘text’ cnt the text to be displayed. ‘width’ represents the width of the label in number of = and ‘height’ represents the height of the label in number of lines. font’ forepa'® @ tuple that contains font name, size and style. ‘fg’ and ‘bg’ represents the Sound and background colors for the text, hh Pry butter" 12, we are creating two push buttons, We display ‘Click Me’ on the first lebe ig When this button is clicked, we will display a label “Welcome to Python”, This created in the event handler method buttonClick() that is bound to the first a © Scanned with OKEN Scanner 596 | Chapter 22 button, We display another button ‘Close that will close the root window upon clicking ‘The close button can be created as: / = bz = sutton(f, texts!close', width=15, ‘height=2, option that is set to ‘quit’. This represents closing of th, + Command=quit) Please observe the ‘command’ root window. Program 12: A Python program to display a label upon clicking a push button. from tkinter import * class MyButtons: bef inte. (self, root) lef _init_(self, 3 : F create a frame as child to root window Aclf.t = FraneCroot, height=350, width=500) # Jet the frame will not shrink self. f. propagate(0) # attach the frame to root window co self. #.packO # create a push button and bind it to buttonclick method self.bl = Button(self.f, text='Click Me', width=15, height=2, command=self.buttonclick) # create another button that closes the root window upon # clicking self.b2 Fuyrontself-£, text='Close', width=15, height=2, ui # attach buttons to the frame self.b1.grid(row=0, column=1) self.b2.grid¢ron-0; column=2) # the event handler method def, buttonclick(sel4): # create a label with some text self.1bl = tabel(self.f, text="welcome to python", width=20,, height=2, font=('Courier", -30, ‘bold underline fo="blue") # attach the label in the fra self.1b1.grid(row=2, columncd) # create root window root = Tk() # create an object to mya mb = MyButtons(root) “YouttOnS class # the root wi + Poot maimloo (oot handles the mouse click event © Scanned with OKEN Scanner Graphical User Interface] 597 output: ick Me Welcome to Python Figure 22.19: Output of Program 12 Message Widget A message is similar to a label, But messages are generally used to display multiple lines oftext where as a label is used to display a single line of text. All the t. text in the message vill be displayed using the same font. To cfeate a message, we need to create an object of Message class as: m = Message(f, text='This isa message that ‘has more than one-line of text.', width=200, font=C'Roman’, 20, ‘bold italic’), f goldenrod') : 2 Here, ‘text’ represents the text to be displayed in the message. The ‘width’ option specifies the message width in pixels. ‘font’ represents the font for the message. We can use options ‘ig’ for specifying foreground color and ‘bg’ for specifying background color for the message text. Program 13: A Python program to display a message in the frame. from tkinter import * class MyMessage: # constructor def _init_(self, root): # Create a frame as child to root window self.f = Frame(root, height=350, width=500) # Jet the frame will not shrink self.f.propagate(0) # attach the frame to root window self.f.packQ) # oifea idget with some text eve tessagetselt text='this is a message that hs rere than one line of text. width=200, font=('Roman', 20, ‘bo italic’), fg='dark goldenrod') # attach Message to the frame self.m.pack(side=LerT) # Create root wi ndow > © Scanned with OKEN Scanner os 598 | chapter 22 root = TKO # create an oh ace to MyMessage class mb = MyMessage(root) # the root window handles the mouse click. event Toot.mainloopO zs Output: This is a message that Aas more than one line of text. Figure 22.20: Output of Program 13 Text Widget Text widget is same as a label or message, But Text widget has several optiot display multiple lines of text in different colors and fonts. It is possible to inser a Text widget, modify it or delete it. We can also display images in the Text Wi can create a Text widget by creating an object to Text class as: a — | at 2 *pold")s FoSPSGSE, Bobet Braptasnen veranes M Here, t’ represents the object of Text class. ‘root’ represents an object of root ee frame. ‘width’ represents the width of the Text widget in characters. ‘height 1°E° ine the height of the widget in lines, The option ‘wrap’ specifies where to CU TT cer wrap=CHAR represents that any line that is too long will be broken at afY © jne wrap-WORD will break the line in the widget after the last word that fits ata sero wrap=NONE will not wrap the lines. In this case, it is better to provide a hori70 bar to view the lines properly in the Text widget. © Scanned with OKEN Scanner ns and ca at text into idget. OT

You might also like