Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Les deux révisions précédentesRévision précédente
Prochaine révision
Révision précédente
tkinter [Le 31/01/2013, 19:28] 88.172.93.113tkinter [Le 04/05/2018, 14:13] (Version actuelle) – [Étude d'un programme simple] 78.253.251.33
Ligne 1: Ligne 1:
 +{{tag> programmation python}}
 +----
 +====== Créer des interfaces graphiques avec Tkinter ======
  
 +===== Présentation =====
 +
 +**Tkinter** est une librairie basique mais très simple d'utilisation pour construire rapidement des interfaces graphiques avec [[:python|Python]].
 +
 +Le style de widgets n'est pas très esthétique (question de goût) mais ça reste tout de même une bonne base pour commencer dans le développement d'interface graphique (GUI). 
 +
 +===== Installation =====
 +
 +[[:tutoriel:comment_installer_un_paquet|Installez les paquets]]:
 +  * **[[apt>python-tk]]**
 +  * **[[apt>python-imaging-tk]]** pour la gestion des images sous tkinter 
 +  * **[[apt>python3-tk]]** pour la version 3.x de python. (La version 3.x comprend les widgets ttk)
 +
 +===== Étude d'un programme simple =====
 +Pour commencer, regardez et essayez de comprendre la structure du code :
 +
 +<file python>
 +#!/usr/bin/env python
 +# -*- coding: Latin-1 -*-
 +#
 +#  Programme Tkinter.py
 +#  Démonstration du language
 +
 +
 +from Tkinter import *  #Pour python3.x Tkinter devient tkinter
 +
 +class ApplicationBasic():
 + '''Application principale'''
 + def __init__(self):
 + '''constructeur'''
 + self.fen = Tk()
 + self.fen.title('Tkinter')
 +
 + self.bou_action = Button(self.fen)
 + self.bou_action.config(text='Action', command=self.action)
 + self.bou_action.pack()
 +
 + self.bou_quitter = Button(self.fen)
 + self.bou_quitter.config(text='Quitter', command=self.fen.destroy)
 + self.bou_quitter.pack()
 +  
 + def run(self):
 +                self.fen.mainloop()
 +
 + def action(self):
 + '''Action sur un bouton'''
 + self.lab = Label(self.fen)
 + self.lab.config(text='Bravo!!!')
 + self.lab.pack()
 +      
 +      
 +if __name__ == '__main__':
 + app = ApplicationBasic()
 +        app.run()
 +</file>
 +chaque partie correspond à :
 +  * importation de la librairie : <file python>from Tkinter import *</file>
 +  * création d'une classe : <file python>class ApplicationBasic():</file>
 +  * création d'une méthode constructrice : <file python>def __init__(self):</file> 
 +  * instancier une fenêtre Tk() : <file python>self.fen = Tk()</file>
 +  * définition du titre de cette fenêtre : <file python>self.fen.title('Tkinter')</file>
 +
 +  * création d'un simple bouton action : <file python>self.bou_action = Button(self.fen)</file>
 +     * configuration de ce bouton : <file python>self.bou_action.config(text='Action', command=self.action)</file>
 +     * mise en place de celui-ci dans la fenêtre avec une méthode de placement : <file python>self.bou_action.pack()</file>
 +     * définition de la fonction qui sera connectée au bouton //Action// : <file python>
 +  def action(self) :
 +      '''Action sur un bouton'''
 +      self.lab = Label(self.fen)
 +      self.lab.config(text='Bravo!!!')
 +      self.lab.pack()
 +</file>
 +
 +  * même travail pour créer un bouton quitter. Ici vous constaterez qu'il n'est pas nécessaire de créer une fonction dédiée à ce bouton, la commande associée faisant le nécessaire : <file python>self.bou_quitter = Button(self.fen)
 +self.bou_quitter.config(text='Quitter', command=self.fen.destroy)
 +self.bou_quitter.pack()</file>
 +
 +
 +  * lancement du gestionnaire d'événements : <file python>self.fen.mainloop()</file>
 +  * assignation de la classe à une variable :<file python>app = ApplicationBasic()</file>
 +
 +Enregistrez votre fichier source avec une extension //.py// puis lancez-le depuis un [[:terminal]] en saisissant la [[:commande_shell|commande]] suivante:
 +<code>python 'fichier.py'</code>
 +
 + {{:programmetkinter.png?direct&100|Fenêtre nommée Tkinter avec les deux boutons}}          
 +{{:terminal:programmetkinter01.png?direct&100|Fenêtre Tkinter après appui sur le bouton //Action//}}
 +
 +===== Exemple de programmes =====
 +==== PyConnect ====
 +La structure du code est un peu différente car j'utilise une classe.
 +
 +<file python>
 +#!/usr/bin/env python
 +# -*- coding: utf-8 -*-
 +#
 +#  PyConnect.py
 +#
 +# Vérification de la connexion internet avec interface et ping
 +#
 +
 +#Importation des librairies nécéssaire au bon fonctionnement du programme.
 +#Tkinter pour l'interface graphique
 +#urllib pour les schémas internet
 +#os pour dialoguer avec le systeme
 +from Tkinter import * 
 +import urllib as url
 +import os 
 +class Application(Frame):
 + def __init__(self,parent):
 + Frame.__init__(self)
 + self.parent = parent
 + self.etat = Label(self, text='',font='Times 28 italic bold')
 + self.etat.grid(row=0, column=0, columnspan=4, sticky=NSEW)
 +
 + self.lab_iface = Label(self, text='Interfaces:',font='Times',underline=0)
 + self.lab_iface.grid(row=1,column=0,sticky=NSEW)
 +
 + self.iface = Text(self, font='Times 10')
 + self.iface.grid(row=2, column=0, sticky=NSEW)
 +
 + self.lab_ping = Label(self, text='Ping:',font='Times',underline=0)
 + self.lab_ping.grid(row=1,column=2,sticky=NSEW)
 +
 + self.ping = Text(self, font='Times',state='disabled')
 + self.ping.grid(row=2, column=1, columnspan=3, sticky=NSEW)
 +
 + self.recharger = Button(self, text='Recharger', font='Times', command=self.checkIface)
 + self.recharger.grid(row=3, column=0, sticky=NSEW)
 +
 + self.quitter = Button(self, text='Quitter', font='Times', command=self.leave)
 + self.quitter.grid(row=3, column=1, columnspan=3,sticky=NSEW)
 +
 + self.checkIface()
 +
 + def checkIface(self):
 + self.iface.config(state='normal')
 + self.iface.delete(1.0,END)
 + self.listing = os.popen('ifconfig', 'r').read()
 + self.iface.insert(END, self.listing)
 + self.iface.config(state='disabled')
 + self.checkInternet()
 +
 + def checkInternet(self):
 + try:
 + url.urlopen('http://www.google.com')
 + self.etat.config(text='Connexion internet active')
 + self.checkPing()
 + except:
 + self.etat.config(text='Connexion internet inactive')
 + self.ping.config(state='normal')
 + self.ping.delete(1.0,END)
 + self.ping.insert(END, 'Ping impossible...')
 + self.ping.config(state='disabled')
 +
 + def checkPing(self):
 + self.ping.config(state='normal')
 + self.ping.delete(1.0,END)
 + c = 3
 + while c != 0:
 + self.pingPacket = os.popen('ping -c 1 google.com').read()
 + self.ping.insert(END, self.pingPacket+'\n')
 + self.parent.after(1,self.parent.update())
 + c = c-1
 +
 + self.ping.config(state='disabled')
 +
 + def leave(self):
 + quit()
 +
 +if __name__ == '__main__':
 + fen = Tk()
 + fen.title('Connexion Internet')
 + fen.resizable(False,False)
 +
 + app = Application(fen)
 + app.grid(row=0, column=0, sticky=NSEW)
 +
 + fen.mainloop()
 +</file>
 +{{:pyconnect.png?800|}}
 +===== Liens =====
 +  * [[http://wiki.python.org/moin/TkInter|Tkinter]] (En)
 +  * [[http://effbot.org/tkinterbook/|Tkinter]] (En)
 +  * [[https://github.com/tarball69/tkRAD/wiki/Accueil|tkRAD: Tkinter XML widget builder]] (Fr) - génération facile de widgets Tkinter grâce à un fichier source XML.
 +  * [[:python]]
 +  * [[:glade]] : pour créer des GUI facilement
 +
 +----
 +//Contributeurs:Boileau jonathan -- Mail: [[couverture.jonathan.b@gmail.com]] //