Sunteți pe pagina 1din 24

GUI -Graphic User Interface in Python

Tkinter este biblioteca (pachetul) lui Python care ne pune la dispozitie


metode si functii pentru a realiza interfete grafice.
Deoarece Tkinter este destul de avansat pentru un incepator, vom lucra
cu libraria grafica graphics.py care este construita cu Tkinter.
graphics.py va va fi pusa la dispozitie de indrumatorul laboratorului si
va fi salvata fie:
- in folderul Python Lib: anaconda3/lib/python3.7.graphics.py
- fie in acelasi folder cu programul curent .
Din moment ce este o biblioteca, pentru a putea sa fie folosita in
program, trebuie importata:
>>> import graphics
>>>

1 ) Window
O fereastra grafica este un loc pe ecran unde pot fi desenate elemente
grafice.
Pentru a crea o fereastra, folosim GraphWin din graphics.

>>> win = graphics.GraphWin()


>>>
Figura 1: Fereastra Grafica

Notatia graphics.GraphWin() indica faptul ca functia


GraphWin() se gaseste in biblioteca graphics.

Functia GraphWin() creeaza o noua fereastra pe ecran.


Fereastra generata are titlul automat: Graphics Window (Figura1).

In momentul in care am apelat functia GraphWin(), am generat un


obiect (o fereastra) care apoi a fost atribuit variabilei win.
De acum, putem manipula fereastra creata prin variabila win.

In momentul in care nu mai folosim o fereastra, aceasta trebuie distrusa:


>>> win.close()
>>>

Deoarece este dificil sa folosim numele bibliotecii graphics de fiecare


data cand folosim o functie din aceasta biblioteca, atunci cand importam
bilioteca putem folosi scrierea:
>>> from graphics import *
Cuvantul cheie from ne permite sa importam anumite functii dintr-o
biblioteca.
* incarca toate functiie din acea bibloteca.

>>> from graphics import *


>>> win = GraphWin()
Observati ca acum nu mai este nevoie sa folosim numele bibliotecii
atunci cand folosim o functie care apartine bibliotecii respective.

Fereastra GraphWin este o colectie de pixeli (“picture elements”) care


are dimensiunea by default de 200x200 pixeli, adica 40,000 pixeli in
total.
Controland culoarea fiecarui pixeli, controlam ceea ce este afisat in
fereastra. Desenam in fereastra prin schimbarea culorii fiecarui pixeli
(lucru realizat automat de functiile bibliotecii graphics).

Putem schimba titlul si dimensiunea ferestrei GraphWin:


>>> win = GraphWin(“Noul nume”, latime,
inaltime)

Un program poate defini un numar nelimitat de GraphWins.

GraphWin Methods

Obiectele GraphWin au urmatoarele metode:

GraphWin(title,width,height) -Constructs new graphic


window on the screen; The parameters are optional; the default title is
"Graphics Window," and the default size is 200 x 200 pixels.

Example: win=GraphWin("Investment Growth",640,480)

plot(x,y,color) - Draws the pixel at (x, y) in the window. Color is

optional; black is the default.

Example: win.plot(35,128,”blue")

setBackground(color) - Sets the window background to the


given color. The default background color depends on your system. See
Example: win.setBackground("white")

close() - Closes the on-screen window.

Example: win.close()


getMouse() -Pauses for the user to click a mouse in the window and
returns where the mouse was clicked as a Point object.

Example: clickPoint = win.getMouse()

checkMouse() -Similar to getMouse, but does not pause for a user

click. Returns the last point where the mouse was clicked or None if the
window has not been clicked since the previous call to checkMouse or
getMouse.
Example: clickPoint=win.checkMouse()
Note: clickPoint may be None.
getKey() -Pauses for the user to type a key on the keyboard and
returns a string representing the key that was pressed.

Example: keyString=win.getKey()

checkKey()- Similar to getKey, but does not pause for the user to
press a key. Returns the last key that was pressed or " " if no key was
pressed since the previous call to checkKey or getKey. This is
particularly useful for controlling simple animation loops.

Example: keyString=win.checkKey()

Note: keyString may be the empty string " "

2) Point
Cel mai simplu obiect din biblioteca graphics este Point.
In geometrie, un punct este o pozitie in spatiu si este localizat prin
referire la un sistem de coordonate.
Obiectul nostru graphics, Point, este similar cu cel de la geometrie:
reprezinta o pozitie in fereastra GraphWin.

Definim un punct furnizand coordonatele x si y ale acestuia, (x,y):


valoarea x reprezinta pozitia orizontala a punctului, valoarea y pozitia
verticala.

In mod traditional, programele grafice localizeaza punctul (0,0) in coltul


din stanga sus al ferestrei. Pentru o fereastra de dimensiunea 200x200,
coltul cel mai din dreapta jos are coordonatele (199,199).
Desenarea unui punct seteaza culoarea pixelului corespunzator in
GraphWin. Culoarea implicita este negru.

>>> p = Point(50, 60)

>>> win = GraphWin()

>>> p.draw(win)

>>> p2 = Point(140, 100)

>>> p2.draw(win)

>>> p.getX()

50

>>> p.getY()

60
Point Methods

Point(x,y) - Constructs a point having the given coordinates.

Example: aPoint=Point(3.5,8)

getX () - Returns the x coordinate of a point.


Example: xValue=aPoint.getX()

getY( ) Returns they coordinate of a point.

Example: yValue=aPoint.getY()

3) Alte obiecte grafice


In afara de puncte, cu metodele din bilioteca graphics mai putem genera
si linii, cercuri, patrate, poligoane si chiar text.

Metodele comune tuturor obiectelor sunt:

setFill (color) -Sets the interior of the object to the given color.
Example: someObject.setFill("red")

setOutline (color) -Sets the outline of the object to the given color.
Example: someObject.setOutline("yellow")
setWidth(pixels) -Sets the width of the outline of the object to the
desired number of pixels. (Does not work for Point.)
Example: some0bject.setWidth(3)

draw(aGraphWin) -Draws the object into the given GraphWin and
returns the drawn object.

Example: someObject.draw(someGraphWin)

undraw() Undraws the object from a graphics window. If the object is


not cur rently drawn, no action is taken.
Example: someObject.undraw()

move (dx , dy) Moves the object dx units in the x direction and dy units
in the y direction. If the object is currently drawn, the image is adjusted
to the new position.
Example: some0bject.move(10,15.5)
clone() Returns a duplicate of the object. Clones are always created in an
undrawn state. Other than that, they are identical to the cloned object.

Example: objectCopy = someObject.clone ()

In afara acestor metode, liniile au cateva metode specifice:

3.1) Line Methods

Line(point1,point2) - Constructs a line segment from point1 to


point2.
Example: aLine=Line(Point(1,3),Point(7,4))

setArrow(endString) - Sets the arrowhead status of a line.


Arrows may be drawn at either the first point, the last point, or both.
Possible values of endString are "first", "last", "both", and "none". The
default set ting is "none".
Example: aLine.setArrow("both")


getCenter() - Returns a clone of the midpoint of the line segment.

Example: midPoint = aLine.getCenter()



getP1(),getP2()- Returns a clone of the corresponding endpoint
of the segment.

Example: startPoint=aLine.getP1()

3.2) Rectangle Methods

Rectangle(point1, point2) Constructs a rectangle having


opposite corners atpoint1 andpoint2.
Example: aRectangle=Rectangle(Point(1,3),Point
(4 , 7) )

getCenter() -Returns a clone of the center point of the rectangle.


Example: centerPoint=aRectangle.getCenter()

getP1(),getP2()-Returns a clone of the corresponding point used
to construct the rectangle.

Example: cornerPoint=aRectangle.getP1()

3.3) Oval Methods

Oval (point1, point2) -Constructs an oval in the bounding box


determined by point1 and point2.
Example: anOval=Oval(Point(1,2),Point(3,4))
getCenter() Returns a clone of the point at the center of the oval.
Example: centerPoint=anOval.getCenter()

getP1(),getP2() -Returns a clone of the corresponding point
used to construct the oval.

Example: cornerPoint=an0val.getP1()

3.4) Polygon Methods

Polygon(point1, point2, point3, . . .)


Constructsapolygonwiththegiven points as vertices. Also accepts a single
parameter that is a list of the vertices.
Example: aPolygon=Polygon(Point(1,2),Point(3,4) ,
Point(5,6))

Example:
aPolygon=Polygon([Point(1,2),Point(3,4),Point(5,
6)])

getPoints() Returns a list containing clones of the points used to


construct the polygon.
Example: pointList=aPolygon.getPoints()
3.5) Circle

>>> circ = Circle(Point(100, 100),30)



>>> win = GraphWin()

>>> circ.draw(win)
Pentru a desena un cerc, primul obiect pe care il cream este un punct
care reprezinta centrul cercului: Point(100, 100).
In exemplul de mai sus, cercul nostru este centrat in punctul de
coordonate (100,100)
Circle Methods

Circle(centerPoint,radius)- Constructs a circle with the


given center point and radius.
Example: aCircle=Circle(Point(3,4),10.5)

getCenter() -Returns a clone of the center point of the circle.


Example: centerPoint = aCircle.getCenter()

getRadius( )- Returns the radius of the circle.

Example: radius = aCircle.getRadius ( )


getP1(),getP2() - Returns a clone of the corresponding corner
of the circle's bounding box. These are opposite corner points of a square
that circumscribes the circle.
Example: cornerPoint=aCircle.getP1()

Exercitiul 3.5:
Implementati urmatoarul program:
>>> ### Open a graphics window
>>> win = GraphWin('Shapes')
>>> ### Draw a red circle centered at point
>>> ### (100, 100) with radius 30
>>> center = Point(100, 100)
>>> circ = Circle(center, 30)
>>> circ.setFill('red')
>>> circ.draw(win)
>>> ### Put a textual label in the center of the
circle
>>> label = Text(center, "Red Circle")
>>> label.draw(win)
>>> ### Draw a square using a Rectangle object
>>> rect = Rectangle(Point(30, 30), Point(70,
70))
>>> rect.draw(win)
>>> ### Draw a line segment using a Line object
>>> line = Line(Point(20, 30), Point(180, 165))
>>> line.draw(win)
>>> ### Draw an oval using the Oval object
>>> oval = Oval(Point(20, 150), Point(180, 199))
>>> oval.draw(win)

Output:
3.6) Text Methods

Text(anchorPoint,textString) -Constructs a text object that


displays textString centered at anchorPoint. The text is displayed
horizontally.

Example: message=Text(Point(3,4),"Hello!")

setText (string) -Sets the text of the object to string.

Example: message.setText("Goodbye!")

getText ( ) -Returns the current string.

Example: msgString=message.getText()

getAnchor ( ) Returns a clone of the anchor point.

Example: centerPoint=message.getAnchor( )


setFace(family) -Changes the font face to the given family. Possible

values are "helvetica", "courier", "times roman", and "arial".

Example: message.setFace("arial")

setTextColor(color) -Sets the color of the text to color. Note: setFill has
the same effect.

Example: message.setTextColor("pink")
setSize (point) Changes the font size to the given point size. Sizes from
5 to 36 points are legal.

Example: message.setSize(18)


setStyle (style) -Changes font to the given style. Possible values are:

"normal", "bold", "italic", and "bold italic". e

Example: message.setStyle("bold")

4) Grafica interactiva

Exercitiu 4.1
# click.py

from graphics import *
def main():

win = GraphWin("Click Me!")
for i in range(10):
p = win.getMouse()

print("You clicked at:", p.getXO, p.getY())
main()

Exercitiu 4.2
# triangle.py
# Interactive graphics program to draw a
triangle

from graphics import *

def main():
win = GraphWin("Draw a Triangle")
win.setCoords(0.0, 0.0, 10.0, 10.0)
message = Text(Point(5, 0.5), "Click on
three points")
message.draw(win)

# Get and draw three vertices of triangle


p1 = win.getMouse()
p1.draw(win)
p2 = win.getMouse()
p2.draw(win)
p3 = win.getMouse()
p3.draw(win)
# Use Polygon object to draw the triangle
triangle = Polygon(p1,p2,p3)
triangle.setFill("peachpuff")
triangle.setOutline("cyan")
triangle.draw(win)

# Wait for another click to exit


message.setText("Click anywhere to quit.")
win.getMouse()
main()

Output:

Observatii:
Nu exista o clasa triunghi. Exista in schimb clasa Polygon care accepta
un numar nelimitat de puncte si creaza un poligon folosind segmente
care conecteaza punctele intre ele, in ordinea in care sunt introduce, si
apoi conectand ultimul punct cu primul.
triangle = Polygon(p1, p2, p3)
message = Text(Point(5,0.5), "Click on
three points")

message.draw(win)
Pentru a inchide fereastra:
 message.setText("Click anywhere to quit.”
5) Obiecte de tip Entry

Obiectele de tip Entry sunt afisate niste casute in care se poate introduce
text si care pot fi editate de utilizatorul programului.

Obiectele de tip Entry suporta metodele grafice generale, move(),


draw(graphwin), undraw(), setFill(color), si
clone()la care se adauga si cateva metode specifice:

Entry(centerPoint, width) - Constructs an Entry having the given


center point and width. The width is specified in number of characters of
text that can be displayed.

Example: inputBox=Entry(Point(3,4),5)

getAnchor () - Returns a clone of the point where the entry box is


centered.

Example: centerPoint = inputBox.getAnchor ( )



getText ( ) Returns the string of text that is currently in the entry box.

Example: inputStr=inputBox.getText()


setText (string) Sets the text in the entry box to the given string.

Example: inputBox.setText(“32.0")
setFace(family) -Changes the font face to the given family. Possible
values are "helvetica", "courier", "times roman", and "arial".

Example: inputBox.setFace("courier")

setSize (point) - Changes the font size to the given point size. Sizes
from 5 to 36 points are legal.

Example: inputBox.setSize(12)


setStyle (style) - Changes font to the given style. Possible values are:

"normal", "bold", "italic", and "bold italic".

Example: inputBox.setStyle("italic")

setTextColor ( color) Sets the color of the text to color.

Example: inputBox.setTextColor("green")

Exercitiu 5.1
Realizati o interfata grafica pentru un convertor din grade Celsius in
grade Farhenheit.

# convert_gui.pyw
# Program to convert Celsius to Fahrenheit using
a simple
# graphical interface.

from graphics import *


def main():
win = GraphWin("Celsius Converter", 300,
200)
win.setCoords(0.0,0.0. 3.0, 4.0)
# Draw the interface
Text(Point(1,3),"Celsius
Temperature:").draw(win)
Text(Point(1,1),"Fahrenheit
Temperature:").draw(win)
input=Entry(Point(2,3), 5)
input.setText("0.0")
input.draw(win)
output=Text(Point(2,1),"")
output.draw(win)
button=Text(Point(1.5,2.0),"Convert It")
button.draw(win)

Rectangle(Point(1,1.5),Point(2,2.5).draw(win
)
# wait for a mouse click
win.getMouse()

# convert input
celsius = eval(input.getText())
fahrenheit = 9.0/5.0 * celsius + 32

# display output and change button


output.setText(fahrenheit)
button.setText("Quit")
# wait for click and then quit
win.getMouse()
win.close()

main()

Output:
Observatii
Metoda Entry deseneaza o cutie care contine text.
In urma executiei programului, se produce o casuta text in care se
introduce valoarea temperaturii.

Exercitii propuse

1. Modificati exercitiul 5.1 astfel incat sa obtineti outputul de mai jos:


2. Realizati o interfata care afiseaza suma a 2 numere introduse de
utilizator.

3. Realizati o interfata pentru fisa unui student. Aceasta va contine:


nume, prenume, an de studiu (toate vor fi introduse de utilizator), si
notele la 3 materii. Apoi se calcula si afisa in interfata, media
studentului.
4. Scrieti un program care permite utilizatorului sa deseneze un
dreptunghi (in urma a 2 click-uri cu mouse-ul in fereastra grafica). Apoi
programul va calcula si afisa aria si perimetrul dreptunghiului.

Se vor folosi formulele:


d x = x2 − x1
dy = y2 − y1
lumgimea = d x 2 + dy 2

5 . Aceeasi cerinta ca la 3, doar ca se va desena un triunghi (cu 3 click-


uri). Apoi programul va calcula si afisa aria triunghiului.

a+b+c
aria = s(s − a)(s − b)(s − c) unde s =
2

6. Scrieti un program care ii permite utilizatorului sa deseneze o casa


simpla folosind 5 click-uri.
Primele 2 click-uri vor fi colturile opuse ale cadrului dreptunghiular al
casei. Cel de al 3lea click indica centrul marginii superioare al unei usi
1
dreptunghiulare. Usa trebuie sa aiba o latieme totala egala cu din
5
latimea totala a casei. Partile laterale ale usii trebuie sa se extinda de la
colturile de sus pana la cadrul de jos al casei. Al 4lea clic indica centrul
unei ferestre patrat. Fereastra este jumatate din latimea usii. Ultimul
click indica varful acoperisului. Muchiile acoperisului se extind de la
varf la colturile marginii superioare a cadrului casei.

S-ar putea să vă placă și