#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from tkinter import *

# on définit une fermeture
def key_pad (key_value):
    # on définit ici la vraie fonction qui fait le traitement attendu;
    # comme cette fonction sera appelée par le bouton cliquable
    # elle ne prend AUCUN ARGUMENT dans sa définition;
    # en revanche, elle va se servir des arguments stockés dans
    # la fermeture (c'est tout l'intérêt du truc);
    def mon_traitement ():
        # on exploite l'argument stocké par la fermeture
        # touche pavé numérique '0' à '9':
        if key_value in range(10):
            # on ajoute un chiffre à l'affichage
            display.set(display.get() + str(key_value))
        # touche 'AC' - 'All Clear' - tout effacer
        elif key_value == 'AC':
            # on efface tout
            display.set("")
        # ...etc...
        # end if
    # end def
    # retourne une fonction en résultat
    return mon_traitement
# end def

# on crée la fenêtre principale
fenetre = Tk()
fenetre.title("Calculette")
fenetre.resizable(width=False, height=False)

# on ajoute des widgets
display = StringVar()
Label(
    fenetre,
    textvariable=display,
    anchor=E,
    bg="pale green",
    font="sans 14 bold",
    relief=SUNKEN,
    width=10,
).pack(padx=5, pady=5)

# on crée un conteneur à boutons
frame = Frame(fenetre)
frame.pack(padx=5, pady=5)

# options de grid()
opts = dict(sticky=NW+SE)

# on ajoute les boutons utilisant la fermeture
Button(
    frame,
    text="C",
    command=key_pad('C')
).grid(row=0, column=0, **opts)

Button(
    frame,
    text="AC",
    command=key_pad('AC')
).grid(row=0, column=1, columnspan=2, **opts)

Button(frame, text="9", command=key_pad(9)).grid(row=1, column=2, **opts)
Button(frame, text="8", command=key_pad(8)).grid(row=1, column=1, **opts)
Button(frame, text="7", command=key_pad(7)).grid(row=1, column=0, **opts)
Button(frame, text="6", command=key_pad(6)).grid(row=2, column=2, **opts)
Button(frame, text="5", command=key_pad(5)).grid(row=2, column=1, **opts)
Button(frame, text="4", command=key_pad(4)).grid(row=2, column=0, **opts)
Button(frame, text="3", command=key_pad(3)).grid(row=3, column=2, **opts)
Button(frame, text="2", command=key_pad(2)).grid(row=3, column=1, **opts)
Button(frame, text="1", command=key_pad(1)).grid(row=3, column=0, **opts)

Button(
    frame,
    text="0",
    command=key_pad(0)
).grid(row=4, column=0, columnspan=2, **opts)

Button(
    frame,
    text=".",
    command=key_pad('.')
).grid(row=4, column=2, **opts)

# on ajoute un bouton quitter
Button(
    fenetre,
    text="Quitter",
    command=fenetre.destroy,
).pack(padx=5, pady=5)

# on lance la boucle principale
fenetre.mainloop()
