Vous êtes sur la page 1sur 50

Interface graphique avec Python

Bibliotheques graphiques libres


wxPython pour wxWidgets

PyGTK pour GTK+

PyQt pour Qt

Tkinter pour Tk
Premiere interface

#!/usr/bin/env python3
from tkinter import *

fenetre = Tk()

texte = Label(fenetre, text="Hello World")


texte.pack()

fenetre.mainloop()
Premiere interface

#!/usr/bin/env python3 Importe la librairie qui contient ‘tous’


les elements d’une interface graphique
from tkinter import *

fenetre = Tk() Appelle et cree l’interface graphique VIDE

texte = Label(fenetre, text="Hello World")


texte.pack()

fenetre.mainloop()
Premiere interface

#!/usr/bin/env python3
from tkinter import *
Cree un texte non modifiable
qui sera rattache a l’interface graphique
nommee ‘fenetre’
fenetre = Tk()

texte = Label(fenetre, text="Hello World")


texte.pack()
Rend visible le texte

fenetre.mainloop()
Premiere interface

#!/usr/bin/env python3
from tkinter import *

fenetre = Tk()

texte = Label(fenetre, text="Hello World")


texte.pack()

Cree une boucle infinie (obligatoire)


qui affiche l’interface tant qu’une commande
fenetre.mainloop() ne ferme pas l’interface
Les Boutons

● Bouton1 = Button(fenetre, text = 'Quitter', command = fenetre.destroy)


Options d’un bouton:
– command : lance une commande interface ou une fonction
– activebackground : change la couleur du bouton quand on passe la souris
– bd : la taille de la bordure du bouton
– image : une image peut remplacer le texte
– height, width : hauteur et largeur du bouton
– …
Interaction entre les elements de l’interface
#!/usr/bin/env python3

from tkinter import *

from random import *

def NouveauLance():

nb = randint(1,6)

Texte.set('Résultat -> ' + str(nb))

Mafenetre = Tk()

Mafenetre.title('De à 6 faces')

BoutonLancer = Button(Mafenetre, text ='Lancer', command = NouveauLance)

BoutonLancer.pack()

BoutonQuitter = Button(Mafenetre, text ='Quitter', command = Mafenetre.destroy)

BoutonQuitter.pack()

Texte = StringVar()

NouveauLance()

LabelResultat = Label(Mafenetre, textvariable = Texte, fg ='red', bg ='white')

LabelResultat.pack()

Mafenetre.mainloop()
Interaction entre les elements de l’interface
#!/usr/bin/env python3

from tkinter import *


Importation des librairies

from random import *

def NouveauLance():
Fonction qui choisi un chiffre aleatoire
nb = randint(1,6) Sauvegarde le resultat
Texte.set('Résultat -> ' + str(nb))
dans un label de l’interface

Mafenetre = Tk()

Mafenetre.title('De à 6 faces')

BoutonLancer = Button(Mafenetre, text ='Lancer', command = NouveauLance)

BoutonLancer.pack()

BoutonQuitter = Button(Mafenetre, text ='Quitter', command = Mafenetre.destroy)

BoutonQuitter.pack()

Texte = StringVar()

NouveauLance()

LabelResultat = Label(Mafenetre, textvariable = Texte, fg ='red', bg ='white')

LabelResultat.pack()

Mafenetre.mainloop()
Interaction entre les elements de l’interface
#!/usr/bin/env python3

from tkinter import *

from random import *

def NouveauLance():
Creation de la fenetre avec son titre
nb = randint(1,6)

Texte.set('Résultat -> ' + str(nb))

Mafenetre = Tk()

Mafenetre.title('De à 6 faces')

BoutonLancer = Button(Mafenetre, text ='Lancer', command = NouveauLance)

BoutonLancer.pack()

BoutonQuitter = Button(Mafenetre, text ='Quitter', command = Mafenetre.destroy)

BoutonQuitter.pack()

Texte = StringVar()

NouveauLance()

LabelResultat = Label(Mafenetre, textvariable = Texte, fg ='red', bg ='white')

LabelResultat.pack()

Mafenetre.mainloop()
Interaction entre les elements de l’interface
#!/usr/bin/env python3

from tkinter import *

from random import *

def NouveauLance():

nb = randint(1,6)

Texte.set('Résultat -> ' + str(nb))

Mafenetre = Tk() Creation de 2 boutons

Mafenetre.title('De à 6 faces')

BoutonLancer = Button(Mafenetre, text ='Lancer', command = NouveauLance)

BoutonLancer.pack()

BoutonQuitter = Button(Mafenetre, text ='Quitter', command = Mafenetre.destroy)

BoutonQuitter.pack()

Texte = StringVar()

NouveauLance()

LabelResultat = Label(Mafenetre, textvariable = Texte, fg ='red', bg ='white')

LabelResultat.pack()

Mafenetre.mainloop()
Interaction entre les elements de l’interface
#!/usr/bin/env python3

from tkinter import *

from random import *

def NouveauLance():

nb = randint(1,6)
Commande creee par le programmeur
Texte.set('Résultat -> ' + str(nb))

Mafenetre = Tk()

Mafenetre.title('De à 6 faces')

BoutonLancer = Button(Mafenetre, text ='Lancer', command = NouveauLance)

BoutonLancer.pack()

BoutonQuitter = Button(Mafenetre, text ='Quitter', command = Mafenetre.destroy)

BoutonQuitter.pack()

Texte = StringVar()
Commande interface existante
NouveauLance()

LabelResultat = Label(Mafenetre, textvariable = Texte, fg ='red', bg ='white')

LabelResultat.pack()

Mafenetre.mainloop()
Interaction entre les elements de l’interface
#!/usr/bin/env python3

from tkinter import *

from random import *

def NouveauLance():

nb = randint(1,6)

Texte.set('Résultat -> ' + str(nb))

Mafenetre = Tk()

Mafenetre.title('De à 6 faces')

BoutonLancer = Button(Mafenetre, text ='Lancer', command = NouveauLance)

BoutonLancer.pack()

BoutonQuitter = Button(Mafenetre, text ='Quitter', command = Mafenetre.destroy)

BoutonQuitter.pack()

Texte = StringVar()
Cree la chaine de caractere qui contient les resulats du de
NouveauLance() Lance la fonction 1 fois avant l’affichage
LabelResultat = Label(Mafenetre, textvariable = Texte, fg ='red', bg ='white')

LabelResultat.pack()

Mafenetre.mainloop()
Interaction entre les elements de l’interface
#!/usr/bin/env python3

from tkinter import *

from random import *

def NouveauLance():

nb = randint(1,6)

Texte.set('Résultat -> ' + str(nb))

Mafenetre = Tk()

Mafenetre.title('De à 6 faces')

BoutonLancer = Button(Mafenetre, text ='Lancer', command = NouveauLance)

BoutonLancer.pack()

BoutonQuitter = Button(Mafenetre, text ='Quitter', command = Mafenetre.destroy)

BoutonQuitter.pack()

Texte = StringVar() Indique a l’interface que le texte est modifiable


NouveauLance()

LabelResultat = Label(Mafenetre, textvariable = Texte, fg ='red', bg ='white')

LabelResultat.pack()

Mafenetre.mainloop()
Radiobutton

Radiobutton permet de faire un choix unique parmi N possibilites
● value = StringVar()
● bouton1 = Radiobutton(Mafenetre, text="Oui", variable=value, value=1)
● bouton2 = Radiobutton(Mafenetre, text="Non", variable=value, value=2)
● bouton1.pack()
● bouton2.pack()


variable = ‘’ : permet de relier les radiobuttons entre eux


Options du Radiobutton:
– textvariable : permet d’afficher un texte lie a une variable
– relief : ajoute du relief au bouton (par defaut FLAT)
– activebackground, activeforeground, ...
Listebox

Cree une liste dont on choisit 1 (defaut) ou plusieurs elements
● liste = Listbox(Mafenetre)
● liste.insert(1, "Python")
● liste.insert(2, "PHP")
● liste.insert(3, "jQuery")


Options d’une Listebox:
– cursor : change le curseur de la souris quand il est sur la liste
– font : police de caractere de votre liste
– Selectmode : choisit le mode de selection de la liste

BROWSE : 1 seul choix, par defaut

MULTIPLE : plusieurs choix

...

– bg, bd ...
Menu d’une interface
Cree un menu lie a l’interface


menubar = Menu(Mafenetre)

menu1 = Menu(menubar)

menu1.add_command(label="Créer", command=alert)

menu1.add_separator()

menu1.add_command(label="Quitter", command=Mafenetre.quit)

menubar.add_cascade(label="Fichier", menu=menu1)

Mafenetre.config(menu = menubar)

Affiche le menu dans l’interface


Menu d’une interface

Cree un menu au sens ‘utilisateur’



menubar = Menu(Mafenetre)

menu1 = Menu(menubar)

menu1.add_command(label="Créer", command=alert)

menu1.add_separator()

menu1.add_command(label="Quitter", command=Mafenetre.quit)

menubar.add_cascade(label="Fichier", menu=menu1)

Mafenetre.config(menu = menubar)

Donne un nom au menu ‘utilisatueur


Ce menu est directement ‘dessous’ le menu ‘menubar’
Menu d’une interface

Cree une fonction du menu avec :


Un nom et une commande

menubar = Menu(Mafenetre)

menu1 = Menu(menubar)

menu1.add_command(label="Créer", command=alert)

menu1.add_separator()

menu1.add_command(label="Quitter", command=Mafenetre.quit)

menubar.add_cascade(label="Fichier", menu=menu1)

Mafenetre.config(menu = menubar)
Menu d’une interface


menubar = Menu(Mafenetre)

menu1 = Menu(menubar)

menu1.add_command(label="Créer", command=alert)

menu1.add_separator() Ajouter une ligne de separation entre 2 noms

menu1.add_command(label="Quitter", command=Mafenetre.quit)

menubar.add_cascade(label="Fichier", menu=menu1)

Mafenetre.config(menu = menubar)
Menu d’une interface
On peut inserer une image, un radiobutton, un checkbutton, …
Changer la forme de la souris, de la police de caractere ...


menubar = Menu(Mafenetre)

menu1 = Menu(menubar)

menu1.add_command(label="Créer", command=alert)

menu1.add_separator()

menu1.add_command(label="Quitter", command=Mafenetre.quit)

menubar.add_cascade(label="Fichier", menu=menu1)

Mafenetre.config(menu = menubar)
Menu d’une interface


menubar = Menu(Mafenetre)

menu1 = Menu(menubar)

menu1.add_command(label="Créer", command=alert)

menu1.add_separator()

menu1.add_command(label="Quitter", command=Mafenetre.quit)

menubar.add_cascade(label="Fichier", menu=menu1)

Mafenetre.config(menu = menubar)
Fenetres pop-up

● from tkinter.messagebox import *

● showinfo(“title”, “message”) : pop-up affchant le message


● showwarning() : pop-up affchant le message, avec une icone
● showerror () : pop-up affchant le message, avec une icone

...
Canvas : Dessiner dans une interface
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from tkinter import *

# Tcl/Tk interpreter + main window (implicit)


Mafenetre = Tk()
Mafenetre.rowconfigure(0, weight=1)
Mafenetre.columnconfigure(0, weight=1)

# canvas + scrollbars frame container


cframe = Frame(Mafenetre)
cframe.rowconfigure(0, weight=1)
cframe.columnconfigure(0, weight=1)
cframe.grid(row=0, column=0, sticky="nsew")

# canvas
Canevas = Canvas(cframe, width=450, height=350, bg='white')
Canevas.create_line((10,10), (50,50), (10, 50), width=2)
Canevas.create_rectangle((100,100), (150,250), fill='red', width=4, outline='green')
Canevas.create_oval((400,10), (250,150), width=2, outline='blue')
Canevas.create_text(550,310, fill="darkblue", font="Times 12 italic", text="Click the bubbles")
Canevas.grid()

# horizontal scrollbar
hbar = Scrollbar(cframe, orient=HORIZONTAL)
hbar.grid(row=1, column=0, sticky="nsew")

# vertical scrollbar
vbar = Scrollbar(cframe, orient=VERTICAL)
vbar.grid(row=0, column=1, sticky="nsew")

# connecting items...
Canevas.configure(xscrollcommand=hbar.set, yscrollcommand=vbar.set, scrollregion=(0, 0, 800, 600) )
hbar.configure(command=Canevas.xview)
vbar.configure(command=Canevas.yview)

# launching events main loop


Mafenetre.mainloop()
Canvas : Dessiner dans une interface
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from tkinter import * Creation de l’interface et du
# Tcl/Tk interpreter + main window (implicit) Gestionnaire de position des objets
Mafenetre = Tk()
Mafenetre.rowconfigure(0, weight=1)
Mafenetre.columnconfigure(0, weight=1)

# canvas + scrollbars frame container


cframe = Frame(Mafenetre)
cframe.rowconfigure(0, weight=1)
cframe.columnconfigure(0, weight=1)
cframe.grid(row=0, column=0, sticky="nsew")

# canvas
Canevas = Canvas(cframe, width=450, height=350, bg='white')
Canevas.create_line((10,10), (50,50), (10, 50), width=2)
Canevas.create_rectangle((100,100), (150,250), fill='red', width=4, outline='green')
Canevas.create_oval((400,10), (250,150), width=2, outline='blue')
Canevas.create_text(550,310, fill="darkblue", font="Times 12 italic", text="Click the bubbles")
Canevas.grid()

# horizontal scrollbar
hbar = Scrollbar(cframe, orient=HORIZONTAL)
hbar.grid(row=1, column=0, sticky="nsew")

# vertical scrollbar
vbar = Scrollbar(cframe, orient=VERTICAL)
vbar.grid(row=0, column=1, sticky="nsew")

# connecting items...
Canevas.configure(xscrollcommand=hbar.set, yscrollcommand=vbar.set, scrollregion=(0, 0, 800, 600) )
hbar.configure(command=Canevas.xview)
vbar.configure(command=Canevas.yview)

# launching events main loop


Mafenetre.mainloop()
Canvas : Dessiner dans une interface
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from tkinter import *

# Tcl/Tk interpreter + main window (implicit)


Mafenetre = Tk()
Mafenetre.rowconfigure(0, weight=1)
Mafenetre.columnconfigure(0, weight=1) Creation d’un frame qui va contenir :
# canvas + scrollbars frame container Scrollbars et Canvas
cframe = Frame(Mafenetre)
cframe.rowconfigure(0, weight=1)
Gestionnaire de position
cframe.columnconfigure(0, weight=1)
cframe.grid(row=0, column=0, sticky="nsew")

# canvas
Canevas = Canvas(cframe, width=450, height=350, bg='white')
Canevas.create_line((10,10), (50,50), (10, 50), width=2)
Canevas.create_rectangle((100,100), (150,250), fill='red', width=4, outline='green')
Canevas.create_oval((400,10), (250,150), width=2, outline='blue')
Canevas.create_text(550,310, fill="darkblue", font="Times 12 italic", text="Click the bubbles")
Canevas.grid()

# horizontal scrollbar
hbar = Scrollbar(cframe, orient=HORIZONTAL)
hbar.grid(row=1, column=0, sticky="nsew")

# vertical scrollbar
vbar = Scrollbar(cframe, orient=VERTICAL)
vbar.grid(row=0, column=1, sticky="nsew")

# connecting items...
Canevas.configure(xscrollcommand=hbar.set, yscrollcommand=vbar.set, scrollregion=(0, 0, 800, 600) )
hbar.configure(command=Canevas.xview)
vbar.configure(command=Canevas.yview)

# launching events main loop


Mafenetre.mainloop()
Canvas : Dessiner dans une interface
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from tkinter import *

# Tcl/Tk interpreter + main window (implicit)


Mafenetre = Tk()
Mafenetre.rowconfigure(0, weight=1)
Mafenetre.columnconfigure(0, weight=1)

# canvas + scrollbars frame container


cframe = Frame(Mafenetre)
cframe.rowconfigure(0, weight=1)
cframe.columnconfigure(0, weight=1)
cframe.grid(row=0, column=0, sticky="nsew")

# canvas
Canevas = Canvas(cframe, width=450, height=350, bg='white')
Canevas.create_line((10,10), (50,50), (10, 50), width=2)
Canevas.create_rectangle((100,100), (150,250), fill='red', width=4, outline='green')
Canevas.create_oval((400,10), (250,150), width=2, outline='blue')
Canevas.create_text(550,310, fill="darkblue", font="Times 12 italic", text="Click the bubbles")
Canevas.grid()

# horizontal scrollbar
hbar = Scrollbar(cframe, orient=HORIZONTAL) Creation des scrollbars
hbar.grid(row=1, column=0, sticky="nsew")
Positionnement en bas du scrollbar horizontal
# vertical scrollbar
vbar = Scrollbar(cframe, orient=VERTICAL)
Positionnement a droite du scrollbar vertical
vbar.grid(row=0, column=1, sticky="nsew")

# connecting items...
Canevas.configure(xscrollcommand=hbar.set, yscrollcommand=vbar.set, scrollregion=(0, 0, 800, 600) )
hbar.configure(command=Canevas.xview)
vbar.configure(command=Canevas.yview)

# launching events main loop


Mafenetre.mainloop()
Canvas : Dessiner dans une interface
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from tkinter import *

# Tcl/Tk interpreter + main window (implicit)


Mafenetre = Tk()
Mafenetre.rowconfigure(0, weight=1)
Mafenetre.columnconfigure(0, weight=1)

# canvas + scrollbars frame container


cframe = Frame(Mafenetre)
cframe.rowconfigure(0, weight=1)
cframe.columnconfigure(0, weight=1)
cframe.grid(row=0, column=0, sticky="nsew")

# canvas
Canevas = Canvas(cframe, width=450, height=350, bg='white')
Canevas.create_line((10,10), (50,50), (10, 50), width=2)
Canevas.create_rectangle((100,100), (150,250), fill='red', width=4, outline='green')
Canevas.create_oval((400,10), (250,150), width=2, outline='blue')
Canevas.create_text(550,310, fill="darkblue", font="Times 12 italic", text="Click the bubbles")
Canevas.grid()

# horizontal scrollbar
hbar = Scrollbar(cframe, orient=HORIZONTAL) Creation du canvas
hbar.grid(row=1, column=0, sticky="nsew")
Taille affiche du canvas
# vertical scrollbar
vbar = Scrollbar(cframe, orient=VERTICAL)
vbar.grid(row=0, column=1, sticky="nsew")

# connecting items...
Canevas.configure(xscrollcommand=hbar.set, yscrollcommand=vbar.set, scrollregion=(0, 0, 800, 600) )
hbar.configure(command=Canevas.xview)
vbar.configure(command=Canevas.yview)

# launching events main loop


Mafenetre.mainloop()
Canvas : Dessiner dans une interface
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from tkinter import *

# Tcl/Tk interpreter + main window (implicit) Creation de 2 lignes (3 points) dans le canvas
Mafenetre = Tk()
Mafenetre.rowconfigure(0, weight=1)
Mafenetre.columnconfigure(0, weight=1)

# canvas + scrollbars frame container


cframe = Frame(Mafenetre)
Creation d’un rectangle (carre)
cframe.rowconfigure(0, weight=1)
cframe.columnconfigure(0, weight=1)
cframe.grid(row=0, column=0, sticky="nsew")

# canvas
Canevas = Canvas(cframe, width=450, height=350, bg='white')
Canevas.create_line((10,10), (50,50), (10, 50), width=2)
Canevas.create_rectangle((100,100), (150,250), fill='red', width=4, outline='green')
Canevas.create_oval((400,10), (250,150), width=2, outline='blue')
Canevas.create_text(550,310, fill="darkblue", font="Times 12 italic", text="Click the bubbles")
Canevas.grid()

# horizontal scrollbar
hbar = Scrollbar(cframe, orient=HORIZONTAL)
hbar.grid(row=1, column=0, sticky="nsew") Affichage d’un texte dans le canvas
# vertical scrollbar Choix de la police de caractere
vbar = Scrollbar(cframe, orient=VERTICAL)
vbar.grid(row=0, column=1, sticky="nsew")
Creation d’un ovale (cercle)
# connecting items...
Canevas.configure(xscrollcommand=hbar.set, yscrollcommand=vbar.set, scrollregion=(0, 0, 800, 600) )
hbar.configure(command=Canevas.xview)
vbar.configure(command=Canevas.yview)

# launching events main loop


Mafenetre.mainloop()
Canvas : Dessiner dans une interface
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from tkinter import *

# Tcl/Tk interpreter + main window (implicit)


Mafenetre = Tk()
Mafenetre.rowconfigure(0, weight=1)
Mafenetre.columnconfigure(0, weight=1)

# canvas + scrollbars frame container


cframe = Frame(Mafenetre)
cframe.rowconfigure(0, weight=1)
cframe.columnconfigure(0, weight=1)
cframe.grid(row=0, column=0, sticky="nsew")

# canvas
Canevas = Canvas(cframe, width=450, height=350, bg='white')
Canevas.create_line((10,10), (50,50), (10, 50), width=2)
Canevas.create_rectangle((100,100), (150,250), fill='red', width=4, outline='green')
Canevas.create_oval((400,10), (250,150), width=2, outline='blue')
Canevas.create_text(550,310, fill="darkblue", font="Times 12 italic", text="Click the bubbles")
Canevas.grid()

# horizontal scrollbar
hbar = Scrollbar(cframe, orient=HORIZONTAL)
hbar.grid(row=1, column=0, sticky="nsew")

# vertical scrollbar Connexion entre les scrollbars et le canvas


vbar = Scrollbar(cframe, orient=VERTICAL)
vbar.grid(row=0, column=1, sticky="nsew") Taille virtuelle du canvas
# connecting items...
Canevas.configure(xscrollcommand=hbar.set, yscrollcommand=vbar.set, scrollregion=(0, 0, 800, 600) )
hbar.configure(command=Canevas.xview)
vbar.configure(command=Canevas.yview)

# launching events main loop


Mafenetre.mainloop()
Canvas et scrollbar ensembles


L'intérêt de placer le canvas et les scrollbars dans une frame est
de considérer le bloc canvas+scrollbars comme un seul composant
solidaire,

Cela permet de transporter ensuite le composant entier un peu
partout dans le code / interface sans que cela ne pose de problème
particulier d'adaptation.

C'est une technique répandue en programmation de GUI
(raisonnement par composants, par briques de Lego(tm)
autonomes).
Pseudo exercice


Modifier les parametres des objets de l’interface precedente

En commentaire (separement)
– Mafenetre.rowconfigure(0, weight=1)
– cframe.grid(row=0, column=0, sticky="nsew")
– hbar.configure(command=Canevas.xview)

– cframe.rowconfigure(0, weight=1) et cframe.columnconfigure(0,


weight=1) puis remplacer cframe.grid(row=0, column=0,
sticky="nsew")par cframe.pack()
Autres objets d’une interface

Checkbutton(fenetre, text="Nouveau?")


Scale(fenetre, variable=value)


Spinbox(fenetre, from_=0, to=100)


Combobox(root, values=["ligne 1", "ligne 2", "ligne 3"])


Progressbar(orient=HORIZONTAL, length=250, mode='determinate')


Treeview

Notebook (onglet)

...
Ouverture / Sauvegarde d’un fichier
● from tkinter.filedialog import *

Ouverture d’un fichier
– askopenfilename(options)

Sauvegarde d’un fichier
– asksaveasfilename(options)


Options :
– initialdir : chemin absolue/relatif du repertoire de depart
– filetypes : liste de la forme [(nom1, motif1), (nom2, motif2), …], nomX est du
type de fichier et motifX est le motif qui filtre les fichiers. Ex : ("PNG", "*.png")
– title
– ...
Exemple d’ouverture d’un fichier
from tkinter import *
from tkinter.filedialog import *
#This is where we lauch the file manager bar.
def OpenFile():
name = askopenfilename(initialdir=".", filetypes = [("Text File",
"*.txt")], title = "Choose a file.")
#Using try in case user types in unknown file or closes without choosing a file.
try:
fichier = open(name,'r')
print(fichier.read())
except:
print("No file exists")

root = Tk()

menu = Menu(root)
file = Menu(menu)
file.add_command(label = 'Open', command = OpenFile)
file.add_command(label = 'Exit', command = root.destroy)
menu.add_cascade(label = 'File', menu = file)

root.config(menu=menu)
root.mainloop()
Conteneur d’objets : Panel


PanedWindow peut contenir des objets (non limte) arrange
horizontallement ou verticallement
● PanedWindow(objetParent, options)

Options
– Orient : HORIZONTAL (defaut), VERTICAL
– bg, cursor, height, width, ...
Conteneur d’objets : Frame


La Frame fonctionne comme un conteneur qui est responsible du
positionnement des autres objets (boutons, label, ...)

● Frame(objetParent, options)

Options
– bg, bd, cursor, relief, ...
Positionnement simple des objets

● objet.pack(options)


Options
– expend : si ‘true’, remplit tout l’espace non rempli par son parent (Ex : Frame)
– fill : remplit ou non l’espace aloue; NONE, X (remplit horizontalement), Y
(remplit verticalement), BOTH
– side : determine le cote du parent ou l’objet se place TOP (defaut), BOTTOM,
LEFT, or RIGHT.
Positionnement des objets


objet.grid(options)

from tkinter import *

root = Tk( )

for r in range(3):

for c in range(5):

Button(root, text='R%s/C%s'%(r,c), borderwidth=1).grid(row=r, column=c)

root.mainloop()
Positionnement des objets


objet.grid(options)


column : numero de colonne ou est place votre objet dans le parent

row : numero de lignes ou est place votre objet dans le parent

columnspan, rowspan : normalement un objet occuper 1 colonne et 1 ligne, ceci
permet d’agrandir ou d’allonger l’objet

padx, pady : marge exterieur X et Y en pixels

sticky : par defaut l’objet est centre dans sa cellule de la grille, si l’objet est plus
petit que la cellule, on peut positionner l’objet dans la cellule via les indications d’un
‘compas’ : N, E, S, W, NE, NW, SE, and SW (ces indications ne sont pas exclusives)
Exercice 1


Recreer l’interface suivante


L’interface est statique (elle ne fait rien !)

Utilisez .grid() pour placer les objets dans une frame
Exercice 2


Recreer l’interface suivante


L’interface est statique (elle ne fait rien !)

Utilisez .grid() pour placer les objets
Evenements de l’interface

Un événement (event) est la survenue d’une action (clavier, souris)
dont votre application a besoin d’être informée

Les objets (widgets) ont normalement un grand nombre de
comportements prédéfinis.
– Par exemple, un bouton réagit à un clic souris via son option command.

Un gestionnaire d’événement (event handler) est une fonction de
votre application qui a vocation a être appelée lorsqu’un certain
événement se produira.

Nous parlons de liaison lorsque votre application défini un gestionnaire
d’événement qui sera appelé lorsqu’un certain événement se produit
sur un widget.
Evenements de l’interface


Evénement à trois niveaux:
– Au niveau d’un widget: Par exemple, lier la touche PageUp dans un canevas pour
faire défiler la page vers le haut. La méthode bind() lie événement à un widget
● canevas.bind('<Button-1>', dessineDisqueOrange)
– Au niveau d’une classe: Par exemple, vous pourriez souhaiter régler tous les boutons
pour qu’ils réagissent à l’appui sur le bouton centrale. Utiliser la méthode
bind_class() sur n’importe quel widget (bouton).
● # w est un widget arbitraire
● w.bind_class('Canvas', '<Button-2>', dessineDisqueOrange)
– Au niveau de l’application: Par exemple, vous pourriez souhaiter lier l’événement «
appui sur la touche ImprÉcran » à tous les widgets de l’applicatoin de telle sorte que
l’écran soit imprimé indépendamment du widget qui a reçu l’appui sur la touche.
● w.bind_all('<Key-Print>', imprimeEcran)
Exemple d’evenements de l’interface
#!/usr/bin/env python3
from tkinter import *

""" Gestion de l'evenement Clic gauche sur la zone graphique """


def Clic(event):
# position du pointeur de la souris
X = event.x
Y = event.y
# on dessine un carre vert
Canevas.create_rectangle(X-15, Y-15, X+15, Y+15, outline='black', fill='green')
""" Efface la zone graphique """
def Effacer():
Canevas.delete(ALL)

# Creation de la fenetre principale


Mafenetre = Tk()
Mafenetre.title('Carres')

# Creation d'un widget Canvas


Canevas = Canvas(Mafenetre, width=480, height=320, bg ='white')
# La methode bind() lie un evenement avec une fonction :
# un clic gauche sur la zone graphique appelle la fonction Clic()
Canevas.bind('<Button-1>', Clic)
Canevas.pack(padx =5, pady =5)

# Creation d'un widget Button (bouton Effacer)


Button(Mafenetre, text ='Effacer', command = Effacer).pack(side=LEFT,padx = 5,pady = 5)

# Creation d'un widget Button (bouton Quitter)


Button(Mafenetre, text ='Quitter', command = Mafenetre.destroy).pack(side=LEFT,padx=5,pady=5)

Mafenetre.mainloop()
Exemple d’evenements de l’interface
#!/usr/bin/env python3
from tkinter import *

""" Gestion de l'evenement Clic gauche sur la zone graphique """


def Clic(event):
# position du pointeur de la souris
X = event.x
Y = event.y
# on dessine un carre vert
Canevas.create_rectangle(X-15, Y-15, X+15, Y+15, outline='black', fill='green')
""" Efface la zone graphique """
def Effacer():
Canevas.delete(ALL)

# Creation de la fenetre principale ‘Evenement’ plus simple avec command


Mafenetre = Tk()
Mafenetre.title('Carres')

# Creation d'un widget Canvas


Canevas = Canvas(Mafenetre, width=480, height=320, bg ='white')
# La methode bind() lie un evenement avec une fonction :
# un clic gauche sur la zone graphique appelle la fonction Clic()
Canevas.bind('<Button-1>', Clic)
Canevas.pack(padx =5, pady =5)

# Creation d'un widget Button (bouton Effacer)


Button(Mafenetre, text ='Effacer', command = Effacer).pack(side=LEFT,padx = 5,pady = 5)

# Creation d'un widget Button (bouton Quitter)


Button(Mafenetre, text ='Quitter', command = Mafenetre.destroy).pack(side=LEFT,padx=5,pady=5)

Mafenetre.mainloop()
Exemple d’evenements de l’interface
#!/usr/bin/env python3
from tkinter import *

""" Gestion de l'evenement Clic gauche sur la zone graphique """


def Clic(event):
# position du pointeur de la souris
X = event.x
Y = event.y
# on dessine un carre vert
Canevas.create_rectangle(X-15, Y-15, X+15, Y+15, outline='black', fill='green')
""" Efface la zone graphique """
def Effacer():
Canevas.delete(ALL)
Liaison d’evenements entre
# Creation de la fenetre principale
Mafenetre = Tk() Le bouton gauche de la souris et le canevas
Mafenetre.title('Carres') Appel de la fonction ‘clic’
# Creation d'un widget Canvas
Canevas = Canvas(Mafenetre, width=480, height=320, bg ='white')
# La methode bind() lie un evenement avec une fonction :
# un clic gauche sur la zone graphique appelle la fonction Clic()
Canevas.bind('<Button-1>', Clic)
Canevas.pack(padx =5, pady =5)

# Creation d'un widget Button (bouton Effacer)


Button(Mafenetre, text ='Effacer', command = Effacer).pack(side=LEFT,padx = 5,pady = 5)

# Creation d'un widget Button (bouton Quitter)


Button(Mafenetre, text ='Quitter', command = Mafenetre.destroy).pack(side=LEFT,padx=5,pady=5)

Mafenetre.mainloop()
Exemple d’evenements de l’interface
#!/usr/bin/env python3
from tkinter import *

""" Gestion de l'evenement Clic gauche sur la zone graphique """


def Clic(event):
# position du pointeur de la souris Recuperation de la position de la souris
X = event.x
Y = event.y
# on dessine un carre vert
Canevas.create_rectangle(X-15, Y-15, X+15, Y+15, outline='black', fill='green')
""" Efface la zone graphique """
def Effacer():
Canevas.delete(ALL)

# Creation de la fenetre principale


Mafenetre = Tk()
Dessine un carre a l’endroit
Mafenetre.title('Carres') de la souris clicquee
# Creation d'un widget Canvas
Canevas = Canvas(Mafenetre, width=480, height=320, bg ='white')
# La methode bind() lie un evenement avec une fonction :
# un clic gauche sur la zone graphique appelle la fonction Clic()
Canevas.bind('<Button-1>', Clic)
Canevas.pack(padx =5, pady =5)

# Creation d'un widget Button (bouton Effacer)


Button(Mafenetre, text ='Effacer', command = Effacer).pack(side=LEFT,padx = 5,pady = 5)

# Creation d'un widget Button (bouton Quitter)


Button(Mafenetre, text ='Quitter', command = Mafenetre.destroy).pack(side=LEFT,padx=5,pady=5)

Mafenetre.mainloop()
Exercice 3


Reprendre l’exercice 2, rajouter les evenements pour “jouer”
reellement au morpion
Pour aller plus loin


http://tkinter.fdex.eu/index.html


http://apprendre-python.com/page-tkinter-interface-graphique-
python-tutoriel


https://www.tutorialspoint.com/python/tk_*.htm
– * est le nom de l’objet

Vous aimerez peut-être aussi