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

Python Discussion :

Comment modifier (ou récupérer) la valeur de l'attribut d'une classe dans un autre thread ?


Sujet :

Python

  1. #1
    Futur Membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2014
    Messages
    6
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2014
    Messages : 6
    Points : 5
    Points
    5
    Par défaut Comment modifier (ou récupérer) la valeur de l'attribut d'une classe dans un autre thread ?
    Bonjour à vous,

    Je rencontre un problème alors que j'essaye de développer une petite interface GUI (edit : vaut-il mieux le poster dans la partie GUI du forum ?)
    Un code réduit, avec trois Radiobuttons (On, Off, Timer).

    Lorsque je lance mon thread, je souhaiterais que celui-ci ait accès aux attributs, ou aux variables définis dans le main thread qui le lance, dans la class Commandes.

    Je souhaiterais par exemple, pouvoir changer la couleur d'un Radiobutton d'une autre classe au début et à la fin de mon thread, ou pouvoir récupérer la valeur d'un Radiobutton (1, 2, ou 3) pour pouvoir, par exemple, ne pas lancer une commande si jamais ces Radiobuttons sont activés (On ou Off).

    Je souhaite donc avoir une marche forcée (On, Off) et un bouton de confort (Timer) qui me lance une action On pendant un certain temps.
    Du coup, si jamais j'utilise la marche forcée "On" après avoir cliqué sur le Timer (le thread), je ne veux pas que le thread rechange la valeur de mon pin, vu qu'il aura perdu "la priorité".

    Par exemple, voici l'erreur que je rencontre si je souhaite récupérer la valeur de Radioarrosage.
    Exception in thread Thread-1:
    Traceback (most recent call last):
    File "C:\Python27\lib\threading.py", line 810, in __bootstrap_inner
    self.run()
    File "<module1>", line 16, in run
    AttributeError: class Commandes has no attribute 'Radioarrosage'
    Je ne comprends pas pourquoi le message me dit que Commandes n'a pas Radioarrosage pour attribut.
    Comment faire pour ne plus avoir cette erreur ?

    Et voici le code. J'ai commenté les lignes incriminées 16 et 17.
    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
    #!/usr/bin/python
    # -*- coding: iso-8859-1 -*-
    import sys
    from Tkinter import *
    import Tkinter
    import time
    import threading
    ###############################################################################
    class WateringThread(threading.Thread): # Thread pour ne pas freezer l'interface
        def __init__(self):
            threading.Thread.__init__(self)
            self.encore = True
        def run(self):
            print "WateringThread se lance et change la valeur du pin"
            time.sleep(1)
            #if Commandes.Radioarrosage.get() == 3: # si je n'ai pas fait "On" ou "Off"
            #    print "je peux faire passer la pin à 0 et éteindre"
     
        def stop(self):
            print "WateringThread rechange le pin"
            self.encore == False
    ###############################################################################
    class Commandes (Tkinter.Tk):
        def __init__(self):
            Tkinter.Tk.__init__(self)
            self.title("Commandes")
     
            self.Radioarrosage = IntVar()
            self.RadioarrosageOn = Radiobutton(self, text='\non\n',font=('bold'), variable= self.Radioarrosage, value=1, indicatoron =0 ,highlightcolor='blue', background = 'green', activebackground = 'red', command = self.SwitchOnArrosage )
            self.RadioarrosageOff = Radiobutton(self, text='\noff\n',font=('bold'), variable= self.Radioarrosage, value=2, indicatoron =0 ,highlightcolor='blue', background = 'green', activebackground = 'red', command = self.SwitchOffArrosage )
            self.RadioarrosageCinqMin = Radiobutton(self, text='\ntimer\n', font=('bold'),variable=self.Radioarrosage, value=3, indicatoron =0 ,highlightcolor='blue', background = 'green', activebackground = 'red', command = self.SwitchCinqMinArrosage)
            self.RadioarrosageOn.grid(column=6,row=11,columnspan=2,sticky='EW')
            self.RadioarrosageOff.grid(column=8,row=11,columnspan=2,sticky='EW')
            self.RadioarrosageCinqMin.grid(column=10,row=11,columnspan=2,sticky='EW')
     
        def SwitchOnArrosage(self):
            self.RadioarrosageOn.configure(selectcolor='red')
            print self.Radioarrosage.get()
            print "j'allume"
     
        def SwitchOffArrosage(self):
            self.RadioarrosageOff.configure(selectcolor='red')
            print self.Radioarrosage.get()
            print "j'éteins"
     
        def SwitchCinqMinArrosage(self):
            self.RadioarrosageCinqMin.configure(selectcolor='red')
            self.RadioarrosageOn.deselect()
            self.RadioarrosageOff.deselect()
            print self.Radioarrosage.get()
     
            if all(type(i) != WateringThread for i in threading.enumerate()): # si je n'ai pas encore lancé mon thread, je le lance
                WT=WateringThread()
                WT.start()
     
    ###############################################################################
    #if __name__ == '__main__':
    Interface = Commandes()
    Interface.title('Menu')
    Interface.mainloop()
    En vous remerciant pour votre aide.
    Vince

  2. #2
    Expert éminent

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

    Informations forums :
    Inscription : Octobre 2008
    Messages : 4 300
    Points : 6 780
    Points
    6 780
    Par défaut
    Il faut utiliser l'instance de ta classe et non pas elle-même.

    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
     
    >>> class Commandes():
    ...     def __init__(self):
    ...             self.foo = 42
    ... 
    >>> class Baz():
    ...     def __init__(self):
    ...             try:
    ...                     print Commandes.foo
    ...             except AttributeError as why:
    ...                     print why
    ...             print cmd.foo
    ... 
    >>> cmd = Commandes()
    >>> baz = Baz()
    class Commandes has no attribute 'foo'
    42
    >>>

  3. #3
    Futur Membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2014
    Messages
    6
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2014
    Messages : 6
    Points : 5
    Points
    5
    Par défaut
    Bonjour Vinss,

    Merci, effectivement, en mettant Interface plutôt que ma classe elle-même, ça a très bien fonctionné, c'est encourageant ! J'ai également pu changé la couleur des mes Radiobuttons.

    Par contre, quand j'ai essayé de re-inclure ça dans mon code plus général, je n'arrive pas à le faire marcher.
    Je fais une instance de ma classe Commandes à deux reprises. Au début, et je la détruis tout aussi vite, mais c'est pour avoir "cmd" comme instance défini (ligne 209).
    Egalement, sur l'onglet Commandes (ligne 56).

    Lorsque j'essaye de récupérer la valeur depuis mon thread (ligne 30), rien ne se passe. J'imagine que ma manière d'instancer Commandes avec cmd est clairement trop bancale.
    Mais jusque là, je l'avais défini uniquement à la ligne 56, mais si je ne la mets pas à la ligne 209 pour la redétruire, il ne reconnait pas cmd (global name 'cmd' is not defined).
    Ce qui se passe donc actuellement, c'est que je pense que cmd est reconnu, mais détruit. Du coup, rien ne s'affiche à la ligne 30, parce que ca s'est fait destroy. Je me trompe ?
    Comment je peux faire pour l'instancer proprement (lorsque je l'appelle depuis le button "Actions"), et qu'elle soit reconnue de manière à ce que je puisse utiliser l'instance pour gérer ses attributs dans mon thread ?

    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
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    #!/usr/bin/python
    # -*- coding: iso-8859-1 -*-
    import sys
    from Tkinter import *
    import Tkinter
    import time
    import threading
     
    ###############################################################################
    class FoggingThread(threading.Thread):
        def __init__(self):
            threading.Thread.__init__(self)
            self.encore = True
        def run(self):
            print "FoggingThread commence proprement"
            time.sleep(2)
            print "et se termine"
        def stop(self):
            print "FoggingThread  a ete oblige de s'arreter et a rechanger le pin"
            self.encore = False
    ###############################################################################
    class WateringThread(threading.Thread):
        def __init__(self):
            threading.Thread.__init__(self)
            self.encore = True
        def run(self):
            print "WateringThread commence proprement je change le pin"
            time.sleep(1)
     
            if cmd.Radioarrosage.get() == 3: # si je n'ai pas fait "On" ou "Off"
                print "je peux faire passer la pin à 0 et éteindre"
     
            print "WateringThread s'arrete facile et rechange le pin"
            print cmd.Radioarrosage.get()
            print "WateringThread fin de test"
     
        def stop(self):
            print "WateringThread  a ete oblige de s'arreter et a rechanger le pin"
            self.encore == False
    ###############################################################################
    class General(Tkinter.Tk):
        def __init__(self, parent):
            Tkinter.Tk.__init__(self, parent)
            self.parent = parent
            self.title('Menu')
     
            self.grid()
            self.Bouton_Menu1 = Tkinter.Button(self,text='Actions',font=('bold'),fg='black', bg='pink', activebackground='red', command = self.Menu1)
            self.Bouton_Menu1.grid(column=1,row=0, rowspan=1, columnspan=1, sticky='EWNS')
            self.Bouton_Menu2 = Tkinter.Button(self,text='Tools',font=('bold'),fg='black', bg='pink', activebackground='red', command = self.Menu2)
            self.Bouton_Menu2.grid(column=2,row=0, rowspan=1,columnspan=1, sticky='EWNS')
            self.Bouton_Parameters = Tkinter.Button(self,text='Par.',font=('bold'),fg='black', bg='pink', activebackground='red', command = self.Menu3)
            self.Bouton_Parameters.grid(column=3,row=0, sticky='EWNS')
     
        def Menu1(self):
            cmd= Commandes()
            self.destroy()
     
        def Menu2(self):
            Tools()
            self.destroy()
     
        def Menu3(self):
            Parameters()
            self.destroy()
     
    ###############################################################################
    class Commandes (Tkinter.Tk):
        def __init__(self):
            Tkinter.Tk.__init__(self)
            self.title("Commandes")
     
            self.Radioarrosage = IntVar(self)
     
            self.fog = IntVar()
            self.RadiobrumisationOn = Radiobutton(self, text='\n on \n',font=('bold'), variable=self.fog, value=1, indicatoron =0,highlightcolor='blue', background = 'green', activebackground = 'red', command = self.SwitchOnBrumisation)
            self.RadiobrumisationOff = Radiobutton(self, text='\noff\n', font=('bold'),variable=self.fog, value=2, indicatoron =0,highlightcolor='blue', background = 'green', activebackground = 'red', command = self.SwitchOffBrumisation)
            self.RadiobrumisationDeuxMin = Radiobutton(self, text='\ntimer\n',font=('bold'), variable=self.fog, value=3, indicatoron =0,highlightcolor='blue', background = 'green', activebackground = 'red', command = self.SwitchDeuxMinBrumisation)
            self.Bouton_brumisation = Tkinter.Button(self,text='Fogging',font=('bold', 15),fg='black', bg='lightblue', activebackground='red')
            self.Bouton_brumisation.grid(column=0,row=10,columnspan=6, sticky='EW')
            self.RadiobrumisationOn.grid(column=0,row=11,columnspan=2,sticky='EW')
            self.RadiobrumisationOff.grid(column=2,row=11,columnspan=2,sticky='EW')
            self.RadiobrumisationDeuxMin.grid(column=4,row=11, columnspan=2,sticky='EW')
     
            self.RadioarrosageOn = Radiobutton(self, text='\non\n',font=('bold'), variable= self.Radioarrosage, value=1, indicatoron =0 ,highlightcolor='blue', background = 'green', activebackground = 'red', command = self.SwitchOnArrosage )
            self.RadioarrosageOff = Radiobutton(self, text='\noff\n',font=('bold'), variable= self.Radioarrosage, value=2, indicatoron =0 ,highlightcolor='blue', background = 'green', activebackground = 'red', command = self.SwitchOffArrosage )
            self.RadioarrosageCinqMin = Radiobutton(self, text='\ntimer\n', font=('bold'),variable= self.Radioarrosage, value=3, indicatoron =0 ,highlightcolor='blue', background = 'green', activebackground = 'red', command = self.SwitchCinqMinArrosage)
     
            self.Bouton_arrosage = Tkinter.Button(self,text='Watering',font=('bold', 15),fg='white', bg='darkblue', activebackground='red')
            self.Bouton_arrosage.grid(column=6,row=10,columnspan=6, sticky='EW')
            self.RadioarrosageOn.grid(column=6,row=11,columnspan=2,sticky='EW')
            self.RadioarrosageOff.grid(column=8,row=11,columnspan=2,sticky='EW')
            self.RadioarrosageCinqMin.grid(column=10,row=11,columnspan=2,sticky='EW')
     
            self.Bouton_Back1 = Tkinter.Button(self,text='BACK',font=('bold', 11),fg='white', bg='red', activebackground='red', command= self.back1)
            self.Bouton_Back1.grid(column=6,row=13, rowspan=3, columnspan = 6, sticky='EWN')
     
        def back1(self):
            General(None)
            self.destroy()
     
        def SwitchOnBrumisation(self):
            self.RadiobrumisationOn.configure(selectcolor='red')
            self.Bouton_brumisation.configure(bg='red')
        def SwitchOffBrumisation(self):
            self.RadiobrumisationOff.configure(selectcolor='red')
            self.Bouton_brumisation.configure(bg='red')
        def SwitchDeuxMinBrumisation(self):
            self.RadiobrumisationDeuxMin.configure(selectcolor='red')
            self.Bouton_brumisation.configure(bg='red')
            self.RadiobrumisationOn.deselect()
            self.RadiobrumisationOff.deselect()
     
            if all(type(i) != FoggingThread for i in threading.enumerate()):
                FT=FoggingThread()
                FT.start()
     
            #print self.fog.get()
     
        def SwitchOnArrosage(self):
            self.RadioarrosageOn.configure(selectcolor='red')
            self.Bouton_arrosage.configure(bg='red', fg='black')
            print self.Radioarrosage.get()
     
        def SwitchOffArrosage(self):
            self.RadioarrosageOff.configure(selectcolor='red')
            self.Bouton_arrosage.configure(bg='red',fg='black')
            print self.Radioarrosage.get()
     
        def SwitchCinqMinArrosage(self):
            self.RadioarrosageCinqMin.configure(selectcolor='red')
            self.Bouton_arrosage.configure(bg='red',fg='black')
            self.RadioarrosageOn.deselect()
            self.RadioarrosageOff.deselect()
            #print self.Radioarrosage.get()
     
            if all(type(i) != WateringThread for i in threading.enumerate()):
                WT=WateringThread()
                WT.start()
     
    ###############################################################################
    class Tools (Tkinter.Tk):
        def __init__(self):
            Tkinter.Tk.__init__(self)
            self.title("Tools")
     
            self.Led = IntVar(self)
            self.RadioLedsOn = Radiobutton(self, text='\non\n', font=('bold'), variable=self.Led, value=1, indicatoron =0 ,highlightcolor='blue', background = 'green', activebackground = 'red' )
            self.RadioLedsOff = Radiobutton(self, text='\noff\n', font=('bold'),variable=self.Led, value=2, indicatoron =0,highlightcolor='blue', background = 'green', activebackground = 'red' )
            self.Bouton_Leds = Tkinter.Button(self,text='\nLeds\n',fg='black', font=('bold', 10),bg='yellow', activebackground='red')
            self.Bouton_Leds.grid(column=0,row=0,columnspan=2, sticky='EWNS')
            self.RadioLedsOn.grid(column=0,row=1,sticky='EWNS')
            self.RadioLedsOff.grid(column=1,row=1,sticky='EWNS')
     
            self.Bouton_Back2 = Tkinter.Button(self,text='\nBACK\n',fg='white',font=('bold', 10), bg='red', activebackground='red', command= self.back2)
            self.Bouton_Back2.grid(column=10,row=3,rowspan=4,columnspan = 3, sticky='EWN')
     
        def back2(self):
            General(None)
            self.destroy()
     
        def SwitchOnLeds(self):
            self.RadioLedsOn.configure(selectcolor='red')
            self.Bouton_Leds.configure(bg='red')
     
        def StopLeds (self):
            self.RadioLedsOn.deselect()
            self.RadioLedsOff.deselect()
            self.Bouton_Leds.configure(bg='yellow')
     
    ###############################################################################
    ###############################################################################
    ###############################################################################
    ###############################################################################
    class Parameters (Tkinter.Tk):
        def __init__(self):
            Tkinter.Tk.__init__(self)
            self.title("Parameters")
     
            self.ValeurHourOn = StringVar(self)
            self.ValeurHourOn.set(2)
     
            self.SpinValeurHourOn = StringVar(self)
            self.SpinValeurHourOn.set('10')
     
            self.HourOn = StringVar(self)
            self.HourOn.set("Time On\n"+str(self.ValeurHourOn.get())+'h')
     
            self.LabelHourOn=Label(self,textvariable= self.HourOn, bg='yellow').grid(column=0,row=0,columnspan=2, sticky='EW')
            self.boiteHourOn = Spinbox(self,from_=0.10,to=23.50,increment=0.10,font=('bold', 13),textvariable=self.SpinValeurHourOn,width=5)
            self.boiteHourOn.grid(column=0,row=1,columnspan=1, rowspan = 2, sticky='EW')
            self.Bouton_ValidHourOn = Button(self,text='ok',font=('bold'),fg='black', bg='white', activebackground='red', command = self.HorairesOn)
            self.Bouton_ValidHourOn.grid(column=1,row=1, sticky='EWS',rowspan = 2)
     
            self.Bouton_Back3 = Tkinter.Button(self,text='Back',fg='white', bg='red',font=('bold',14), activebackground='red', command= self.back3)
            self.Bouton_Back3.grid(column=0,row=9,rowspan=2, columnspan = 8, sticky='EWN')
     
        def HorairesOn(self):
            self.HourOn.set("Time On\n"+str(self.SpinValeurHourOn.get())+'h')
     
        def back3(self):
            General(None)
            self.destroy()
    ###############################################################################
    #if __name__ == '__main__':
     
    Interface = General(None)
    Interface.title('Menu')
    cmd = Commandes()
    cmd.destroy()
     
    Interface.mainloop()

  4. #4
    Expert éminent

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

    Informations forums :
    Inscription : Octobre 2008
    Messages : 4 300
    Points : 6 780
    Points
    6 780
    Par défaut
    Lorsque tu crées une interface principale qui sera la "mainloop", tu ne peux pas la détruire en cours d'exécution, mais uniquement à la sortie du programme.

    Il faut impérativement conserver une référence d'une fenêtre que tu crées séparément, sans quoi Python la détruit aussitôt sortit de la fonction.
    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
     
    class General(Tkinter.Tk):
        def __init__(self, parent):
            Tkinter.Tk.__init__(self, parent)
            self.parent = parent
            self.title('Menu')
     
            ....
     
        def Menu1(self):
            cmd= Commandes()    # Conserver une référence: self.cmd = Commandes()
            self.destroy()      # Ne pas détruire !
     
        def Menu2(self):
            Tools()             # Conserver une référence: self.tools = Tools()
            self.destroy()      # Ne pas détruire !
     
        def Menu3(self):
            Parameters()        # Conserver une référence: self.param = Parameters()
            self.destroy()      # Ne pas détruire !
    Donc pour sortir de la fenêtre Commandes ou Tools ou Parameters, il ne faut pas recréer de fenêtre principale.

    Cela dit, pourquoi faut-il des fenêtres séparées ? TKinter n'a pas de barre de menu ?

  5. #5
    Futur Membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2014
    Messages
    6
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2014
    Messages : 6
    Points : 5
    Points
    5
    Par défaut
    EDIT : en fait, il vaut peut-être mieux que je ne conserve que trois classes. La principale, et les deux Threads, non ? Ainsi, je n'aurais plus de problèmes de référence, et je détruis ou forget les Radiobuttons au fur et à mesure

    Edit bis : cela fonctionne, j'ai changé mes classes en fonctions. J'ai initialisé tous mes bouttons au début. Et je les appelle avec .grid dans mes fonctions Commandes, Tools, Parameters. Lorsque je re-vais au menu principal, je les grid_remove(). Grand merci VinsS. Ainsi, je peux facilement changer la couleur de mes bouttons dans mon thread, et récupérer la valeur de la variable si besoin .

    Citation Envoyé par VinsS Voir le message
    Lorsque tu crées une interface principale qui sera la "mainloop", tu ne peux pas la détruire en cours d'exécution, mais uniquement à la sortie du programme.
    Ok, j'enlève donc tous les self.destroy.
    Il faut impérativement conserver une référence d'une fenêtre que tu crées séparément, sans quoi Python la détruit aussitôt sortit de la fonction.
    Avec cette écriture, le souci est que le nom de mon instance est locale. Donc, self.Cmd n'est pas reconnu lorsque je le lance dans le thread. Je n'arrive pas à voir commander faire une instance de Commandes sans pour autant créer le fenêtre.

    Par ailleurs, je recrée une fenêtre, alors que je souhaiterais soit conserver la même, soit que l'ancienne disparaisse, sinon, elles s'accumulent.

    Donc pour sortir de la fenêtre Commandes ou Tools ou Parameters, il ne faut pas recréer de fenêtre principale.

    Cela dit, pourquoi faut-il des fenêtres séparées ? TKinter n'a pas de barre de menu ?
    En fait, effectivement, c'est un Menu que je souhaite faire. Du coup, j'essaye d'effacer la fenêtre précédente lorsque je navigue, d'où les self.destroy.

    En fait, ce code est pour une petite interface qui va rentrer sur un écran tactile 320x240 pour un Raspberry. Donc, je me suis fait un accueil avec les valeurs des capteurs, les Commandes et Tools pour gérer des appareils, Parameters pour changer les dits paramètres, et un dernier onglet pour afficher le graphe des capteurs sous 24 heures. Une station météo pour monitorer un terrarium en somme.
    Donc, si les onglets sont les plus gros possibles, c'est plus facile à gérer par la suite pour les doigts. Je me disais donc que si je pouvais avoir chaque fenêtre comprenant de gros Widgets, cela serait plus ergonomique.
    Mais j'ai l'impression que cela va être difficile avec mon Thread, non ?

    Car, avec ce code, je n'arrive toujours pas à jouer avec l'attribut de l'instance Cmd de commandes, et je ne suis pas capable de me séparer de l'ancienne fenêtre lorsque je navigue parmi mes onglets .

    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
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    #!/usr/bin/python
    # -*- coding: iso-8859-1 -*-
    import sys
    from Tkinter import *
    import Tkinter
    import time
    import threading
     
    ###############################################################################
    class FoggingThread(threading.Thread):
        def __init__(self):
            threading.Thread.__init__(self)
            self.encore = True
        def run(self):
            print "FoggingThread commence proprement"
            time.sleep(2)
            print "et se termine"
        def stop(self):
            print "FoggingThread  a ete oblige de s'arreter et a rechanger le pin"
            self.encore = False
    ###############################################################################
    class WateringThread(threading.Thread):
        def __init__(self):
            threading.Thread.__init__(self)
            self.encore = True
        def run(self):
            print "WateringThread commence proprement je change le pin"
            time.sleep(1)
     
            if Cmd.Radioarrosage.get() == 3: # si je n'ai pas fait "On" ou "Off" # self.Cmd renverrait à WateringThread, et Cmd n'est pas défini comme variable globale
                print "je peux faire passer la pin à 0 et éteindre"
     
            print "WateringThread s'arrete facile et rechange le pin"
            #print cmd.Radioarrosage.get()
            print "WateringThread fin de test"
     
        def stop(self):
            print "WateringThread  a ete oblige de s'arreter et a rechanger le pin"
            self.encore == False
    ###############################################################################
    class General(Tkinter.Tk):
        def __init__(self, parent):
            Tkinter.Tk.__init__(self, parent)
            self.parent = parent
            self.title('Menu')
     
            self.grid()
            self.Bouton_Menu1 = Tkinter.Button(self,text='Actions',font=('bold'),fg='black', bg='pink', activebackground='red', command = self.Menu1)
            self.Bouton_Menu1.grid(column=1,row=0, rowspan=1, columnspan=1, sticky='EWNS')
            self.Bouton_Menu2 = Tkinter.Button(self,text='Tools',font=('bold'),fg='black', bg='pink', activebackground='red', command = self.Menu2)
            self.Bouton_Menu2.grid(column=2,row=0, rowspan=1,columnspan=1, sticky='EWNS')
            self.Bouton_Parameters = Tkinter.Button(self,text='Par.',font=('bold'),fg='black', bg='pink', activebackground='red', command = self.Menu3)
            self.Bouton_Parameters.grid(column=3,row=0, sticky='EWNS')
     
        def Menu1(self):
            self.Cmd= Commandes()
            #self.destroy()
     
        def Menu2(self):
            self.Outils = Tools()
            #self.destroy()
     
        def Menu3(self):
            self.Par = Parameters()
            #self.destroy()
     
    ###############################################################################
    class Commandes (Tkinter.Tk):
        def __init__(self):
            Tkinter.Tk.__init__(self)
            self.title("Commandes")
     
            self.Radioarrosage = IntVar(self)
     
            self.fog = IntVar()
            self.RadiobrumisationOn = Radiobutton(self, text='\n on \n',font=('bold'), variable=self.fog, value=1, indicatoron =0,highlightcolor='blue', background = 'green', activebackground = 'red', command = self.SwitchOnBrumisation)
            self.RadiobrumisationOff = Radiobutton(self, text='\noff\n', font=('bold'),variable=self.fog, value=2, indicatoron =0,highlightcolor='blue', background = 'green', activebackground = 'red', command = self.SwitchOffBrumisation)
            self.RadiobrumisationDeuxMin = Radiobutton(self, text='\ntimer\n',font=('bold'), variable=self.fog, value=3, indicatoron =0,highlightcolor='blue', background = 'green', activebackground = 'red', command = self.SwitchDeuxMinBrumisation)
            self.Bouton_brumisation = Tkinter.Button(self,text='Fogging',font=('bold', 15),fg='black', bg='lightblue', activebackground='red')
            self.Bouton_brumisation.grid(column=0,row=10,columnspan=6, sticky='EW')
            self.RadiobrumisationOn.grid(column=0,row=11,columnspan=2,sticky='EW')
            self.RadiobrumisationOff.grid(column=2,row=11,columnspan=2,sticky='EW')
            self.RadiobrumisationDeuxMin.grid(column=4,row=11, columnspan=2,sticky='EW')
     
            self.RadioarrosageOn = Radiobutton(self, text='\non\n',font=('bold'), variable= self.Radioarrosage, value=1, indicatoron =0 ,highlightcolor='blue', background = 'green', activebackground = 'red', command = self.SwitchOnArrosage )
            self.RadioarrosageOff = Radiobutton(self, text='\noff\n',font=('bold'), variable= self.Radioarrosage, value=2, indicatoron =0 ,highlightcolor='blue', background = 'green', activebackground = 'red', command = self.SwitchOffArrosage )
            self.RadioarrosageCinqMin = Radiobutton(self, text='\ntimer\n', font=('bold'),variable= self.Radioarrosage, value=3, indicatoron =0 ,highlightcolor='blue', background = 'green', activebackground = 'red', command = self.SwitchCinqMinArrosage)
     
            self.Bouton_arrosage = Tkinter.Button(self,text='Watering',font=('bold', 15),fg='white', bg='darkblue', activebackground='red')
            self.Bouton_arrosage.grid(column=6,row=10,columnspan=6, sticky='EW')
            self.RadioarrosageOn.grid(column=6,row=11,columnspan=2,sticky='EW')
            self.RadioarrosageOff.grid(column=8,row=11,columnspan=2,sticky='EW')
            self.RadioarrosageCinqMin.grid(column=10,row=11,columnspan=2,sticky='EW')
     
            self.Bouton_Back1 = Tkinter.Button(self,text='BACK',font=('bold', 11),fg='white', bg='red', activebackground='red', command= self.back1)
            self.Bouton_Back1.grid(column=6,row=13, rowspan=3, columnspan = 6, sticky='EWN')
     
        def back1(self):
            Interface = General(None)
            #self.destroy()
     
        def SwitchOnBrumisation(self):
            self.RadiobrumisationOn.configure(selectcolor='red')
            self.Bouton_brumisation.configure(bg='red')
        def SwitchOffBrumisation(self):
            self.RadiobrumisationOff.configure(selectcolor='red')
            self.Bouton_brumisation.configure(bg='red')
        def SwitchDeuxMinBrumisation(self):
            self.RadiobrumisationDeuxMin.configure(selectcolor='red')
            self.Bouton_brumisation.configure(bg='red')
            self.RadiobrumisationOn.deselect()
            self.RadiobrumisationOff.deselect()
     
            if all(type(i) != FoggingThread for i in threading.enumerate()):
                FT=FoggingThread()
                FT.start()
     
            #print self.fog.get()
     
        def SwitchOnArrosage(self):
            self.RadioarrosageOn.configure(selectcolor='red')
            self.Bouton_arrosage.configure(bg='red', fg='black')
            print self.Radioarrosage.get()
     
        def SwitchOffArrosage(self):
            self.RadioarrosageOff.configure(selectcolor='red')
            self.Bouton_arrosage.configure(bg='red',fg='black')
            print self.Radioarrosage.get()
     
        def SwitchCinqMinArrosage(self):
            self.RadioarrosageCinqMin.configure(selectcolor='red')
            self.Bouton_arrosage.configure(bg='red',fg='black')
            self.RadioarrosageOn.deselect()
            self.RadioarrosageOff.deselect()
            #print self.Radioarrosage.get()
     
            if all(type(i) != WateringThread for i in threading.enumerate()):
                WT=WateringThread()
                WT.start()
     
    ###############################################################################
    class Tools (Tkinter.Tk):
        def __init__(self):
            Tkinter.Tk.__init__(self)
            self.title("Tools")
     
            self.Led = IntVar(self)
            self.RadioLedsOn = Radiobutton(self, text='\non\n', font=('bold'), variable=self.Led, value=1, indicatoron =0 ,highlightcolor='blue', background = 'green', activebackground = 'red' )
            self.RadioLedsOff = Radiobutton(self, text='\noff\n', font=('bold'),variable=self.Led, value=2, indicatoron =0,highlightcolor='blue', background = 'green', activebackground = 'red' )
            self.Bouton_Leds = Tkinter.Button(self,text='\nLeds\n',fg='black', font=('bold', 10),bg='yellow', activebackground='red')
            self.Bouton_Leds.grid(column=0,row=0,columnspan=2, sticky='EWNS')
            self.RadioLedsOn.grid(column=0,row=1,sticky='EWNS')
            self.RadioLedsOff.grid(column=1,row=1,sticky='EWNS')
     
            self.Bouton_Back2 = Tkinter.Button(self,text='\nBACK\n',fg='white',font=('bold', 10), bg='red', activebackground='red', command= self.back2)
            self.Bouton_Back2.grid(column=10,row=3,rowspan=4,columnspan = 3, sticky='EWN')
     
        def back2(self):
            Interface = General(None)
            #self.destroy()
     
        def SwitchOnLeds(self):
            self.RadioLedsOn.configure(selectcolor='red')
            self.Bouton_Leds.configure(bg='red')
     
        def StopLeds (self):
            self.RadioLedsOn.deselect()
            self.RadioLedsOff.deselect()
            self.Bouton_Leds.configure(bg='yellow')
     
    ###############################################################################
    ###############################################################################
    ###############################################################################
    ###############################################################################
    class Parameters (Tkinter.Tk):
        def __init__(self):
            Tkinter.Tk.__init__(self)
            self.title("Parameters")
     
            self.ValeurHourOn = StringVar(self)
            self.ValeurHourOn.set(2)
     
            self.SpinValeurHourOn = StringVar(self)
            self.SpinValeurHourOn.set('10')
     
            self.HourOn = StringVar(self)
            self.HourOn.set("Time On\n"+str(self.ValeurHourOn.get())+'h')
     
            self.LabelHourOn=Label(self,textvariable= self.HourOn, bg='yellow').grid(column=0,row=0,columnspan=2, sticky='EW')
            self.boiteHourOn = Spinbox(self,from_=0.10,to=23.50,increment=0.10,font=('bold', 13),textvariable=self.SpinValeurHourOn,width=5)
            self.boiteHourOn.grid(column=0,row=1,columnspan=1, rowspan = 2, sticky='EW')
            self.Bouton_ValidHourOn = Button(self,text='ok',font=('bold'),fg='black', bg='white', activebackground='red', command = self.HorairesOn)
            self.Bouton_ValidHourOn.grid(column=1,row=1, sticky='EWS',rowspan = 2)
     
            self.Bouton_Back3 = Tkinter.Button(self,text='Back',fg='white', bg='red',font=('bold',14), activebackground='red', command= self.back3)
            self.Bouton_Back3.grid(column=0,row=9,rowspan=2, columnspan = 8, sticky='EWN')
     
        def HorairesOn(self):
            self.HourOn.set("Time On\n"+str(self.SpinValeurHourOn.get())+'h')
     
        def back3(self):
            Interface = General(None)
            #self.destroy()
    ###############################################################################
    #if __name__ == '__main__':
     
    Interface = General(None)
    Interface.title('Menu')
    Interface.mainloop()

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

Discussions similaires

  1. Récupérer la valeur d'un attribut d'une balise séléctionnée par Spinner
    Par kamclasse dans le forum Composants graphiques
    Réponses: 5
    Dernier message: 16/12/2014, 13h14
  2. passer la valeur d'un attribut a une classe
    Par filor dans le forum Débuter avec Java
    Réponses: 2
    Dernier message: 18/04/2009, 00h04
  3. Réponses: 4
    Dernier message: 21/03/2009, 14h13
  4. Réponses: 7
    Dernier message: 27/11/2007, 17h05
  5. Réponses: 2
    Dernier message: 24/01/2007, 15h05

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