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 :

[DEBUTANT] Fermer une fenêtre après un clic sur un boutton


Sujet :

Tkinter Python

  1. #1
    Membre chevronné

    Profil pro
    Account Manager
    Inscrit en
    Décembre 2006
    Messages
    2 301
    Détails du profil
    Informations personnelles :
    Localisation : France, Savoie (Rhône Alpes)

    Informations professionnelles :
    Activité : Account Manager

    Informations forums :
    Inscription : Décembre 2006
    Messages : 2 301
    Points : 1 752
    Points
    1 752
    Par défaut [DEBUTANT] Fermer une fenêtre après un clic sur un boutton
    Bonjour,
    j'ai récupérer le code suivant sur le net auquel j'ai apporté de petites modifications :
    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
    #!/usr/bin/env python
    #coding=utf-8
     
    import Tkinter
     
    answers = None
     
    class simpleapp_tk(Tkinter.Tk):
        def __init__(self):
            Tkinter.Tk.__init__(self, None)
            self.__initialize()
     
        def __initialize(self):
            self.grid()
     
    # Static text
            self.labelVariable = Tkinter.StringVar()
     
            label = Tkinter.Label(self,
                                  textvariable = self.labelVariable)
            label.grid(row=0,
                       column=0,
                       sticky='EW')
     
            self.labelVariable.set(u"a = ")
     
    # Entry here the user can give its value
            self.entryVariable = Tkinter.StringVar()
     
            self.entry = Tkinter.Entry(self,
                                       textvariable = self.entryVariable)
            self.entry.grid(row = 0,
                            column = 1,
                            sticky='EW')
    #    self.entry.bind("<Return>", self.OnPressEnter)
     
            self.entryVariable.set(u"Votre valeur")
     
    # One Button to say that everythong is ok
     
            button = Tkinter.Button(self,
                                    text = u"OK",
                                    command = self.OnButtonClick)
            button.grid(row = 0,
                        column = 2)
     
            self.grid_columnconfigure(0,
                                      weight=1)
            self.resizable(True,
                           False)
            self.update()
            self.geometry(self.geometry())
            self.entry.focus_set()
            self.entry.selection_range(0, Tkinter.END)
     
        def OnButtonClick(self):
            global answers
            answers = self.entryVariable.get()
     
    # Tout fermer maintenant.
     
     
    if __name__ == "__main__":
        app = simpleapp_tk()
        app.title('my application')
        a = app.mainloop()
     
        if answers != None:
            print answers
    Il y a deux choses que je n'arrive pas à faire :
    1. Fermer mon application au moment indiquer en commentaire.
    2. Récupérer le contenu de "l'entrée" sans passer par une variable globale.


    Toute info. est bienvenue.

    PS : l'idée de mon code est de fournir un alternative visuelle au input de la console.

  2. #2
    Expert éminent

    Homme Profil pro
    Inscrit en
    Octobre 2008
    Messages
    4 301
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations forums :
    Inscription : Octobre 2008
    Messages : 4 301
    Points : 6 781
    Points
    6 781
    Par défaut
    Salut,

    Tu veux récupérer la saisie dans la console, c'est bien ça ?

    Alors comme ça :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
    ...
        def OnButtonClick(self):
            answers = self.entryVariable.get()
            sys.exit(answers)
     
    if __name__ == "__main__":
        app = simpleapp_tk()
        app.title('my application')
        a = app.mainloop()

  3. #3
    Membre chevronné

    Profil pro
    Account Manager
    Inscrit en
    Décembre 2006
    Messages
    2 301
    Détails du profil
    Informations personnelles :
    Localisation : France, Savoie (Rhône Alpes)

    Informations professionnelles :
    Activité : Account Manager

    Informations forums :
    Inscription : Décembre 2006
    Messages : 2 301
    Points : 1 752
    Points
    1 752
    Par défaut
    Bonjour,
    en fait voici un code plus parlant qui montre ce que je cherche à faire :
    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
    #!/usr/bin/env python
    #coding=utf-8
     
    """
    Here we show how to have an easy-to-use graphical input.
     
    For example, if you want to ask three variables to the user,
    you just have to type something like :
        a, b, c = ask("a =", "b =", "c =")
    """
     
    try:
        import Tkinter as tkinter
    except:
        import tkinter
     
    answers = []
     
    class ask_tk(tkinter.Tk):
        def __init__(self, theTexts):
            tkinter.Tk.__init__(self, None)
            self.theText = theTexts
            self.answers = []
            self.labelVariable = []
            self.entryVariable = []
            self.entry = []
            self.__initialize()
     
        def __initialize(self):
            self.grid()
     
            for i, oneText in enumerate(self.theText):
    # Static text
                self.labelVariable.append(tkinter.StringVar())
                currentLabelVariable = self.labelVariable[i]
     
                label = tkinter.Label(self,
                                      textvariable = currentLabelVariable)
                label.grid(row=i,
                           column=0,
                           sticky=tkinter.E)
     
                currentLabelVariable.set(oneText)
     
    # Entry here the user can give its value
                self.entryVariable.append(tkinter.StringVar())
                currentEntryVariable = self.entryVariable[i]
     
                self.entry.append(tkinter.Entry(self,
                                                textvariable = currentEntryVariable))
                currentEntry = self.entry[i]
                currentEntry.grid(row = i,
                                  column = 1,
                                  sticky='EW')
    #    self.entry.bind("<Return>", self.OnPressEnter)
     
    # One Button to say that everything is ok
            button = tkinter.Button(self,
                                    text = "OK",
                                    command = self.OnButtonClick)
            button.grid(row = len(self.theText),
                        column = 0)
     
            self.grid_columnconfigure(0,
                                      weight=1)
            self.resizable(True,
                           False)
            self.update()
            self.geometry(self.geometry())
    #        self.entry.focus_set()
    #        self.entry.selection_range(0, tkinter.END)
     
        def OnButtonClick(self):
            global answers
            answers = [x.get() for x in self.entryVariable]
     
    # MON PROBLEME EST ICI !!!!
    # Tout fermer maintenant.
     
    def ask(*args):
        global answers
        answers = ['']*len(args)
     
        app = ask_tk(args)
        app.title('')
        a = app.mainloop()
     
        return answers
     
    if __name__ == "__main__":
        a,b,c = ask("a =",
                    "b =",
                    "c =")
     
        print('a = ', a)
        print('b = ', b)
        print('c = ', c)
    En fait, je cherche à faire un outil pour enseigner l'algorithmique. Au lieu de passer par la console, je préfèrerais utiliser une petite boîte de dialogue dynamique.

    Le code ci-dessus me crée une interface qui me convient.

    Il me reste juste une chose à faire : une fois le bouton OK activé, je veux que ma boîte de dialogue disparaisse. Mon problème est peut-être dû à la façon dont est définie ma boîte de dialogue.

  4. #4
    Expert éminent

    Homme Profil pro
    Inscrit en
    Octobre 2008
    Messages
    4 301
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations forums :
    Inscription : Octobre 2008
    Messages : 4 301
    Points : 6 781
    Points
    6 781
    Par défaut
    Oui mais tu veux les récupérer dans la console ou pas tes infos ?

    C'est ce que fait mon code.

  5. #5
    Membre chevronné

    Profil pro
    Account Manager
    Inscrit en
    Décembre 2006
    Messages
    2 301
    Détails du profil
    Informations personnelles :
    Localisation : France, Savoie (Rhône Alpes)

    Informations professionnelles :
    Activité : Account Manager

    Informations forums :
    Inscription : Décembre 2006
    Messages : 2 301
    Points : 1 752
    Points
    1 752
    Par défaut
    Je veux que ce soit le code qui récupère les variables. En l'état, la variable globale fait le job même si je trouve cela inélégant.

    Mon réel problème, le plus important, est que le clic sur OK ne permet pas de fermer la fenêtre. Comment faire ? J'ai esssayé quit, destroy.

  6. #6
    Expert éminent

    Homme Profil pro
    Inscrit en
    Octobre 2008
    Messages
    4 301
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations forums :
    Inscription : Octobre 2008
    Messages : 4 301
    Points : 6 781
    Points
    6 781
    Par défaut
    Fait de tta fenêtre un objet séparé.

    Je m'explique :

    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
     
    #!/usr/bin/env python
    #coding=utf-8
     
    import sys
    import time
     
    import Tkinter
     
    answers = None
     
    class simpleapp_tk(Tkinter.Tk):
        def __init__(self):
            Tkinter.Tk.__init__(self, None)
            self.__initialize()
     
        def __initialize(self):
            self.grid()
     
    # Static text
            self.labelVariable = Tkinter.StringVar()
     
            label = Tkinter.Label(self,
                                  textvariable = self.labelVariable)
            label.grid(row=0,
                       column=0,
                       sticky='EW')
     
            self.labelVariable.set(u"a = ")
     
    # Entry here the user can give its value
            self.entryVariable = Tkinter.StringVar()
     
            self.entry = Tkinter.Entry(self,
                                       textvariable = self.entryVariable)
            self.entry.grid(row = 0,
                            column = 1,
                            sticky='EW')
    #    self.entry.bind("<Return>", self.OnPressEnter)
     
            self.entryVariable.set(u"Votre valeur")
     
    # One Button to say that everythong is ok
     
            button = Tkinter.Button(self,
                                    text = u"OK",
                                    command = self.OnButtonClick)
            button.grid(row = 0,
                        column = 2)
     
            self.grid_columnconfigure(0,
                                      weight=1)
            self.resizable(True,
                           False)
            self.update()
            self.geometry(self.geometry())
            self.entry.focus_set()
            self.entry.selection_range(0, Tkinter.END)
     
        def OnButtonClick(self):
            main.datas = self.entryVariable.get()
            main.close()
     
    class Main(object):
        def __init__(self):
            self.datas = None
            self.win = None
     
        def close(self):
            self.win.destroy()
            print "datas :", self.datas
     
    if __name__ == "__main__":
        main = Main()
        app = simpleapp_tk()
        main.win = app
        app.title('my application')
        app.mainloop()
    Ca, ça marche.

  7. #7
    Membre chevronné

    Profil pro
    Account Manager
    Inscrit en
    Décembre 2006
    Messages
    2 301
    Détails du profil
    Informations personnelles :
    Localisation : France, Savoie (Rhône Alpes)

    Informations professionnelles :
    Activité : Account Manager

    Informations forums :
    Inscription : Décembre 2006
    Messages : 2 301
    Points : 1 752
    Points
    1 752
    Par défaut
    Merci.

    Voilà ce que j'ai pu faire :
    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
    #!/usr/bin/env python
    #coding=utf-8
     
    # Source
    #    http://www.developpez.net/forums/d1007391/autres-langages/python-zope/gui/tkinter/debutant-fermer-fenetre-apres-clic-boutton/#post5630766
     
    import sys
     
    try:
        import Tkinter as tkinter
    except:
        import tkinter
     
    DATAS = None
    MAIN = None
     
    class askTk(tkinter.Tk):
        def __init__(self, theTexts):
            tkinter.Tk.__init__(self, None)
            self.theText = theTexts
            self.datas = []
            self.labelVariable = []
            self.entryVariable = []
            self.entry = []
            self.__initialize()
     
        def __initialize(self, *args):
            self.grid()
     
            for i, oneText in enumerate(self.theText):
    # Static text
                self.labelVariable.append(tkinter.StringVar())
                currentLabelVariable = self.labelVariable[i]
     
                label = tkinter.Label(self,
                                      textvariable = currentLabelVariable)
                label.grid(row=i,
                           column=0,
                           sticky=tkinter.E)
     
                currentLabelVariable.set(oneText)
     
    # Entry here the user can give its value
                self.entryVariable.append(tkinter.StringVar())
                currentEntryVariable = self.entryVariable[i]
     
                self.entry.append(tkinter.Entry(self,
                                                textvariable = currentEntryVariable))
                currentEntry = self.entry[i]
                currentEntry.grid(row = i,
                                  column = 1,
                                  sticky='EW')
    #    self.entry.bind("<Return>", self.OnPressEnter)
     
    # One Button to say that everything is ok
            button = tkinter.Button(self,
                                    text = "OK",
                                    command = self.OnButtonClick)
            button.grid(row = len(self.theText),
                        column = 0,
                        columnspan = 3)
     
            self.grid_columnconfigure(0,
                                      weight=1)
            self.resizable(False,
                           False)
            self.update()
            self.geometry(self.geometry())
     
    # We want that the cursor is in the first entry.
            self.entry[0].focus_set()
     
        def OnButtonClick(self):
            MAIN.datas = [x.get() for x in self.entryVariable]
            MAIN.close()
     
    class Main(object):
        def __init__(self):
            self.datas = None
            self.win = None
     
        def close(self):
            self.win.destroy()
            global DATAS
            DATAS = self.datas
     
    def ask(*args):
        global MAIN
        MAIN = Main()
        for oneArg in args:
            if not isinstance(oneArg, str):
                raise ValueError('All the arguments must be strings...')
     
        global DATAS
        DATAS = ['']*len(args)
     
        app = askTk(args)
        MAIN.win = app
        app.title('')
        app.mainloop()
     
        return DATAS
     
    if __name__ == "__main__":
        a, b, c = ask("a =",
                      "b =",
                      "c =")
     
        print a
        print b
        print c

  8. #8
    Expert éminent

    Homme Profil pro
    Inscrit en
    Octobre 2008
    Messages
    4 301
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations forums :
    Inscription : Octobre 2008
    Messages : 4 301
    Points : 6 781
    Points
    6 781
    Par défaut
    Eh m'sieur, ya rambc qui utilise des globals !


  9. #9
    Membre chevronné

    Profil pro
    Account Manager
    Inscrit en
    Décembre 2006
    Messages
    2 301
    Détails du profil
    Informations personnelles :
    Localisation : France, Savoie (Rhône Alpes)

    Informations professionnelles :
    Activité : Account Manager

    Informations forums :
    Inscription : Décembre 2006
    Messages : 2 301
    Points : 1 752
    Points
    1 752
    Par défaut
    N'en parles pas trop, j'ai trop honte... Ne le dis pas à ma mère, je risque d'être deshérité...

    Plus sérieusement, peut-on s'en passer ?

  10. #10
    Expert éminent

    Homme Profil pro
    Inscrit en
    Octobre 2008
    Messages
    4 301
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations forums :
    Inscription : Octobre 2008
    Messages : 4 301
    Points : 6 781
    Points
    6 781
    Par défaut
    Bien sur on peut s'en passer, c'est même plus facile et plus lisible, je trouve.

    Avec ton dernier code :

    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
     
    #!/usr/bin/env python
    #coding=utf-8
     
    # Source
    #    http://www.developpez.net/forums/d1007391/autres-langages/python-zope/gui/tkinter/debutant-fermer-fenetre-apres-clic-boutton/#post5630766
     
    import sys
     
    try:
        import Tkinter as tkinter
    except:
        import tkinter
     
    class askTk(tkinter.Tk):
        def __init__(self, theTexts, m):
            tkinter.Tk.__init__(self, None)
            self.theText = theTexts
            self.main = m
            self.datas = []
            self.labelVariable = []
            self.entryVariable = []
            self.entry = []
            self.__initialize()
     
        def __initialize(self, *args):
            self.grid()
     
            for i, oneText in enumerate(self.theText):
                # Static text
                self.labelVariable.append(tkinter.StringVar())
                currentLabelVariable = self.labelVariable[i]
     
                label = tkinter.Label(self,
                                      textvariable = currentLabelVariable)
                label.grid(row=i,
                           column=0,
                           sticky=tkinter.E)
     
                currentLabelVariable.set(oneText)
     
                # Entry here the user can give its value
                self.entryVariable.append(tkinter.StringVar())
                currentEntryVariable = self.entryVariable[i]
     
                self.entry.append(tkinter.Entry(self,
                                                textvariable = currentEntryVariable))
                currentEntry = self.entry[i]
                currentEntry.grid(row = i,
                                  column = 1,
                                  sticky='EW')
                # self.entry.bind("<Return>", self.OnPressEnter)
     
                # One Button to say that everything is ok
            button = tkinter.Button(self,
                                    text = "OK",
                                    command = self.OnButtonClick)
            button.grid(row = len(self.theText),
                        column = 0,
                        columnspan = 3)
     
            self.grid_columnconfigure(0,
                                      weight=1)
            self.resizable(False,
                           False)
            self.update()
            self.geometry(self.geometry())
     
            # We want that the cursor is in the first entry.
            self.entry[0].focus_set()
     
        def OnButtonClick(self):
            self.main.datas = [x.get() for x in self.entryVariable]
            self.main.close()
     
    class Main(object):
        def __init__(self):
            self.datas = None
            self.win = None
     
        def ask(self, *args):
            for oneArg in args:
                if not isinstance(oneArg, str):
                    raise ValueError('All the arguments must be strings...')
            self.datas = ['']*len(args)
     
            app = askTk(args, self)
            self.win = app
            app.title('')
            app.mainloop()
            return self.datas
     
        def close(self):
            self.win.destroy()
     
     
     
     
    if __name__ == "__main__":
        main = Main()
        a, b, c = main.ask("a =","b =","c =")
     
        print a
        print b
        print c

  11. #11
    Membre chevronné

    Profil pro
    Account Manager
    Inscrit en
    Décembre 2006
    Messages
    2 301
    Détails du profil
    Informations personnelles :
    Localisation : France, Savoie (Rhône Alpes)

    Informations professionnelles :
    Activité : Account Manager

    Informations forums :
    Inscription : Décembre 2006
    Messages : 2 301
    Points : 1 752
    Points
    1 752
    Par défaut
    Merci. C'est vrai que la classe de l'interface n'est pas détruite contrairement à l'interface.

    Citation Envoyé par VinsS Voir le message
    Bien sur on peut s'en passer, c'est même plus facile et plus lisible, je trouve.
    C'est bien pour cela que j'avais "honte". Je vais demander au webmaster d'effacer le post...

  12. #12
    Expert confirmé Avatar de PauseKawa
    Homme Profil pro
    Technicien Help Desk, maintenance, réseau, système et +
    Inscrit en
    Juin 2006
    Messages
    2 725
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations professionnelles :
    Activité : Technicien Help Desk, maintenance, réseau, système et +
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juin 2006
    Messages : 2 725
    Points : 4 005
    Points
    4 005
    Par défaut
    Je compatis...
    Aller, un petit bout de code de Tkinter.py pour te remonter le moral : global _varnum
    Merci d'utiliser le forum pour les questions techniques.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Réponses: 3
    Dernier message: 14/09/2011, 23h41
  2. Ouvrir une page au milieu d'une autre après un clic sur un bouton
    Par yassineos19 dans le forum Balisage (X)HTML et validation W3C
    Réponses: 1
    Dernier message: 16/08/2011, 12h32
  3. fermer une fenêtre apres l'affichage d'un message
    Par perloutta dans le forum ASP.NET
    Réponses: 8
    Dernier message: 12/05/2009, 09h52
  4. Comment effectuer une redirection après un clic sur un lien
    Par Angelik dans le forum Général JavaScript
    Réponses: 3
    Dernier message: 24/11/2007, 22h13
  5. Fermer une fenêtre après impression
    Par uado dans le forum Général JavaScript
    Réponses: 3
    Dernier message: 22/02/2006, 17h19

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