IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Tkinter Python Discussion :

Widget Entry pour une Date


Sujet :

Tkinter Python

  1. #1
    Membre à l'essai
    Homme Profil pro
    manutentionnaire
    Inscrit en
    Décembre 2020
    Messages
    31
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Suisse

    Informations professionnelles :
    Activité : manutentionnaire

    Informations forums :
    Inscription : Décembre 2020
    Messages : 31
    Points : 13
    Points
    13
    Par défaut Widget Entry pour une Date
    Bonjour,

    sur un exercice demandant à introduire une date, d'en vérifier le format, ceci fonctionne.
    je trébuche une difficulté pour imposer des deux événements Bind de type <Tab> et <Button-1> sur le widget Entry.
    Seul l'événement <Tab> fonctionne.
    Si j'introduit une date puis clique directement dans le Entry KM_Compteur, j'obtient cette erreur :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
        print("addData - Date Consommation - Entry - Date_Plein", Date_Plein)
    NameError: name 'Date_Plein' is not defined
    ça signifie que l'événement n'a pas été sollicité.
    Comment imposer l'activation de l'événement, si l'utilisateur clique sur une autre widget entre?




    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    108
    109
    110
    111
    # coding:utf-8
    # version 3.x python
     
     
    from tkinter import *
    import tkinter as tk
    from tkinter.ttk import *
     
    from tkinter.ttk import Button
    from tkinter import font
    from tkinter.scrolledtext import ScrolledText
    from tkinter import messagebox                                                                          # Librairie des fenêtres d'alerte
     
    from datetime import datetime                                                                            # Librairie de gestion des dates et heures
     
    # =========================== Fenêtre principale  ==========================
    root = tk.Tk()
    root.title('Nouvelle consommation de carburant')
    root.geometry("706x307+1100+700")                                                                    # ("950x355+30+30")
    root.resizable(width=False, height=False)                                                         # Fenêtre verrouillée
    root.attributes("-toolwindow", 1)                                                                       # Supprime les boutons Réduire/Agrandir
    root.attributes("-topmost", 1)                                                                           # au priemier plan
     
    # ============================== Cadres  ==============================
    FrameLeft = LabelFrame(root, text="[Nouveau plein]", width=300, height=140)
    FrameLeft.grid(row=0, column=0, sticky=W)
     
    ConsoKM = IntVar()
    # ============================== Fonctions ========================
    #
    def ClearEntry():
        txt_ConsoDate.delete(0, END)
        txt_ConsoDate.focus_force()
        txt_ConsoKM.delete(0, END)
     
    #
    def addData():
        #
        if txt_ConsoDate.get() != "":    # and txt_ConsoKM.get() != "" and txt_ConsoPlein.get() != "" and txt_ConsoPrix.get() != "":
            print("\n-----------------------------------------------------------------------------------------------")
            print("addData - Date Consommation - Entry - txt_ConsoDate.get()", txt_ConsoDate.get())
            print("addData - Date Consommation - Entry - Date_Plein", Date_Plein)
            print("addData - Date Consommation - Entry - txt_ConsoKM.get()", txt_ConsoKM.get())
            print("\n")
     
        else:
            # La fenêtre msgBox apparaît sur le fenêtre enfant SAF_SD sans l'affichage de le fenêtre master Main
            messagebox.showwarning("Attention", "Veuillez remplir tous les champs")
            root.deiconify()
     
    # [Entry Widget] -
    def onClick_Dtr(event, obj):
        # Curseur après la valeur de  la variable
        # print("onClick_Dtr - obj", obj)
        obj.focus()
        if obj == FrameLeft.winfo_children()[1]:
            print("**")
            saisieDateConso(event, obj)
     
    # Validation de la date
    def saisieDateConso(event, obj):
        print("saisieDateConso - obj -->    ", obj, obj.get(), type(obj.get()))
        if event.widget == obj:
            try:
                # -- Analyse --
                # Conversion d'une chaînes en date avec strptime
                # strptime --> analyse une chaîne de caractères dans un objet datetime en fonction du format de correspondance donné
                # %d Jour du mois sur 2 chiffres
                # %m Numéro du mois sur 2 chiffres
                # %Y     Année complète sur 4 chiffres
                datetime.strptime(obj.get(), '%d.%m.%Y')
                global Date_Plein
                Date_Plein = ""
                Date_Plein = datetime.strptime(obj.get(), '%d.%m.%Y').date()
                print("saisieDateConso - Date_Plein - datetime.strptime(obj.get(), '%d.%m.%Y')  ", Date_Plein, type(Date_Plein))
     
            except ValueError:
                messagebox.showwarning("Attention", "Veuillez saisir une date valide" + "\n" + "              jj.mm.aaaa")
                root.withdraw()
                root.deiconify()
                obj.delete(0, 'end')
     
     
    # ============================== Widgets ==============================
     
    #
    lblConsoDate = Label(FrameLeft, text="Date")
    lblConsoDate.place(x=2, y=25)
     
    txt_ConsoDate = Entry(FrameLeft, text="", width=11)
    txt_ConsoDate.focus_force()
    txt_ConsoDate.place(x=88, y=26)
    txt_ConsoDate.insert(0, "jj.mm.aaaa")
    # print("Identification Entry Date Consommation - FrameLeft.winfo_children()[1]            							", FrameLeft.winfo_children()[1])
     
    txt_ConsoDate.bind("<Tab>", lambda event, obj=FrameLeft.winfo_children()[1]: onClick_Dtr(event, obj))
    txt_ConsoDate.bind("<Button-1>", lambda event, obj=FrameLeft.winfo_children()[1]: onClick_Dtr(event, obj))
     
    #
    lblConsoKM = Label(FrameLeft, text="KM_Compteur")
    lblConsoKM.place(x=2, y=46)
    txt_ConsoKM = Entry(FrameLeft, textvariable=ConsoKM, width=33)
    txt_ConsoKM.place(x=88, y=47)
    txt_ConsoKM.bind("<Tab>", lambda event, obj=txt_ConsoKM: onClick_Dtr(event, obj))
     
     
     
    btnAddData = tk.Button(root, text="Ajouter", font=('verdana', 8, ''), state=NORMAL, command=addData)
    btnAddData.place(x=12, y=150)
     
    root.mainloop()

    merci de votre temps

  2. #2
    Expert éminent sénior
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 379
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Architecte technique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 21 379
    Points : 36 923
    Points
    36 923
    Par défaut
    Salut,

    Si la fonction/callback n'est pas appelée, la variable globale ne sera pas définie.

    Après, c'est un écran de saisie... vérifier que l'utilisateur à bien effectué les saisies attendues avant de faire quelque chose avec des résultats qui ne sont pas encore là...

    - W

  3. #3
    Membre à l'essai
    Homme Profil pro
    manutentionnaire
    Inscrit en
    Décembre 2020
    Messages
    31
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Suisse

    Informations professionnelles :
    Activité : manutentionnaire

    Informations forums :
    Inscription : Décembre 2020
    Messages : 31
    Points : 13
    Points
    13
    Par défaut
    ça donnerai ceci :

    apparemment cela fonctionne
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    # coding:utf-8
    # version 3.x python
     
    from tkinter import *
    import tkinter as tk
    from tkinter.ttk import *
     
    from tkinter.ttk import Button
    from tkinter import font
    from tkinter.scrolledtext import ScrolledText
    from tkinter import messagebox                                                                          # Librairie des fenêtres d'alerte
     
    from datetime import datetime                                                                            # Librairie de gestion des dates et heures
     
    # =========================== Fenêtre principale  ==========================
    root = tk.Tk()
    root.title('Nouvelle consommation de carburant')
    root.geometry("706x307+1100+700")                                                                    # ("950x355+30+30")
    root.resizable(width=False, height=False)                                                         # Fenêtre verrouillée
    root.attributes("-toolwindow", 1)                                                                       # Supprime les boutons Réduire/Agrandir
    root.attributes("-topmost", 1)                                                                           # au priemier plan
     
    # ============================== Cadres  ==============================
    FrameLeft = LabelFrame(root, text="[Nouveau plein]", width=300, height=140)
    FrameLeft.grid(row=0, column=0, sticky=W)
     
    ConsoKM = IntVar()
     
    # ============================== Fonctions ========================
    #
    def ClearEntry():
        txt_ConsoDate.delete(0, END)
        txt_ConsoDate.focus_force()
        txt_ConsoKM.delete(0, END)
     
    #
    def addData():
        #
        if txt_ConsoDate.get() != "":    # and txt_ConsoKM.get() != "" and txt_ConsoPlein.get() != "" and txt_ConsoPrix.get() != "":
            print("\n-----------------------------------------------------------------------------------------------")
            print("addData - Date Consommation - Entry - txt_ConsoDate.get()", txt_ConsoDate.get())
            print("addData - Date Consommation - Entry - Date_Plein", Date_Plein)
            print("addData - Date Consommation - Entry - txt_ConsoKM.get()", txt_ConsoKM.get())
            print("\n")
     
        else:
            # La fenêtre msgBox apparaît sur le fenêtre enfant sans l'affichage de le fenêtre master
            messagebox.showwarning("Attention", "Veuillez remplir tous les champs")
            root.deiconify()
     
        # [Entry Widget] -
    def onClick_Dtr(obj):
        # Curseur après la valeur de  la variable
        # print("onClick_Dtr - obj", obj)
        obj.focus()
     
     
    # Validation de la date
    def saisieDateConso(obj):
        print("saisieDateConso - obj -->    ", obj, obj.get(), type(obj.get()))
        try:
            # -- Analyse --
            # Conversion d'une chaînes en date avec strptime
            # strptime --> analyse une chaîne de caractères dans un objet datetime en fonction du format de correspondance donné
            # %d Jour du mois sur 2 chiffres
            # %m Numéro du mois sur 2 chiffres
            # %Y     Année complète sur 4 chiffres
            datetime.strptime(obj.get(), '%d.%m.%Y')
            global Date_Plein
            Date_Plein = ""
            Date_Plein = datetime.strptime(obj.get(), '%d.%m.%Y').date()
            print("saisieDateConso - Date_Plein - datetime.strptime(obj.get(), '%d.%m.%Y')  ", Date_Plein, type(Date_Plein))
     
            addData()
     
        except ValueError:
            messagebox.showwarning("Attention", "Veuillez saisir une date valide" + "\n" + "              jj.mm.aaaa")
            root.withdraw()
            root.deiconify()
            obj.delete(0, 'end')
     
    # ============================== Widgets ==============================
    #
    lblConsoDate = Label(FrameLeft, text="Date")
    lblConsoDate.place(x=2, y=25)
     
    txt_ConsoDate = Entry(FrameLeft, text="", width=11)
    txt_ConsoDate.focus_force()
    txt_ConsoDate.place(x=88, y=26)
    txt_ConsoDate.insert(0, "jj.mm.aaaa")
     
    # print("Identification Entry Date Consommation - FrameLeft.winfo_children()[1]            							", FrameLeft.winfo_children()[1])
    txt_ConsoDate.bind("<Tab>", lambda event, obj=FrameLeft.winfo_children()[1]: onClick_Dtr(obj))
     
    #
    lblConsoKM = Label(FrameLeft, text="KM_Compteur")
    lblConsoKM.place(x=2, y=46)
    txt_ConsoKM = Entry(FrameLeft, textvariable=ConsoKM, width=33)
    txt_ConsoKM.place(x=88, y=47)
    txt_ConsoKM.bind("<Tab>", lambda event, obj=txt_ConsoKM: onClick_Dtr(event, obj))
     
    btnAddData = tk.Button(root, text="Ajouter", font=('verdana', 8, ''), state=NORMAL, command=lambda obj=FrameLeft.winfo_children()[1]: saisieDateConso(obj)) 
    btnAddData.place(x=12, y=150)
     
    root.mainloop()

  4. #4
    Expert éminent sénior
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 379
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Architecte technique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 21 379
    Points : 36 923
    Points
    36 923
    Par défaut
    Par exemple...
    Vous pourriez même sans doute passer Date_Plein en paramètre de add_data et ne plus en faire une variable globale.

    Notez que quand vous faite un .bind, la fonction reçoit un event en paramètre dans lequel le widget associé se récupère via event.widget.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    lambda event, obj=FrameLeft.winfo_children()[1]: onClick_Dtr(obj))
    pourrait se réduire à:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    lambda event=onClick_Dtr(event.widget))
    - W

  5. #5
    Membre à l'essai
    Homme Profil pro
    manutentionnaire
    Inscrit en
    Décembre 2020
    Messages
    31
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Suisse

    Informations professionnelles :
    Activité : manutentionnaire

    Informations forums :
    Inscription : Décembre 2020
    Messages : 31
    Points : 13
    Points
    13
    Par défaut
    merci pour votre aide

Discussions similaires

  1. [Dates] Besoin de conseil pour une date
    Par Dargos dans le forum Langage
    Réponses: 6
    Dernier message: 19/07/2006, 11h59
  2. Manipuler le format retourné pour une date.
    Par BlackMinou dans le forum Oracle
    Réponses: 3
    Dernier message: 05/04/2006, 18h01
  3. Regroupement de valeur pour une date
    Par Erakis dans le forum Requêtes
    Réponses: 4
    Dernier message: 15/06/2005, 21h00
  4. [VB.NET] Valur null pour une date.
    Par Lois dans le forum Windows Forms
    Réponses: 2
    Dernier message: 20/12/2004, 14h38
  5. Création requete besoin d'aide pour une date
    Par royrremi dans le forum MS SQL Server
    Réponses: 2
    Dernier message: 14/07/2004, 22h03

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo