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 :

if '*' or '/' in (E1.get() or E2.get() or E3.get()) [Python 2.X]


Sujet :

Tkinter Python

  1. #1
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Juillet 2014
    Messages
    23
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France, Gironde (Aquitaine)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juillet 2014
    Messages : 23
    Points : 15
    Points
    15
    Par défaut if '*' or '/' in (E1.get() or E2.get() or E3.get())
    Bonjour,

    Je me demande , une fois mon programme lancé, lorsque j'appuie seulement sur le bouton 'ok', pourquoi le programme lance la fonction multDiv() puisque je n'ai pas mis ni un '*' ni un '/' dans les entry.
    Quelque chose m'échappe.

    Voici mon 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
    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
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
     
    from Tkinter import *
    from math import *
     
    def dispatch_yview (*args):
        """
            cette fonction dispatche les commandes de la scrollbar
            VERTICALE entre les deux canevas;
        """
        canvas.yview(*args)
        canvas2.yview(*args)
    # end def
     
    def multDiv(a,b,c):
        if '*' in (E1.get() or E2.get() or E3.get()):
            print 'mult'
        elif '/' in (E1.get() or E2.get() or E3.get()) :
            print 'div'
        else:
            print '?'
     
     
    def ok():
        with open("matrice.txt") as inf:
            lines = inf.readlines()
     
        roundval = E4.get()
        print E1.get()
        print E2.get()
        print E3.get()
        if '*' or '/' in (E1.get() or E2.get() or E3.get()):
            multDiv(E1.get(), E2.get(), E3.get())
        else:
            entries = [float(E1.get()), float(E2.get()), float(E3.get())]
            news = ""
            for line in lines:
                vals = line.strip().replace('[','').replace(']','').split(',')
                new = []
                for i, j in zip(vals, entries):
                    s = float(i) + j
                    if roundval :
                        s = round(s, int(roundval))
     
                    new.append(s)
     
                news = news + str(new) + '\n'
     
            with open('matrice2.txt','w') as outf:
                outf.write(news)
     
            canvas2.itemconfig(c2,text=news)
            L.config(text="Finished !")
     
    # Création de fenêtre
    root = Tk()
    root.rowconfigure(0, weight=1)
    root.columnconfigure(0, weight=1)
    root.title("coordinate change")
     
    # Label, Entry
    L=Label(root,text='This program allows to increase or decrease one of the coordinates (X, Y or Z) of a [X,Y,Z] matrice such as: \n [15,1.454,0.1]\n[12.1,5.2,78]\n[0.3,0,45]\n(...)\n\n Please copy your matrice in a file whose the name is matrice.txt.\nPut the file in the same directory than this program. The new matrice will be in the file named matrice2.txt.',font=('Arial',17,'bold'))
    L.grid()
     
    L1=Label(root,text='Give the value(s)',font=('Helvetica',15,'underline'))
    L1.grid(column=1)
     
    LX=Label(root,text='X',font=('Helvetica',15,'underline'))
    LX.grid(row=2)
     
    E1=Entry(root)
    E1.grid(row=2,column=1)
    E1.insert(0,0)
     
    LY=Label(root,text='Y',font=('Helvetica',15,'underline'))
    LY.grid()
     
    E2=Entry(root)
    E2.grid(row=3,column=1)
    E2.insert(0,0)
     
    LZ=Label(root,text='Z',font=('Helvetica',15,'underline'))
    LZ.grid()
     
    E3=Entry(root)
    E3.grid(row=4,column=1)
    E3.insert(0,0)
     
    L2=Label(root,text='Contenu de matrice.txt :',font=('Helvetica',15,'underline'))
    L2.grid(row=6,column=0,columnspan=2)
     
    with open("matrice.txt") as inf:
        lines = inf.readlines()
     
    canvas = Canvas(root, bg="white")
    canvas.grid(row=7, column=0, sticky=NW+SE)
    list=canvas.create_text(0,0, text=lines, font="sans 16 bold", fill="blue",anchor='nw')
     
     
    # horizontal scrollbar
    hbar = Scrollbar(root, orient=HORIZONTAL)
    hbar.grid(row=8, column=0, sticky=NW+SE)
    # vertical scrollbar pour les 2
    vbar = Scrollbar(root, orient=VERTICAL)
    vbar.grid(row=7, column=3, sticky=W+N+S)
    # connecting people...
    canvas.configure(
        xscrollcommand=hbar.set,
        yscrollcommand=vbar.set,
        scrollregion=(0, 0, 800, 600),
    )
    hbar.configure(command=canvas.xview)
    vbar.configure(command=canvas.yview)
     
    L2=Label(root,text='Contenu de matrice2.txt :',font=('Helvetica',15,'underline'))
    L2.grid(row=6,column=2,columnspan=2)
     
    canvas2 = Canvas(root, bg="white")
    c2=canvas2.create_text(0,0, text='', font="sans 16 bold", fill="blue",anchor='nw')
    canvas2.grid(row=7, column=2, sticky=NW+SE)
     
    # horizontal scrollbar
    hbar = Scrollbar(root, orient=HORIZONTAL)
    hbar.grid(row=8, column=2, sticky=NW+SE)
     
    # connecting people...
    canvas2.configure(
        xscrollcommand=hbar.set,
        yscrollcommand=vbar.set,
        scrollregion=(0, 0, 800, 600),
    )
    hbar.configure(command=canvas2.xview)
    vbar.configure(command=canvas2.yview)
     
    # special dispatch between 2 canvases
    vbar.configure(command=dispatch_yview)
     
    B=Button(root,text='OK',width=25,command=ok)
    B.grid(row=4,column=2,columnspan=2)
     
    L5=Label(root,text='Voulez-vous arrondir ? Si oui, mettez le nombre de chiffres après la virgule que vous souhaitez faire apparaître :')
    L5.grid(row=5)
     
    E4=Entry(root)
    E4.grid(row=5,column=1)
     
    root.mainloop()
    merci.

  2. #2
    Invité
    Invité(e)
    Par défaut
    Citation Envoyé par adrbessy Voir le message
    Bonjour,

    Je me demande , une fois mon programme lancé, lorsque j'appuie seulement sur le bouton 'ok', pourquoi le programme lance la fonction multDiv() puisque je n'ai pas mis ni un '*' ni un '/' dans les entry.
    Quelque chose m'échappe.
    merci.
    Bonjour,

    Le mieux en cas de doute, c'est encore de lancer une console Python pour tester ce que l'on a écrit.

    Dans votre fonction ok(), vous avez écrit ligne 33 :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
        if '*' or '/' in (E1.get() or E2.get() or E3.get()):
            multDiv(E1.get(), E2.get(), E3.get())
    Vous dites qu'il y a appel intempestif de multDiv(), voyons donc ce que l'évaluation de if '*' or '/' in (E1.get() or E2.get() or E3.get()): nous donne.

    Ouvrez une console Python, puis essayez ceci :

    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
    >>> ('x' or 'y' or 'z')
    'x'
    >>> '/' in 'x'
    False
    >>> '*' or '/' in ('x' or 'y' or 'z')
    '*'
    >>> ('*' or '/') in ('x', 'y', 'z')
    False
    >>> ('*' or '/')
    '*'
    >>> ('*', '/') in ('x', '*', '/')
    False
    >>> any(['*' in 'xyz', '/' in 'xyz'])
    False
    >>> any(['*' in 'xy*', '/' in 'xy*'])
    True
    >>> any(['*' in 'x/y', '/' in 'x/y'])
    True
    Pour finir, n'hésitez pas à (re)lire : https://docs.python.org/3/library/st...ml#comparisons

    @+.

  3. #3
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Juillet 2014
    Messages
    23
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France, Gironde (Aquitaine)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juillet 2014
    Messages : 23
    Points : 15
    Points
    15
    Par défaut
    Merci, je ne connaissais pas le any() !

    Voici mon 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
    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
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
     
    from Tkinter import *
    from math import *
     
    def dispatch_yview (*args):
        """
            cette fonction dispatche les commandes de la scrollbar
            VERTICALE entre les deux canevas;
        """
        canvas.yview(*args)
        canvas2.yview(*args)
    # end def
     
    def multDiv(a,b,c):
        if any(['*' in E1.get(),'*' in E2.get(),'*' in E3.get()]):
            print 'mult'
        if any(['/' in E1.get(),'/' in E2.get(),'/' in E3.get()]):
            print 'div'
     
     
    def ok():
        with open("matrice.txt") as inf:
            lines = inf.readlines()
     
        roundval = E4.get()
        print E1.get()
        print E2.get()
        print E3.get()
        if any(['*' in E1.get(),'*' in E2.get(),'*' in E3.get(),'/' in E1.get(),'/' in E2.get(),'/' in E3.get()]):
            multDiv(E1.get(), E2.get(), E3.get())
        else:
            entries = [float(E1.get()), float(E2.get()), float(E3.get())]
            news = ""
            for line in lines:
                vals = line.strip().replace('[','').replace(']','').split(',')
                new = []
                for i, j in zip(vals, entries):
                    s = float(i) + j
                    if roundval :
                        s = round(s, int(roundval))
     
                    new.append(s)
     
                news = news + str(new) + '\n'
     
            with open('matrice2.txt','w') as outf:
                outf.write(news)
     
            canvas2.itemconfig(c2,text=news)
            L.config(text="Finished !")
     
    # Création de fenêtre
    root = Tk()
    root.rowconfigure(0, weight=1)
    root.columnconfigure(0, weight=1)
    root.title("coordinate change")
     
    # Label, Entry
    L=Label(root,text='This program allows to increase or decrease one of the coordinates (X, Y or Z) of a [X,Y,Z] matrice such as: \n [15,1.454,0.1]\n[12.1,5.2,78]\n[0.3,0,45]\n(...)\n\n Please copy your matrice in a file whose the name is matrice.txt.\nPut the file in the same directory than this program. The new matrice will be in the file named matrice2.txt.',font=('Arial',17,'bold'))
    L.grid()
     
    L1=Label(root,text='Give the value(s)',font=('Helvetica',15,'underline'))
    L1.grid(column=1)
     
    LX=Label(root,text='X',font=('Helvetica',15,'underline'))
    LX.grid(row=2)
     
    E1=Entry(root)
    E1.grid(row=2,column=1)
    E1.insert(0,0)
     
    LY=Label(root,text='Y',font=('Helvetica',15,'underline'))
    LY.grid()
     
    E2=Entry(root)
    E2.grid(row=3,column=1)
    E2.insert(0,0)
     
    LZ=Label(root,text='Z',font=('Helvetica',15,'underline'))
    LZ.grid()
     
    E3=Entry(root)
    E3.grid(row=4,column=1)
    E3.insert(0,0)
     
    L2=Label(root,text='Contenu de matrice.txt :',font=('Helvetica',15,'underline'))
    L2.grid(row=6,column=0,columnspan=2)
     
    with open("matrice.txt") as inf:
        lines = inf.readlines()
     
    canvas = Canvas(root, bg="white")
    canvas.grid(row=7, column=0, sticky=NW+SE)
    list=canvas.create_text(0,0, text=lines, font="sans 16 bold", fill="blue",anchor='nw')
     
     
    # horizontal scrollbar
    hbar = Scrollbar(root, orient=HORIZONTAL)
    hbar.grid(row=8, column=0, sticky=NW+SE)
    # vertical scrollbar pour les 2
    vbar = Scrollbar(root, orient=VERTICAL)
    vbar.grid(row=7, column=3, sticky=W+N+S)
    # connecting people...
    canvas.configure(
        xscrollcommand=hbar.set,
        yscrollcommand=vbar.set,
        scrollregion=(0, 0, 800, 600),
    )
    hbar.configure(command=canvas.xview)
    vbar.configure(command=canvas.yview)
     
    L2=Label(root,text='Contenu de matrice2.txt :',font=('Helvetica',15,'underline'))
    L2.grid(row=6,column=2,columnspan=2)
     
    canvas2 = Canvas(root, bg="white")
    c2=canvas2.create_text(0,0, text='', font="sans 16 bold", fill="blue",anchor='nw')
    canvas2.grid(row=7, column=2, sticky=NW+SE)
     
    # horizontal scrollbar
    hbar = Scrollbar(root, orient=HORIZONTAL)
    hbar.grid(row=8, column=2, sticky=NW+SE)
     
    # connecting people...
    canvas2.configure(
        xscrollcommand=hbar.set,
        yscrollcommand=vbar.set,
        scrollregion=(0, 0, 800, 600),
    )
    hbar.configure(command=canvas2.xview)
    vbar.configure(command=canvas2.yview)
     
    # special dispatch between 2 canvases
    vbar.configure(command=dispatch_yview)
     
    B=Button(root,text='OK',width=25,command=ok)
    B.grid(row=4,column=2,columnspan=2)
     
    L5=Label(root,text='Voulez-vous arrondir ? Si oui, mettez le nombre de chiffres après la virgule que vous souhaitez faire apparaître :')
    L5.grid(row=5)
     
    E4=Entry(root)
    E4.grid(row=5,column=1)
     
    root.mainloop()

  4. #4
    Invité
    Invité(e)
    Par défaut
    Citation Envoyé par adrbessy Voir le message
    Merci, je ne connaissais pas le any() !
    C'était un peu le but !

    En temps normal, pour deux cas seulement, on se contente de remplacer le any(iterable) par if '*' in seq or '/' in seq:, mais c'est vrai qu'à partir de 3 expressions on commencera à préférer utiliser any([expr1, expr2, expr3, ..., exprN]).

    Bon à savoir : any([expr1, expr2, expr3, ..., exprN]) correspond à expr1 or expr2 or expr3 or ... or exprN https://docs.python.org/3/library/functions.html#any

    alors que all([expr1, expr2, expr3, ..., exprN]) correspond à expr1 and expr2 and expr3 and ... and exprN https://docs.python.org/3/library/functions.html#all

    @+.

  5. #5
    Invité
    Invité(e)
    Par défaut
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    if any(['*' in E1.get(),'*' in E2.get(),'*' in E3.get(),'/' in E1.get(),'/' in E2.get(),'/' in E3.get()]):
            multDiv(E1.get(), E2.get(), E3.get())
    Vive l'optimisation de code, hein !

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    seq = E1.get() + E2.get() + E3.get()
    if '*' in seq or '/' in seq:
        multDiv(E1.get(), E2.get(), E3.get())
    Soit dit en passant, je vous soupçonne de vouloir réinventer la roue en gérant vous-même les opérations à l'intérieur d'une entrée.

    Ne serait-il pas plus simple de s'appuyer sur Python pour cela ? Exemple :

    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
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
     
    def evaluate (expression):
        """
            évalue puis convertit une expression arithmétique en float,
            retourne 0.0 si erreur;
        """
        try:
            return float(eval(expression))
        except:
            return 0.0
        # end try
    # end def
     
     
    def ok():
        with open("matrice.txt") as inf:
            lines = inf.readlines()
     
        roundval = E4.get()
        print E1.get()
        print E2.get()
        print E3.get()
     
        # on prend en charge les opérations arithmétiques (+-*/)
     
        entries = [evaluate(E1.get()), evaluate(E2.get()), evaluate(E3.get())]
     
        # ou si vous préférez :
     
        entries = map(evaluate, (E1.get(), E2.get(), E3.get()))
     
        news = ""
        for line in lines:
            vals = line.strip().replace('[','').replace(']','').split(',')
            new = []
            for i, j in zip(vals, entries):
                s = float(i) + j
                if roundval :
                    s = round(s, int(roundval))
     
                new.append(s)
     
            news = news + str(new) + '\n'
     
        with open('matrice2.txt','w') as outf:
            outf.write(news)
     
        canvas2.itemconfig(c2,text=news)
        L.config(text="Finished !")
    # end def
    @+.

  6. #6
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Juillet 2014
    Messages
    23
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France, Gironde (Aquitaine)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juillet 2014
    Messages : 23
    Points : 15
    Points
    15
    Par défaut
    Quand je lance le programme en cliquant uniquement sur le bouton "ok", le programme va dans le except de la fonction evaluate(expression).

    Voici le programme:

    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
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
     
    from Tkinter import *
    from math import *
     
    def dispatch_yview (*args):
        """
            cette fonction dispatche les commandes de la scrollbar
            VERTICALE entre les deux canevas;
        """
        canvas.yview(*args)
        canvas2.yview(*args)
    # end def
     
    def evaluate (expression):
        """
            évalue puis convertit une expression arithmétique en float,
            retourne 0.0 si erreur;
        """
        try:
            print 'le return : ',float(eval(expression))
            return float(eval(expression))
        except:
            print 'c est l except'
            return 0.0
        # end try
    # end def
     
     
    def ok():
        with open("matrice.txt") as inf:
            lines = inf.readlines()
     
        roundval = E4.get()
     
        # on prend en charge les opérations arithmétiques (+-*/)
     
        entries = [E1.get(), E2.get(), E3.get()]
        print entries
     
        # ou si vous préférez :
     
        #entries = map(evaluate, (E1.get(), E2.get(), E3.get()))
     
        news = ""
        for line in lines:
            vals = line.strip().replace('[','').replace(']','').split(',')
            new = []
            for i, j in zip(vals, entries):
                print 'float(i)+j : ',float(i)+ float(j)
                s = evaluate('float(i)+ float(j)')
                print 's : ',s
                if roundval :
                    s = round(s, int(roundval))
     
                new.append(s)
     
            news = news + str(new) + '\n'
     
        with open('matrice2.txt','w') as outf:
            outf.write(news)
     
        canvas2.itemconfig(c2,text=news)
        L.config(text="Finished !")
    # end def
     
    # Création de fenêtre
    root = Tk()
    root.rowconfigure(0, weight=1)
    root.columnconfigure(0, weight=1)
    root.title("coordinate change")
     
    # Label, Entry
    L=Label(root,text='This program allows to increase or decrease one of the coordinates (X, Y or Z) of a [X,Y,Z] matrice such as: \n [15,1.454,0.1]\n[12.1,5.2,78]\n[0.3,0,45]\n(...)\n\n Please copy your matrice in a file whose the name is matrice.txt.\nPut the file in the same directory than this program. The new matrice will be in the file named matrice2.txt.',font=('Arial',17,'bold'))
    L.grid()
     
    L1=Label(root,text='Give the value(s)',font=('Helvetica',15,'underline'))
    L1.grid(column=1)
     
    LX=Label(root,text='X',font=('Helvetica',15,'underline'))
    LX.grid(row=2)
     
    E1=Entry(root)
    E1.grid(row=2,column=1)
    E1.insert(0,0)
     
    LY=Label(root,text='Y',font=('Helvetica',15,'underline'))
    LY.grid()
     
    E2=Entry(root)
    E2.grid(row=3,column=1)
    E2.insert(0,0)
     
    LZ=Label(root,text='Z',font=('Helvetica',15,'underline'))
    LZ.grid()
     
    E3=Entry(root)
    E3.grid(row=4,column=1)
    E3.insert(0,0)
     
    L2=Label(root,text='Contenu de matrice.txt :',font=('Helvetica',15,'underline'))
    L2.grid(row=6,column=0,columnspan=2)
     
    with open("matrice.txt") as inf:
        lines = inf.readlines()
     
    canvas = Canvas(root, bg="white")
    canvas.grid(row=7, column=0, sticky=NW+SE)
    list=canvas.create_text(0,0, text=lines, font="sans 16 bold", fill="blue",anchor='nw')
     
     
    # horizontal scrollbar
    hbar = Scrollbar(root, orient=HORIZONTAL)
    hbar.grid(row=8, column=0, sticky=NW+SE)
    # vertical scrollbar pour les 2
    vbar = Scrollbar(root, orient=VERTICAL)
    vbar.grid(row=7, column=3, sticky=W+N+S)
    # connecting people...
    canvas.configure(
        xscrollcommand=hbar.set,
        yscrollcommand=vbar.set,
        scrollregion=(0, 0, 800, 600),
    )
    hbar.configure(command=canvas.xview)
    vbar.configure(command=canvas.yview)
     
    L2=Label(root,text='Contenu de matrice2.txt :',font=('Helvetica',15,'underline'))
    L2.grid(row=6,column=2,columnspan=2)
     
    canvas2 = Canvas(root, bg="white")
    c2=canvas2.create_text(0,0, text='', font="sans 16 bold", fill="blue",anchor='nw')
    canvas2.grid(row=7, column=2, sticky=NW+SE)
     
    # horizontal scrollbar
    hbar = Scrollbar(root, orient=HORIZONTAL)
    hbar.grid(row=8, column=2, sticky=NW+SE)
     
    # connecting people...
    canvas2.configure(
        xscrollcommand=hbar.set,
        yscrollcommand=vbar.set,
        scrollregion=(0, 0, 800, 600),
    )
    hbar.configure(command=canvas2.xview)
    vbar.configure(command=canvas2.yview)
     
    # special dispatch between 2 canvases
    vbar.configure(command=dispatch_yview)
     
    B=Button(root,text='OK',width=25,command=ok)
    B.grid(row=4,column=2,columnspan=2)
     
    L5=Label(root,text='Voulez-vous arrondir ? Si oui, mettez le nombre de chiffres après la virgule que vous souhaitez faire apparaître :')
    L5.grid(row=5)
     
    E4=Entry(root)
    E4.grid(row=5,column=1)
     
    root.mainloop()
    Pourtant, lorsque je fait le code suivant, la fonction eval() ne produit pas d'erreur :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    def evaluate(nb):
        print float(eval(nb))
     
    a='float(1)+float(0)'
    evaluate(a)

  7. #7
    Invité
    Invité(e)
    Par défaut
    Citation Envoyé par adrbessy Voir le message
    Quand je lance le programme en cliquant uniquement sur le bouton "ok", le programme va dans le except de la fonction evaluate(expression).

    (snip)(snip)

    Pourtant, lorsque je fait le code suivant, la fonction eval() ne produit pas d'erreur :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    def evaluate(nb):
        print float(eval(nb))
     
    a='float(1)+float(0)'
    evaluate(a)
    Excellent !

    Vous ne comparez pas les mêmes tests.

    Dans le premier cas, vous cliquez simplement 'OK' --> appel de la fonction ok() avec E1.get() == "" par exemple.

    Dans le second cas, vous testez votre code avec float(1)+float(0) et vous vous étonnez que ça fonctionne.

    Il faut être un peu plus rigoureux que cela :

    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
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
     
    def eval_tarball69 (expression):
        """
            évalue puis convertit une expression arithmétique en float,
            retourne 0.0 si erreur;
        """
        try:
            return float(eval(expression))
        except:
            return 0.0
        # end try
    # end def
     
    def eval_adrbessy(nb):
        print float(eval(nb))
     
    # test no. 1 - expression python valide
     
    expr = 'float(1)+float(0)'
     
    print "test de l'expression : '%s'" % expr
    print "test tarball69:", eval_tarball69(expr)
    print "test adrbessy:"
     
    eval_adrbessy(expr)
     
    # test no. 2 - expression python invalide
     
    expr = ""
     
    print "test de l'expression : '%s'" % expr
    print "test tarball69:", eval_tarball69(expr)
    print "test adrbessy:"
     
    eval_adrbessy(expr) # boum ! ça pète une exception ! ^^
     
    # fin du test
    Evidemment que l'except déclenche sur l'évaluation d'une chaîne vide, cela n'a pas de sens pour l'interpréteur Python (EOF rencontré trop tôt).

    Avec le mécanisme try: ... except: ... je m'assure une valeur par défaut en cas de pépin, en l'occurrence la valeur float 0.0.

    @+.

  8. #8
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Juillet 2014
    Messages
    23
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France, Gironde (Aquitaine)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juillet 2014
    Messages : 23
    Points : 15
    Points
    15
    Par défaut
    En fait dans le premier cas, lorsqu'on appuie juste sur 'ok', le E1.get() est égale à zéro par défaut (donc ce n'est pas une chaîne vide). Donc ça revient à evaluate('float(i)+ float(0)'). Ce qui donne toujours 0.0 comme le programme va dans le except.
    Et dans le deuxième cas, je fais float(eval(float(1)+float(0)')) et ça me donne un 1.0 et donc ça fonctionne .
    Donc c'est pour ça que je ne comprends pas.. (après je suis peut-être encore à côté de la plaque ! )

  9. #9
    Invité
    Invité(e)
    Par défaut
    Citation Envoyé par adrbessy Voir le message
    En fait dans le premier cas, lorsqu'on appuie juste sur 'ok', le E1.get() est égale à zéro par défaut (donc ce n'est pas une chaîne vide). Donc ça revient à evaluate('float(i)+ float(0)'). Ce qui donne toujours 0.0 comme le programme va dans le except.
    Et dans le deuxième cas, je fais float(eval(float(1)+float(0)')) et ça me donne un 1.0 et donc ça fonctionne .
    Donc c'est pour ça que je ne comprends pas.. (après je suis peut-être encore à côté de la plaque ! )
    Au temps pour moi, je n'avais pas regardé ce que vous aviez mis dans votre fonction ok().

    Effectivement, vu à quelle sauce vous mangez la fonction evaluate(), ça ne peut pas fonctionner :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
            for i, j in zip(vals, entries):
                #~ print 'float(i)+j : ',float(i)+ float(j)
                s = evaluate('float(i)+ float(j)')
    Petit corrigé vite fait de votre script :

    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
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
     
    from Tkinter import *
     
    def dispatch_yview (*args):
        """
            cette fonction dispatche les commandes de la scrollbar
            VERTICALE entre les deux canevas;
        """
        canvas.yview(*args)
        canvas2.yview(*args)
    # end def
     
    def ensure_float (expression):
        """
            évalue puis convertit une expression en float,
            retourne 0.0 si erreur;
        """
        try:
            return float(eval(str(expression)))
        except Exception as e:
            #~ print "une erreur est survenue :", str(e)
            return 0.0
        # end try
    # end def
     
    def ok():
        """
            validation des données, calculs et création du nouveau
            fichier de sortie;
        """
        with open("matrice.txt") as file_in:
            lines = file_in.readlines()
        # end with
        decimals = int(ensure_float(E4.get()))
        entries = [E1.get(), E2.get(), E3.get()]
        str_data = ""
        for line in lines:
            # si line = "[nnn, nnn, nnn]" inutile de réinventer la roue:
            # c'est déjà la structure d'une liste Python [nnn, nnn, nnn]
            values = eval(line) if line.strip() else []
            data = []
            for (i, j) in zip(values, entries):
                # il faut évaluer chaque valeur séparément !
                sum_up = ensure_float(i) + ensure_float(j)
                if decimals:
                    sum_up = round(sum_up, decimals)
                # end if
                data.append(sum_up)
            # end for
            str_data += str(data) + '\n'
        # end for
        with open('matrice2.txt', 'w') as file_out:
            file_out.write(str_data)
        # end with
        canvas2.itemconfigure(c2_text_id, text=str_data)
        lbl_output.configure(text="Operation succeeded!")
    # end def
     
    # Création de fenêtre
    root = Tk()
    root.title("coordinate change")
    root.resizable(width=False, height=False)
     
    # Label, Entry
    Message(root, text="""Notice:
    This program allows to increase or decrease one \
    of the coordinates (X, Y or Z) of a [X,Y,Z] matrice such as:
    [ [15, 1.454, 0.1], [12.1, 5.2, 78], ..., [0.3, 0, 45] ]
    Please copy your matrice in a file whose the name is 'matrice.txt'.
    Put the file in the same directory than this program.
    The new matrice will be in the file named 'matrice2.txt'.""",
    font="sans 10", width=360).grid(row=0, column=1, padx=5)
     
    my_font = "helvetica 14 underline"
     
    frame = Frame(root)
    frame.grid(row=0, column=0)
     
    Label(frame, text='insert values:', font=my_font).grid(row=0, column=1)
    Label(frame, text='X:', font=my_font).grid(padx=5, sticky=E)
     
    E1 = Entry(frame)
    E1.grid(row=1, column=1)
    #~ E1.insert(0, 0) # risque de notation *octale* e.g. 025 = 21 /!\
     
    Label(frame, text='Y:', font=my_font).grid(padx=5, sticky=E)
     
    E2 = Entry(frame)
    E2.grid(row=2, column=1)
     
    Label(frame, text='Z:', font=my_font).grid(padx=5, sticky=E)
     
    E3 = Entry(frame)
    E3.grid(row=3, column=1)
     
    Label(frame, text='Round values\nup to (decimals):').grid(padx=5, sticky=E)
     
    E4 = Entry(frame)
    E4.grid(row=4, column=1, sticky=SW)
     
    Button(frame, text='OK', width=10, command=ok).grid(row=4, column=2, padx=10, sticky=S)
     
    lbl_output = Label(root, fg="red")
    lbl_output.grid(row=2, column=1)
     
    frame = Frame(root)
    frame.grid(row=1, column=0, columnspan=2)
     
    txt_options = dict(font="sans 12 bold", fill="blue", anchor=NW)
     
    Label(frame, text='matrice.txt contents:', font=my_font).grid(row=0, column=0)
     
    with open("matrice.txt") as file_in:
        lines = file_in.read().strip()
    # end with
     
    canvas = Canvas(frame, bg="white")
    canvas.grid(row=1, column=0, sticky=NW+SE)
    canvas.create_text(0, 0, text=lines, **txt_options)
     
    # horizontal scrollbar
    hbar = Scrollbar(frame, orient=HORIZONTAL)
    hbar.grid(row=2, column=0, sticky=NW+SE)
    # vertical scrollbar pour les 2
    vbar = Scrollbar(frame, orient=VERTICAL)
    vbar.grid(row=1, column=3, sticky=NW+SE)
    # connecting people...
    canvas.configure(
        xscrollcommand=hbar.set,
        yscrollcommand=vbar.set,
        scrollregion=canvas.bbox(ALL),
    )
    hbar.configure(command=canvas.xview)
    vbar.configure(command=canvas.yview)
     
    frame.columnconfigure(1, minsize=5)
     
    Label(frame, text='matrice2.txt contents:', font=my_font).grid(row=0, column=2)
     
    canvas2 = Canvas(frame, bg="white")
    c2_text_id = canvas2.create_text(0, 0, **txt_options)
    canvas2.grid(row=1, column=2, sticky=NW+SE)
     
    # horizontal scrollbar
    hbar = Scrollbar(frame, orient=HORIZONTAL)
    hbar.grid(row=2, column=2, sticky=NW+SE)
     
    # connecting people...
    canvas2.configure(
        xscrollcommand=hbar.set,
        yscrollcommand=vbar.set,
        scrollregion=canvas.bbox(ALL),
    )
    hbar.configure(command=canvas2.xview)
    vbar.configure(command=canvas2.yview)
     
    # special dispatch between 2 canvases
    vbar.configure(command=dispatch_yview)
     
    Button(root, text="Quit", command=root.destroy).grid(row=2, column=1, padx=5, pady=5, sticky=SE)
     
    root.mainloop()
    ça devrait être un peu mieux.

    @+

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

Discussions similaires

  1. [GET] Récupérer des paramètres URL en GET
    Par alavoler dans le forum Général JavaScript
    Réponses: 6
    Dernier message: 26/09/2008, 11h25
  2. gets() a la suite de scanf() -> probleme
    Par ickis dans le forum C
    Réponses: 12
    Dernier message: 14/12/2003, 20h24
  3. gets ,fgets
    Par Zazeglu dans le forum C
    Réponses: 2
    Dernier message: 19/09/2003, 18h24
  4. Créer les get et set des classes
    Par cameleon2002 dans le forum JBuilder
    Réponses: 3
    Dernier message: 17/09/2003, 21h03
  5. url d'une page asp ou upload avec get
    Par taupin dans le forum ASP
    Réponses: 18
    Dernier message: 22/08/2003, 14h25

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