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 :

Aide pour interface graphique


Sujet :

Tkinter Python

  1. #1
    Nouveau Candidat au Club
    Femme Profil pro
    Étudiant
    Inscrit en
    Avril 2013
    Messages
    5
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : France, Nord (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2013
    Messages : 5
    Points : 1
    Points
    1
    Par défaut Aide pour interface graphique
    Bonjour à tous, j'ai programmé un simulateur de croissance radioactive avec la courbe de désintégration. Afin d'amélioré mon programme, je souhaite faire une interface graphique mais le problème et que je n'y arrive pas, pouvez vous m'aidé ?
    Fichiers attachés Fichiers attachés

  2. #2
    Expert éminent

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

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

    As-tu besoin juste d'une interface pour présenter ton graphique ? Matplotlib est l'idéal pour ça.

    Si par contre tu as besoin d'une interface où tu pourras ajouter divers boutons, widgets de saisie de données, etc tu as le choix sur cette page:

    http://python.developpez.com/cours/?page=GUI

    Un exemple dans une fenêtre Qt avec ton 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
     
    # -*- coding: utf-8 -*-
     
    import sys
    from random import randint
    from PyQt4 import QtGui, QtCore
     
    ###################
    ###  VARIABLES  ###
    ###################
     
    tabDes = [1]*600
    x=0
    tabNbreNoyaux=[600]
     
    ###############################################
    ###  Fonctions utilisées dans le programme  ###
    ###############################################
    # METHODES
     
    def remplir(tabDes) :
        for i in range (0,len(tabDes)):
            if tabDes[i]!=0:
                tabDes[i]=randint(1,6)                       
        return tabDes
     
    def remplacer6(tabDes) :
        for i in range (0,len(tabDes)):
            if (tabDes[i]==6) :
                tabDes[i]=0
     
    def nombreNoyaux():
        tabNbreNoyaux.append(600-tabDes.count(0))
     
     
    class MainWindow(QtGui.QMainWindow):
        def __init__(self):
            super(MainWindow, self).__init__()
            self.resize(460, 610)
            self.central = QtGui.QWidget()
            self.topLayout = QtGui.QGridLayout(self.central)
            self.viewer = QtGui.QGraphicsView(self.central)
            self.topLayout.addWidget(self.viewer)
            self.scene = QtGui.QGraphicsScene()
            self.viewer.setScene(self.scene)
            self.setCentralWidget(self.central)
     
        def set_graphics(self, values):
            self.create_background()
            self.draw_curve(values)
            pix = QtGui.QPixmap.fromImage(self.background)
            self.scene.clear()
            self.scene.setSceneRect(0, 0, 450, 650)
            self.scene.addPixmap(pix)
     
        def draw_curve(self, data):
            color = QtGui.QColor(250, 50, 50, 255)
            painter = QtGui.QPainter()
            painter.begin(self.background)
            path = QtGui.QPainterPath()
            x = 10
            path.moveTo(x, 0)
     
            for dat in data:
                x += 10
                path.lineTo(x, 600 - dat)
     
            painter.setPen(QtGui.QPen(color, 2,
                                  QtCore.Qt.SolidLine, QtCore.Qt.RoundCap,
                                  QtCore.Qt.MiterJoin))
            painter.drawPath(path)
            painter.end()
     
        def create_background(self):
            self.background = QtGui.QImage(QtCore.QSize(450, 650), 
                                QtGui.QImage.Format_ARGB32_Premultiplied)
            self.background.fill(QtGui.QColor(0, 0, 0, 255))
     
    if __name__ == '__main__':
        while tabDes.count(0)!=600:        
            remplir(tabDes)
            remplacer6(tabDes)
            nombreNoyaux()
            x=x+1
     
        app = QtGui.QApplication(sys.argv)
        win = MainWindow()
        win.set_graphics(tabNbreNoyaux)
        win.show()
        sys.exit(app.exec_())
    Ici, la courbe fait partie de l'image, (dans le code initial j'avais besoin de sauver cette image sur le disque) mais peut, bien sur, être créée comme objet individuel et donc déplacée, modifiée, etc.

  3. #3
    Nouveau Candidat au Club
    Femme Profil pro
    Étudiant
    Inscrit en
    Avril 2013
    Messages
    5
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : France, Nord (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2013
    Messages : 5
    Points : 1
    Points
    1
    Par défaut
    Je voulais une interface graphique pour tout mon programme en faite, j'avais pensé que sur une fenêtre avec un bouton "demarrer" on lance le programme (en affichant le detaille de la decroissance) et que ensuite ca affiche la courbe. Je pense qu'avec tkinter je comprendrais mieu car j'ai dispose de légere base: cela me permettrait de mieux comprendre la démarche

  4. #4
    Expert éminent
    Avatar de fred1599
    Homme Profil pro
    Lead Dev Python
    Inscrit en
    Juillet 2006
    Messages
    3 896
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Meurthe et Moselle (Lorraine)

    Informations professionnelles :
    Activité : Lead Dev Python
    Secteur : Arts - Culture

    Informations forums :
    Inscription : Juillet 2006
    Messages : 3 896
    Points : 7 256
    Points
    7 256
    Par défaut
    J'ai pas regardé le code, mais avec Tkinter, tu peux utiliser la classe Canvas.

  5. #5
    Nouveau Candidat au Club
    Femme Profil pro
    Étudiant
    Inscrit en
    Avril 2013
    Messages
    5
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : France, Nord (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2013
    Messages : 5
    Points : 1
    Points
    1
    Par défaut
    Justement je me doutait qu'il faut utilisé la classe Canvas mais je ne la maitrise pas suffisemment

  6. #6
    Nouveau Candidat au Club
    Femme Profil pro
    Étudiant
    Inscrit en
    Avril 2013
    Messages
    5
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : France, Nord (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2013
    Messages : 5
    Points : 1
    Points
    1
    Par défaut
    Personne ne veut m'aidé ?

  7. #7
    Expert éminent
    Avatar de fred1599
    Homme Profil pro
    Lead Dev Python
    Inscrit en
    Juillet 2006
    Messages
    3 896
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Meurthe et Moselle (Lorraine)

    Informations professionnelles :
    Activité : Lead Dev Python
    Secteur : Arts - Culture

    Informations forums :
    Inscription : Juillet 2006
    Messages : 3 896
    Points : 7 256
    Points
    7 256
    Par défaut
    Donne un petit exemple de ce que tu souhaites faire.

    Je ne lis pas les pièces jointes, place le morceau de ton code qui pose problème.

  8. #8
    Nouveau Candidat au Club
    Femme Profil pro
    Étudiant
    Inscrit en
    Avril 2013
    Messages
    5
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : France, Nord (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2013
    Messages : 5
    Points : 1
    Points
    1
    Par défaut
    Alors, mon programme est une simulation de 600 lancé de dé. Tout les 6 deviennent des 0. Les 0 representent un noyaux qui se desintegre lors d'une decroissance radioactive. J'ai crée un graphique qui represente la decroissance. Maintenant Je ne dispose pas d'interface graphique (car je n'arrive pas) et je souhaite en avoir une par Tkinter (car c'est la seul ou je peux eventuellement comprendre comme je dispose de quelque base). A partir de cela j'aimerais dans une fenetre voir apparaitre Les differents tableaux de decroissance et le graph correspondant. Bien evidement une touche "Démarrer" pour lancé la simulation.

    Voici mon programme:

    # -*- coding: cp1252 -*-
    from random import *
    from turtle import *


    ###################
    ### VARIABLES ###
    ###################

    tabDes = [1]*600
    x=0
    tabNbreNoyaux=[600]

    ###############################################
    ### Fonctions utilisées dans le programme ###
    ###############################################
    # METHODES

    def remplir(tabDes) :
    for i in range (0,len(tabDes)):
    if tabDes[i]!=0:
    tabDes[i]=randint(1,6)
    return tabDes

    def remplacer6(tabDes) :
    for i in range (0,len(tabDes)):
    if (tabDes[i]==6) :
    tabDes[i]=0

    def nombreNoyaux():
    tabNbreNoyaux.append(600-tabDes.count(0))

    #############################
    ### PROGRAMME PRINCIPAL ###
    #############################

    while tabDes.count(0)!=600:
    remplir(tabDes) # print
    print "Le nombre de 0 est :",(tabDes.count(0))
    remplacer6(tabDes)
    nombreNoyaux()
    # print tabDes
    x=x+1
    print "Il a fallu",x, "tirages"
    print tabNbreNoyaux

    speed(0)

    penup()
    setpos(-350,-300)
    pendown()
    for x in range(0,x+2):
    left(90)
    forward(2)
    backward(4)
    forward(2)
    right(90)
    forward(10)

    stamp()
    backward(x*10+10)
    left(90)
    for y in range(0,61):
    left(90)
    forward(2)
    backward(4)

    forward(2)
    right(90)
    forward(10)


    for i in range (0,len(tabNbreNoyaux)):
    goto(-350+10*i,tabNbreNoyaux[i]-300)


    stamp()
    mainloop()

  9. #9
    Expert éminent

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

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

    Commence par ce cours: http://python.developpez.com/cours/apprendre-python3/

    G. Swinnen y aborde assez vite TKinter et y donne des exemples de tracés dans un canvas.

  10. #10
    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,
    Voici ma proposition (je me suis un peu éloigné du code original en cherchant à comprendre).
    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
    #!/usr/bin/env python
    # -*- coding:Utf-8 -*-
    import matplotlib
    matplotlib.use('TkAgg')
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
    from matplotlib.figure import Figure
    import numpy as np
    from numpy.random import randint
    from scipy.optimize import curve_fit
    import Tkinter as Tk
    from ScrolledText import *
     
    def desintegration_noyaux( nb, tau):
        tab = np.ones((nb), dtype=np.int)
        tNx = np.array([nb])
        while np.max(tab):
            idx = np.argwhere(tab>0)
            tab[idx] = randint( 1, tau+1, np.size(idx))
            tab[np.argwhere(tab==tau)] = 0
            nbv = np.count_nonzero(tab)
            tNx = np.append(tNx, nbv)
        return tNx
     
    def func(x, a, b):
        return a * np.exp(-x/b)
     
    class DesintegrationNoyaux(Tk.LabelFrame):
     
        def __init__(self, master=None, **Arguments):
            Tk.LabelFrame.__init__(self, master, **Arguments)
            self._nb_atomes = Tk.IntVar()
            self._base = Tk.IntVar()
            self._zone_affichage = None
            self._canvas, self._fig, self.ax = None, None, None
     
            # Initialisation
            self.config(text="Désintégration des noyaux")
            self._nb_atomes.set(600)
            self._base.set(6)
     
            Tk.Label(self,text="Nombres d'atomes :").grid( row=0, column=0, padx=3, pady=3, sticky=Tk.E )
     
            var = Tk.Spinbox(self, textvariable= self._nb_atomes)
            var.config(width=10, justify=Tk.RIGHT)
            var.config(from_=1, to=1e9)
            var.grid( row=0, column=1, padx=3, pady=3 )
     
            Tk.Label(self,text="Base :").grid( row=1, column=0, padx=3, pady=3, sticky=Tk.E )
     
            var = Tk.Spinbox(self, textvariable= self._base)
            var.config(width=10, justify=Tk.RIGHT)
            var.config(from_=1, to=1e4)
            var.grid( row=1, column=1, padx=3, pady=3 )
     
            var = Tk.Button(self,text='Démarrer')
            var.config(command=self.lancer)
            var.grid( row=2, column=0, columnspan=2, padx=3, pady=3 )
     
            self._zone_affichage = ScrolledText(self)
            self._zone_affichage.config( width=25, height=15, relief=Tk.SUNKEN)
            self._zone_affichage.grid( row=3, column=0, columnspan=2, padx=3, pady=3 )
     
            fr = Tk.Frame(self)
            fr.grid(row=0, column=2, rowspan=6, padx=3, pady=3 )
     
            self._fig = Figure(figsize=(5,4))
            self._ax = self._fig.add_subplot(111)
     
            self._canvas = FigureCanvasTkAgg(self._fig, master=fr)
            self._canvas.show()
            self._canvas.get_tk_widget().pack( side=Tk.TOP, fill=Tk.BOTH, expand=1)
     
            toolbar = NavigationToolbar2TkAgg( self._canvas, fr)
            toolbar.update()
            self._canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
     
            # Disposition des widgets
            for i in range(6): self.rowconfigure(    i, weight=1 )
            for i in range(3): self.columnconfigure( i, weight=1 )
     
     
        def lancer(self):
            tab = desintegration_noyaux(self._nb_atomes.get(), self._base.get())
            n = np.size(tab)
     
            txt = "\n".join( [str(t) for t in tab] )
            self._zone_affichage.delete("1.0", Tk.END)
            self._zone_affichage.insert(Tk.END, txt)
            mssg = "\nIl a fallu %d tirages\n" % (n-1)
            self._zone_affichage.insert(Tk.END, mssg)
     
            self._ax.clear()
            x = np.arange(n)
            self._ax.plot( x, tab, 'ob', markersize=3)
     
            # Ajustement à une exponentielle
            params = [self._nb_atomes.get(), self._base.get()]
            popt, pcov = curve_fit( func, x, tab, p0=params)
    #        print "amplitude = %.3f +/- %.3f"  % (popt[0], np.sqrt(pcov[0, 0]))
    #        print "dilatation = %.3f +/- %.3f" % (popt[1], np.sqrt(pcov[1, 1]))
     
            xnew = np.linspace(x[0],x[-1], 512)
            ynew = func(xnew, popt[0], popt[1])
            self._ax.plot(xnew, ynew, color='r', linewidth=2)
     
    #        self._ax.set_yscale('log')
            self._canvas.show()
     
    if __name__ == '__main__':
        root = Tk.Tk()
        DesintegrationNoyaux().grid( padx=20, pady=20)
        root.rowconfigure(0, weight=1)
        root.columnconfigure(0, weight=1)
        root.mainloop()
    Images attachées Images attachées  

Discussions similaires

  1. Aide pour interface graphique
    Par Caro75150 dans le forum Débuter
    Réponses: 8
    Dernier message: 08/06/2011, 16h11
  2. Aide pour Interface graphique
    Par ahmedmrj dans le forum VB.NET
    Réponses: 19
    Dernier message: 02/05/2010, 20h55
  3. aide pour interface graphique
    Par matamine dans le forum Débuter
    Réponses: 6
    Dernier message: 25/11/2009, 08h55
  4. De l'aide pour interface graphiques en C
    Par rirou dans le forum C
    Réponses: 3
    Dernier message: 26/03/2007, 11h09
  5. aide pour interface graphique
    Par youp_db dans le forum GTK+ avec C & C++
    Réponses: 2
    Dernier message: 12/01/2007, 15h58

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