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

Calcul scientifique Python Discussion :

problème de portabilité d'un programme avec tkinter et matplotlib


Sujet :

Calcul scientifique Python

  1. #1
    Membre du Club
    Homme Profil pro
    Enseignant
    Inscrit en
    Mars 2013
    Messages
    38
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Côte d'Or (Bourgogne)

    Informations professionnelles :
    Activité : Enseignant
    Secteur : Service public

    Informations forums :
    Inscription : Mars 2013
    Messages : 38
    Points : 47
    Points
    47
    Par défaut problème de portabilité d'un programme avec tkinter et matplotlib
    Bonjour,

    Je suis professeur de mathématiques. j'enseigne à un niveau modeste le langage python en terminale S ( spécialité ISN).
    Vendredi ( après demain), je suis inspecté. J'ai préparé un programme python illustrant la réponse à un problème.
    Le problème ( mais ce n'est pas important):Un distributeur de billets de banque ne délivre que des coupures de 10 euros et 20 euros. On s’intéresse au nombre de façons de délivrer une somme S donnée.

    Le problème que je vous adresse: le programme fonctionne sur mon ordi mais ne fonctionne pas sur celui du lycée. Au lycée: petite fenêtre tkinter vide. Sur mon ordi: windows 7, celui du lycée: windows xp. Matplotlib installé sur les deux ordis. Même version de python (3.2). Plus excatement, j'utilise la dernière version d'edupython ( même version sur les deux ordis).

    Voilà le code:
    # Créé par rafoim, le 06/11/2013 en Python 3.2
    import matplotlib
    matplotlib.use('TkAgg')
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
    from matplotlib.figure import Figure
    import numpy as np
    import tkinter as tk



    def ListeSolutions(somme):
    x=somme//10
    y=0
    liste=[]
    while(x>=0):
    liste.append((x,y))
    x-=2
    y+=1
    nombre_de_solutions=len(liste)
    return liste,nombre_de_solutions

    def center_spines(ax=None, centerx=0, centery=0):
    """Centers the axis spines at <centerx, centery> on the axis "ax", and
    places arrows at the end of the axis spines."""
    if ax is None:
    ax = plt.gca()

    # Set the axis's spines to be centered at the given point
    # (Setting all 4 spines so that the tick marks go in both directions)
    ax.spines['left'].set_position(('data', centerx))
    ax.spines['bottom'].set_position(('data', centery))
    ax.spines['right'].set_position(('data', centerx - 1))
    ax.spines['top'].set_position(('data', centery - 1))


    # Hide the line (but not ticks) for "extra" spines
    for side in ['right', 'top']:
    ax.spines[side].set_color('none')

    # On both the x and y axes...
    for axis, center in zip([ax.xaxis, ax.yaxis], [centerx, centery]):
    # Turn on minor and major gridlines and ticks
    axis.set_ticks_position('both')
    axis.grid(True, 'major', ls='solid', lw=0.5, color='gray')
    axis.grid(True, 'minor', ls='solid', lw=0.1, color='gray')
    axis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())






    class Application():
    def __init__(self):
    self.somme=40
    self.fenetre=tk.Tk()
    self.figure=Figure(figsize=(7,7),dpi=100)


    self.canevas=FigureCanvasTkAgg(self.figure, master=self.fenetre)
    self.canevas.show()
    self.canevas.get_tk_widget().pack(fill=tk.BOTH,expand=1)
    self.canevas._tkcanvas.grid(column=0,row=0,rowspan=4)
    self.champ=tk.Entry(self.fenetre)
    self.champ.bind("<Return>", self.Actualiser)
    self.champ.config(font=("Courrier","16","bold"))
    self.bouton1=tk.Button(self.fenetre,text="Incrémenter",command=self.Incrementer)
    self.bouton2=tk.Button(self.fenetre,text="Décrémenter",command=self.Decrementer)
    self.label=tk.Label(self.fenetre,text="Somme à délivrer:",font=("Courrier","16","bold"))
    self.label.grid(column=1,row=0)
    self.champ.grid(column=1,row=1)
    self.bouton1.grid(column=1, row=2)
    self.bouton2.grid(column=1, row=3)

    def Affichage(self):
    self.figure.clf()
    graphique=self.figure.add_axes([0,0,1,1])
    l,n=ListeSolutions(self.somme)
    message="Le nombre de solutions est: "+str(n)
    graphique.text(0.5,0.5,message,fontsize=20)
    xmin=-self.somme//100
    ymin=-self.somme//100
    xmax=self.somme//10+self.somme//100+1
    ymax=self.somme//20+self.somme//100+1
    graphique.set_xlim(xmin, xmax)
    graphique.set_ylim(ymin, ymax)
    graphique.set_xlabel("billets de 10 euros")
    center_spines(graphique)
    for point in l:
    x=point[0]
    y=point[1]
    graphique.plot(x,y,"r"+"o")
    x=np.arange(0,self.somme//10,0.01)
    y=self.somme/20-0.5*x
    graphique.plot(x,y)
    annotation="segment de la droite d'équation x+2y="+str(self.somme//10)
    graphique.annotate(annotation,
    xy=(0.5, self.somme/20-0.25),
    xytext=(0.5+self.somme/200, self.somme/20-0.25+self.somme/200),
    xycoords='data',
    textcoords='data',
    arrowprops=dict(arrowstyle="fancy"))
    self.canevas.draw()


    def Actualiser(self,event):
    self.somme=int(self.champ.get())
    self.Affichage()
    def Incrementer(self):
    self.somme+=10
    self.champ.delete(0,tk.END)
    self.champ.insert(tk.END, str(self.somme))
    self.Affichage()
    def Decrementer(self):
    self.somme-=10
    self.champ.delete(0,tk.END)
    self.champ.insert(tk.END, str(self.somme))
    self.Affichage()



    application=Application()



    Merci d'avance pour les éventuelles réponses.

  2. #2
    Membre éclairé
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Janvier 2013
    Messages
    388
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : Conseil

    Informations forums :
    Inscription : Janvier 2013
    Messages : 388
    Points : 692
    Points
    692
    Par défaut
    Bonjour,
    Les « moteurs » de PyScripter doivent être différents.
    Dans le menu « Run », « Python Engine », choisir « Remote (Tk) » par exemple.

  3. #3
    Membre du Club
    Homme Profil pro
    Enseignant
    Inscrit en
    Mars 2013
    Messages
    38
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Côte d'Or (Bourgogne)

    Informations professionnelles :
    Activité : Enseignant
    Secteur : Service public

    Informations forums :
    Inscription : Mars 2013
    Messages : 38
    Points : 47
    Points
    47
    Par défaut
    Merci, je vais essayer.
    Suite à un message privé d'un membre, je réédite mon code proprement:
    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
     
    # Créé par rafoim, le 06/11/2013 en Python 3.2
    import matplotlib
    matplotlib.use('TkAgg')
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
    from matplotlib.figure import Figure
    import numpy as np
    import tkinter as tk
     
     
     
    def ListeSolutions(somme):
        x=somme//10
        y=0
        liste=[]
        while(x>=0):
            liste.append((x,y))
            x-=2
            y+=1
        nombre_de_solutions=len(liste)
        return liste,nombre_de_solutions
     
    def center_spines(ax=None, centerx=0, centery=0):
        """Centers the axis spines at <centerx, centery> on the axis "ax", and
        places arrows at the end of the axis spines."""
        if ax is None:
            ax = plt.gca()
     
        # Set the axis's spines to be centered at the given point
        # (Setting all 4 spines so that the tick marks go in both directions)
        ax.spines['left'].set_position(('data', centerx))
        ax.spines['bottom'].set_position(('data', centery))
        ax.spines['right'].set_position(('data', centerx - 1))
        ax.spines['top'].set_position(('data', centery - 1))
     
     
        # Hide the line (but not ticks) for "extra" spines
        for side in ['right', 'top']:
            ax.spines[side].set_color('none')
     
        # On both the x and y axes...
        for axis, center in zip([ax.xaxis, ax.yaxis], [centerx, centery]):
            # Turn on minor and major gridlines and ticks
            axis.set_ticks_position('both')
            axis.grid(True, 'major', ls='solid', lw=0.5, color='gray')
            axis.grid(True, 'minor', ls='solid', lw=0.1, color='gray')
            axis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())
     
     
     
     
     
     
    class Application():
        def __init__(self):
            self.somme=40
            self.fenetre=tk.Tk()
            self.figure=Figure(figsize=(7,7),dpi=100)
     
     
            self.canevas=FigureCanvasTkAgg(self.figure, master=self.fenetre)
            self.canevas.show()
            self.canevas.get_tk_widget().pack(fill=tk.BOTH,expand=1)
            self.canevas._tkcanvas.grid(column=0,row=0,rowspan=4)
            self.champ=tk.Entry(self.fenetre)
            self.champ.bind("<Return>", self.Actualiser)
            self.champ.config(font=("Courrier","16","bold"))
            self.bouton1=tk.Button(self.fenetre,text="Incrémenter",command=self.Incrementer)
            self.bouton2=tk.Button(self.fenetre,text="Décrémenter",command=self.Decrementer)
            self.label=tk.Label(self.fenetre,text="Somme à délivrer:",font=("Courrier","16","bold"))
            self.label.grid(column=1,row=0)
            self.champ.grid(column=1,row=1)
            self.bouton1.grid(column=1, row=2)
            self.bouton2.grid(column=1, row=3)
     
        def Affichage(self):
            self.figure.clf()
            graphique=self.figure.add_axes([0,0,1,1])
            l,n=ListeSolutions(self.somme)
            message="Le nombre de solutions est: "+str(n)
            graphique.text(0.5,0.5,message,fontsize=20)
            xmin=-self.somme//100
            ymin=-self.somme//100
            xmax=self.somme//10+self.somme//100+1
            ymax=self.somme//20+self.somme//100+1
            graphique.set_xlim(xmin, xmax)
            graphique.set_ylim(ymin, ymax)
            graphique.set_xlabel("billets de 10 euros")
            center_spines(graphique)
            for point in l:
                x=point[0]
                y=point[1]
                graphique.plot(x,y,"r"+"o")
            x=np.arange(0,self.somme//10,0.01)
            y=self.somme/20-0.5*x
            graphique.plot(x,y)
            annotation="segment de la droite d'équation x+2y="+str(self.somme//10)
            graphique.annotate(annotation,
                 xy=(0.5, self.somme/20-0.25),
                 xytext=(0.5+self.somme/200, self.somme/20-0.25+self.somme/200),
                 xycoords='data',
                 textcoords='data',
                 arrowprops=dict(arrowstyle="fancy"))
            self.canevas.draw()
     
     
        def Actualiser(self,event):
            self.somme=int(self.champ.get())
            self.Affichage()
        def Incrementer(self):
            self.somme+=10
            self.champ.delete(0,tk.END)
            self.champ.insert(tk.END, str(self.somme))
            self.Affichage()
        def Decrementer(self):
            self.somme-=10
            self.champ.delete(0,tk.END)
            self.champ.insert(tk.END, str(self.somme))
            self.Affichage()
     
     
     
    application=Application()

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

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

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

    Il faut trop d'environnements pour reproduire et comprendre.
    Comme en passant de XP a Windows7 vous changez le s/système graphique cote OS, la chose "touche" l'interface graphique.
    Et le plus impredictible avec Tk est de s’emmêler les pinceaux avec les layouts managers...
    Quand je lis:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
            self.canevas.get_tk_widget().pack(fill=tk.BOTH,expand=1)
            self.canevas._tkcanvas.grid(column=0,row=0,rowspan=4)
    Je me dis "ha ha". Mais ce n'est qu'une piste suggérée par l’expérience.
    - W
    Architectures post-modernes.
    Python sur DVP c'est aussi des FAQs, des cours et tutoriels

Discussions similaires

  1. Problème d'exécution de mon programme avec Launch4J
    Par Mario Cayer dans le forum Général Java
    Réponses: 5
    Dernier message: 15/12/2013, 19h35
  2. Probleme de programmation avec Tkinter
    Par kaize dans le forum Général Python
    Réponses: 1
    Dernier message: 07/01/2013, 08h31
  3. Réponses: 6
    Dernier message: 18/02/2010, 21h40
  4. Portabilité des programmes avec Ogre
    Par Borni Gloim dans le forum Ogre
    Réponses: 1
    Dernier message: 13/01/2008, 18h14
  5. Problème de portabilité du programme
    Par cayou dans le forum C
    Réponses: 19
    Dernier message: 02/01/2008, 21h07

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