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 :

matplotlib et Tkinter [Python 2.X]


Sujet :

Calcul scientifique Python

  1. #1
    Futur Membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Octobre 2014
    Messages
    9
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Sénégal

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Octobre 2014
    Messages : 9
    Points : 6
    Points
    6
    Par défaut matplotlib et Tkinter
    Bonsoir à tous!

    Je voudrais savoir si on peut combiner les modules matplotlib et Tkinter.
    i.e peut-on utiliser les fonctions du module matplotlib a l'intérieur d'une boucle Tkinter?

    merci d'avance

  2. #2
    Membre éprouvé

    Homme Profil pro
    Cyber Security & AI
    Inscrit en
    Février 2009
    Messages
    506
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Oise (Picardie)

    Informations professionnelles :
    Activité : Cyber Security & AI

    Informations forums :
    Inscription : Février 2009
    Messages : 506
    Points : 1 189
    Points
    1 189
    Billets dans le blog
    2
    Par défaut
    Bonjour,


    En créant une image avec matplotlib tu peux après l’intégrer dans Tinker comme noté dans la FAQ ci-dessous;


    FAQ Pyhton sur Tinker


    Cela t'aide-t-il ?


    Cordialement.

  3. #3
    Membre chevronné
    Homme Profil pro
    Enseignant
    Inscrit en
    Juin 2013
    Messages
    1 608
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Enseignant
    Secteur : Enseignement

    Informations forums :
    Inscription : Juin 2013
    Messages : 1 608
    Points : 2 072
    Points
    2 072
    Par défaut
    Pour python3 à adapter.

    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
    import matplotlib
    matplotlib.use('TkAgg')
    import math
     
    from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg,
                                                   NavigationToolbar2TkAgg)
    from matplotlib.figure import Figure
     
    import tkinter as tk
    from tkinter.constants import TOP, BOTH, BOTTOM, LEFT
     
    def figure_create(master=None):
     
        figure = Figure(figsize=(5,4), dpi=100)
        axe = figure.add_subplot(111)
     
        canvas = FigureCanvasTkAgg(figure, master=root)
        canvas.show()
        canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
     
        toolbar = NavigationToolbar2TkAgg( canvas, root )
        toolbar.update()
        canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1)
     
        figure._toolbar = toolbar
        return figure
     
    plotShift = 0
     
    def figure_draw(figure):
        global plotShift
        axe = figure.axes[0] 
        xVals = range(100)
        axe.plot(xVals, [math.sin(x + plotShift) for x in xVals])
        figure.canvas.draw()
        plotShift += 10
     
    def figure_clear(figure):
        axe = figure.axes[0]
        axe.clear()    
        figure.canvas.draw()
     
    def figure_hide(figure):
        figure.canvas.get_tk_widget().pack_forget() 
     
    def figure_show(figure):
        figure.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
     
    root = tk.Tk()
    root.wm_title("Embedding in TK")
     
    figure = figure_create(master=root)
     
    frame = tk.Frame(root)
    tk.Button(frame, text='draw', command=lambda f=figure: figure_draw(f)).pack(side=LEFT)
    tk.Button(frame, text='clear', command=lambda f=figure: figure_clear(f)).pack(side=LEFT)
    tk.Button(frame, text='show', command=lambda f=figure: figure_show(f)).pack(side=LEFT)
    tk.Button(frame, text='hide', command=lambda f=figure: figure_hide(f)).pack(side=LEFT)
    frame.pack(side=BOTTOM)
    tk.mainloop()
    Pas d'aide par mp.

  4. #4
    Futur Membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Octobre 2014
    Messages
    9
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Sénégal

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Octobre 2014
    Messages : 9
    Points : 6
    Points
    6
    Par défaut
    merci dev_ggy de vouloir m'aider

    J'ai suivi le lien mais ça ne répond pas à ma question(le module matplotlib n'est pas utilisé)
    mon projet n'est pas d'afficher des image mais de tracer des courbes avec Tkinter comme on le fait avec le module matplotlib

    Voici un exemple

    1)
    # Exemple simple d'une courbe avec matplotlib

    import matplotlib.pylab as pl
    import numpy as np
    # fonction qui modelise la fonction y=exp(x)*x
    def tracer():
    x=np.linspace(0,10,100)
    y=nb.exp(x)*x
    pl.plot(x,y)
    pl.show()
    tracer() #on teste notre fonction



    2)

    # Voici maintenant en exemple simple avec Tkinter
    from Tkinter import *
    fen=Tk()
    bou=Button(fen,text="Afficher",fg='red',command=fen.quit)
    bou.pack()
    fen.mainloop()


    Ces deux scripts marchent séparément mais en remplaçant fen.quit par la fonction tracer, ça génère une erreur
    Ce que je ne comprends pas c'est pourquoi ça génère une erreur

    Un grand Merci à marco056
    j'ai testé votre code et ça marche même avec python 2.7.
    Il suffit de remplacer :
    import tkinter as tk par import Tkinter as tk
    et from tkinter.constants import TOP, BOTH, BOTTOM, LEFT par from Tkinter import TOP, BOTH, BOTTOM, LEFT

  5. #5
    Membre éprouvé

    Homme Profil pro
    Ingénieur
    Inscrit en
    Août 2010
    Messages
    654
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur
    Secteur : Aéronautique - Marine - Espace - Armement

    Informations forums :
    Inscription : Août 2010
    Messages : 654
    Points : 1 150
    Points
    1 150
    Par défaut
    Salut!

    Voici une version plus simple mais moins complete que celle de Marco056. L'idée est la même: passer par FigureCanvasTkAgg. Dans l'exemple que je donne, la figure n'est pas crée en dehors de la classe qui fait office chez moi de d'interface graphique comme c'est le cas chez Marco056. En regardant les deux codes, et si besoin en posant quelques questions tu devrais sans problème adapter tout ça à tes besoins.

    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
    # -*- coding:Utf-8 -*-
     
    from Tkinter import *
    import ttk
    import random
    import matplotlib
    import matplotlib.pyplot as plt
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
     
    def generate_data():
        x = [i for i in range(50)]
        y = [10*random.random() for i in range(50)]
        return x, y
     
    class DummyFrame():
     
        def __init__(self,root):
            # Construction of the main frame to hold the graph and a button
            self.main_frame = Frame(root)
            self.main_frame.pack()
     
            # Creation of the button which will create and display a new graph
            start_button = Button(self.main_frame, text="START", command=self.draw_graph)
            start_button.grid(column=1, row=1, sticky=(W,E))	
     
            # Definition of the figure
            figure = plt.figure()
            self.ax = figure.add_subplot(111)
            plt.grid()
     
            # Creation of a canva to hold the figure
            self.canvas = FigureCanvasTkAgg(figure, master=self.main_frame)
            self.canvas.get_tk_widget().grid(column=1, row=2, sticky=(W,E))
     
        def draw_graph(self):
            x, y = generate_data()
            self.ax.clear()
            self.ax.plot(x, y, 'red')
            plt.grid()
            self.canvas.draw()
     
     
    if __name__ == '__main__':
     
        root = Tk()
        root.resizable(0,0) 
        root.title("DummyFrame")
        interface = DummyFrame(root)
        root.mainloop()
    Ciao ciao,

    Ju

  6. #6
    Futur Membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Octobre 2014
    Messages
    9
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Sénégal

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Octobre 2014
    Messages : 9
    Points : 6
    Points
    6
    Par défaut
    Bonjour,

    Un grand merci a Julien N , à tout ceux qui m'ont venu et me viendront en aide

    Je suis un passionné, un très passionné même du langage python et de la programmation en général.
    Du coup je veux maîtriser tout ce que j'utilise .C'est pourquoi si je pouvais avoir des commentaires bien détaillés des fonctions du module matplotlib.backends.backend_tkagg que vous avez utilisées dans vos codes ou bien un cours sur ce module ,je vous en serais de nouveau reconnaissant.
    j'ai un projet complexe de modélisation de fonctions complexes. Si vous avez des documenst à partager traitant les modules Tkinter , matplotlib et matplotlib.backends.backend_tkagg merci de me les envoyer à l'adresse profdemathematics@gmail.com svp

  7. #7
    Futur Membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Octobre 2014
    Messages
    9
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Sénégal

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Octobre 2014
    Messages : 9
    Points : 6
    Points
    6
    Par défaut
    Bonsoir,

    J'ai pu comprendre les lignes de vos codes après deux jours de recherche .
    Encore une fois Merci beaucoup!!!

  8. #8
    Membre éprouvé

    Homme Profil pro
    Ingénieur
    Inscrit en
    Août 2010
    Messages
    654
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur
    Secteur : Aéronautique - Marine - Espace - Armement

    Informations forums :
    Inscription : Août 2010
    Messages : 654
    Points : 1 150
    Points
    1 150
    Par défaut
    Y'a pas de quoi. Si tu veux débuter avec tkinter, je te conseil le livre de Mark Roseman, Modern Tkinter for Busy Python Developers. En anglais mais bien documenté et illustré d'exemples. Il aborde les principaux concepts d'une interface. On peut le trouver illégalement à la lecture sur le net (ce que je ne conseil pas).

    J

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

Discussions similaires

  1. Tkinter et Matplotlib
    Par LittleBN dans le forum GUI
    Réponses: 14
    Dernier message: 08/05/2014, 21h30
  2. problème de portabilité d'un programme avec tkinter et matplotlib
    Par rafoim dans le forum Calcul scientifique
    Réponses: 3
    Dernier message: 13/11/2013, 11h52
  3. plot de Matplotlib sous Tkinter?
    Par Invité dans le forum Tkinter
    Réponses: 7
    Dernier message: 28/02/2011, 13h22
  4. [matplotlib] Croubes dans une interface tkinter
    Par vinzzzz dans le forum Tkinter
    Réponses: 2
    Dernier message: 08/12/2006, 14h34
  5. [matplotlib][Tkinter] Conflit figure/Tk ?
    Par Panthère Bleue dans le forum Calcul scientifique
    Réponses: 2
    Dernier message: 12/07/2006, 08h48

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