Wiki Python Fr   TKinter UserPreferences
 
HelpContents FindPage Diffs Info Edit Subscribe XML Print View

  1. Utilisation de la bibliothèque Tkinter
    1. Une initiation à Tkinter
    2. Comment faire appeler des fonctions avec des paramètres à Tkinter
    3. Utilisation du widget ScrolledText
    4. Utilisation d'une checkbox
    5. Une application Tkinter sous forme de classe
    6. Les dialogues Tkinter
      1. Sélection d'un répertoire
      2. Sélection et ouverture d'un fichier
      3. Dialogue "Sauvegarder sous..."

1. Utilisation de la bibliothèque Tkinter

1.1. Une initiation à Tkinter

1.2. Comment faire appeler des fonctions avec des paramètres à Tkinter

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
## Auteur: Eric Brunel

class GenericCallback:

  def __init__(self, callback, *firstArgs):
    self.__callback = callback
    self.__firstArgs = firstArgs

  def __call__(self, *args):
    apply(self.__callback, self.__firstArgs + args)

## Exemple d'utilisation


root.mainloop()

1.3. Utilisation du widget ScrolledText

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
 32 
 33 
 34 
 35 
 36 
 37 
 38 
 39 
 40 
 41 
 42 
 43 
 44 
 45 
 46 
 47 
 48 
 49 
 50 
 51 
 52 
 53 
 54 
 55 
 56 
 57 
 58 
 59 
 60 
 61 
 62 
 63 
 64 
 65 
 66 
 67 
 68 
 69 
 70 
 71 
 72 
 73 
 74 
 75 
 76 
 77 
 78 
 79 
 80 
 81 
 82 
 83 
 84 
 85 
 86 
 87 
 88 
 89 
 90 
 91 
 92 
 93 
 94 
 95 
 96 
 97 
 98 
 99 
100 
101 
102 
103 
104 
105 
106 
107 
#N'hésiter pas à le copier et le modifier à votre convenance
#Auteur : Salvatore

#Pointeur de souris en forme de main
def main(event):
    st.config(cursor='hand2')

#Pointeur de souris en forme de flèche
def fleche(event):
    st.config(cursor='arrow')

def additionne_index(ind1,ind2):
    x1 = string.atoi(string.splitfields(ind1,'.')[0])
    y1 = string.atoi(string.splitfields(ind1,'.')[1])
    x2 = string.atoi(string.splitfields(ind2,'.')[0])
    y2 = string.atoi(string.splitfields(ind2,'.')[1])
    return ('%d.%d')%(x1+x2,y1+y2)

def colore(mot,couleur):
    start = 0.0
    while 1:
        try:
            i = st.search(mot,start,END)
            j = st.index('%s+%dc'%(i,len(mot)))
            st.tag_add(couleur,i,j)
            start = j
        except:
            break

def affiche_commande():
    commande = entre.get()
    st.insert(END,'\n'+commande,'rouge')

def click_python(event):
    st.insert(END,'\nVous avez cliquez sur Python')

texte = """
Ce petit programme constitue un aperçu
de l'utilisation de Tkinter, qui est la librairie graphique standard pour Python.
Son principale inconvénient est son 'look' non natif (sous Windows)
WxPython est une alternative très intéressante.
Python est tout à fait adapté à la création d'interfaces graphiques

Promener la souris sur le texte et constater comment le mot Python
est rendu actif.
Remarquer aussi comment 'taguer' certaines zones de texte.
Ces 'tags' permettent d'attribuer différentes caractéristiques à 
certaines parties du texte : couleur, fonte, tailles..
"""

def initialisation():
    #on insète le texte 'texte' dans le widget 'texte déroulant' nommé 'st'
    st.insert(END,texte)
    #on applique à tout le texte la police par défaut
    st.config(font = 'Arial 12 bold')
    st.config(foreground='DarkGreen')
    #on configure le fond du 'texte dérouant'
    st.config(background='LightYellow')
    #paramètres de configurations spécifiques
    #ces différents 'tags' permettront de 'taguer' de fçon spécifique
    st.tag_config('bleu',foreground='Green')
    st.tag_config('bleu',background='White')
    st.tag_config('bleu',relief='flat')
    st.tag_config('rouge',font = 'Bold')
    st.tag_config('rouge',font = 'Helvetica 12  bold')
    st.tag_config('rouge',foreground='Red')
    st.tag_bind('enorme','<Button-1>',click_python)
    st.tag_bind('enorme','<Leave>',fleche)
    st.tag_bind('enorme','<Enter>',main)
    st.tag_config('enorme',font= 'Arial 24 bold')
    st.tag_config('enorme',foreground='DarkOrange')
    e = Entry(st,width=25)
    #ici on utilise les 'tags' pour colore certains mots'
    colore('Tkinter','rouge')
    colore('Python','enorme')
    colore('Windows','rouge')

#Point d'entrée
from Tkinter import *
from ScrolledText import *

#on crée un fenetre principale 'fp' à partir du 'modèle' Tk   
fp = Tk()
fp.title('Démo Tkinter')

#Création d'un panneau 'menu_top' inséré dans 'fp'
menu_top = Frame(fp,borderwidth=2)
menu_top.pack(side='top',fill='x')

#Création d'une étiquette insérée dans 'menu_top'
etiquette = Label(menu_top,text = 'Commande : ')
etiquette.pack(side = 'left')

#Création d'un boutton dans 'menu_top'
b = Button(menu_top,text='execute',command=affiche_commande)
b.pack(side='right')

#Création d'un boite d'édition dans 'nenu_top'
entre = Entry(menu_top,width=20,relief='sunken')
entre.insert(END,'promener la souris dans le texte')
entre.pack(side='left',fill='x',expand='true')

#Déclaration du texte déroulant dans 'fp'
st = ScrolledText(fp)
st.pack(expand=1,fill='both',side='bottom')
initialisation()
fp.mainloop()

1.4. Utilisation d'une checkbox

Pour lire la valeur de certains widgets (checkbox, boutons radio...), Tkinter ne vous laisse pas la possibilité de lire directement la valeur du widget. Vous vous serez amené à créer des variables Tkinter spéciales.

Voici un exemple avec une checkbox:

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
import Tkinter

class monApplication:
    def __init__(self,root):
        self.root = root
        self.initialisation()

    def initialisation(self):
        self.monoption = Tkinter.IntVar()  # On cree une variable Tkinter
        # On cree la checkbox:
        Tkinter.Checkbutton(self.root,text="Cochez moi !",variable=self.monoption).grid(column=0,row=0)
        # On cree un bouton:
        Tkinter.Button(self.root,text="Cliquez moi pour lire la valeur",command=self.afficheValeur).grid(column=0,row=1)

    def afficheValeur(self):
        if self.monoption.get() != 0:
            print "La case est cochee."
        else:
            print "La case n'est pas cochee."

def main():
    root = Tkinter.Tk()
    root.title('Mon application')
    app = monApplication(root)
    root.mainloop()

if __name__ == "__main__":
    main()

Vous remarquerez qu'on a créé une variable numérique Tkinter (Tkinter.IntVar()) que nous attachons à la checkbox (variable=self.monoption) et dont nous lisons plus loin la valeur (self.monoption.get()).

1.5. Une application Tkinter sous forme de classe

Pour faciliter la réutilisation de votre code, vous avez tout intérêt à le mettre sous forme de classe.

Par exemple, monApplication.py (qui affiche simplement "Salut !"):

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
import Tkinter

class monApplication:
    def __init__(self,root):
        self.root = root       # On garde une référence au widget qui nous contient.
        self.initialisation()

    def initialisation(self):
        Tkinter.Label(self.root,text="Salut !").grid(column=0,row=0)

Ce qui vous permet de l'utiliser facilement par la suite dans n'importe lequel de vos logiciels Tkinter:

  1 
  2 
  3 
  4 
  5 
  6 
  7 
import Tkinter
import monApplication

root = Tkinter.Tk()
root.title('Ceci est mon programme')
app = monApplication.monApplication(root)
root.mainloop()

L'idéal est même de mettre ce code directement dans monApplication.py:

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
import Tkinter

class monApplication:
    def __init__(self,root):
        self.root = root
        self.initialisation()

    def initialisation(self):
        Tkinter.Label(self.root,text="Salut !").grid(column=0,row=0)

def main():
    root = Tkinter.Tk()
    root.title('Mon application')
    app = monApplication(root)
    root.mainloop()

if __name__ == "__main__":
    main()

Ainsi:

1.6. Les dialogues Tkinter

Tkinter est fourni avec différents dialogue qui vous simplifient la vie. En voici une partie:

1.6.1. Sélection d'un répertoire

  1 
  2 
  3 
  4 
  5 
  6 
  7 
import Tkinter
import tkFileDialog

root = Tkinter.Tk()
repertoire = tkFileDialog.askdirectory(parent=root,initialdir="/",title='Choisissez un repertoire')
if len(repertoire) > 0:
    print "vous avez choisi le repertoire %s" % repertoire

1.6.2. Sélection et ouverture d'un fichier

tkFileDialog.askopenfile ouvre lui-même le fichier vous renvoie un objet "file" que vous pouvez manipuler comme un fichier normal.

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
import Tkinter
import tkFileDialog

root = Tkinter.Tk()
file = tkFileDialog.askopenfile(parent=root,mode='rb',title='Choisissez un fichier')
if file != None:
    data = file.read()
    file.close()
    print "J'ai lu %d octets du fichier." % len(data)

1.6.3. Dialogue "Sauvegarder sous..."

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
import Tkinter
import tkFileDialog

mesFormats = [
    ('Windows Bitmap','*.bmp'),
    ('Portable Network Graphics','*.png'),
    ('JPEG / JFIF','*.jpg'),
    ('CompuServer GIF','*.gif'),
    ]

root = Tkinter.Tk()
nomFichier = tkFileDialog.asksaveasfilename(parent=root,filetypes=mesFormats,title="Sauvez l'image sous...")
if len(nomFichier) > 0:
    print "Sauvegarde en cours dans %s" % nomFichier


PythonPowered