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 :

[Tkinter] Créa et modif texte dans canvas


Sujet :

Tkinter Python

  1. #1
    Membre éclairé
    Avatar de airod
    Homme Profil pro
    Gérant Associé, DMP Santé et Directeur technique
    Inscrit en
    Août 2004
    Messages
    767
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 48
    Localisation : France, Essonne (Île de France)

    Informations professionnelles :
    Activité : Gérant Associé, DMP Santé et Directeur technique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Août 2004
    Messages : 767
    Points : 891
    Points
    891
    Par défaut [Tkinter] Créa et modif texte dans canvas
    Bonjour,
    voici un script que j'ai ecrit pour créer du texte dans un Canvas.
    Le but est de pouvoir modifier de facon dynamique par le panneau correspondant les attribut du texte.

    Il fonctionne correctement sauf que lorsque je crée un 2 eme texte, je ne peux plus modifier les attribut du premier texte.
    Malgré qques semaines de recherche sur ce problème je bloque littéralement.
    Pourriez vous m'aider?!

    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
    # -*- coding: cp1252 -*-
    import Tkinter as tk
    import Image
    import tkFont
    from tkColorChooser import askcolor
     
     
    class ajouttexte:
        def __init__(self):
     
            self.Dic_TXT=[]
            self.texte='Your Texte'
            self.size=36
            self.familly="Helvetica"
            self.style='normal'
            self.color='black'
            self.root=tk.Tk()
            self.root.title('création de texte')
     
            self.canvas=tk.Canvas(self.root,width=500,height=500,bg='white')
            self.canvas.grid()
            self.canvas.bind('<Button-1>',self.crea)
     
            #attribut=tk.Button(self.root,text='couleur',command=self.setBgColor)
            #attribut.grid()
     
            quitter=tk.Button(self.root,text='quitter',command=self.root.quit)
            quitter.grid()
     
            self.root.mainloop()
            self.root.destroy()
     
        def setBgColor(self):
            (triple, hexstr) = askcolor()
            if hexstr:
                self.color= hexstr
                self.champcolor.delete(0,tk.END)
                self.champcolor.insert(0,self.color)
                self.applychange(event=tk.NONE)
     
     
        def crea(self,event):
            self.font=tkFont.Font(family=(self.familly),size=(self.size),weight=(self.style))
            self.txt=self.canvas.create_text(event.x,event.y,fill=self.color,text=self.texte,font=self.font)
            self.Dic_TXT.append([self.txt,event.x,event.y,self.texte,self.familly,self.style,self.size])
            self.x,self.y=event.x,event.y
            print self.Dic_TXT
            self.modiftextpan()
     
     
        def modiftextpan(self):
            self.top=tk.Toplevel()
            self.top.title('Attributs de texte')
            self.attribut()
            #tk.Button(frametop,width=64,text='Fermer',command=self.top.destroy).grid()
     
        def attribut(self):
            frametop=tk.Frame(self.top)
            frametop.grid()
            tk.Label(frametop,text='ID texte').grid(column=0,row=0,padx=3,pady=3)
            self.id=tk.Label(frametop,width=20,text=self.txt)
            self.id.grid(column=1,row=0)
     
            tk.Label(frametop,text='Texte').grid(column=0,row=1,padx=3,pady=3)
            self.champtxt=tk.Entry(frametop,width=50)
            self.champtxt.bind('<FocusOut>',self.applychange)
            self.champtxt.bind('<FocusIn>',self.seltxt)
            self.champtxt.bind('<Return>',self.applychange)
            self.champtxt.grid(column=1,row=1,columnspan=3,padx=3,pady=3)
            self.champtxt.insert(0,self.texte)
     
            tk.Label(frametop,text='Police').grid(column=0,row=2,padx=3,pady=3)
            self.champfont=tk.Entry(frametop)
            self.champfont.bind('<FocusOut>',self.applychange)
            self.champfont.bind('<FocusIn>',self.seltxt)
            self.champfont.bind('<Return>',self.applychange)
            self.champfont.grid(column=1,row=2,padx=3,pady=3)
            self.champfont.insert(0,self.familly)
     
            tk.Label(frametop,text='Taille').grid(column=2,row=2,padx=3,pady=3)
            self.champtaille=tk.Entry(frametop)
            self.champtaille.bind('<FocusOut>',self.applychange)
            self.champtaille.bind('<FocusIn>',self.seltxt)
            self.champtaille.bind('<Return>',self.applychange)
            self.champtaille.grid(column=3,row=2,padx=3,pady=3)
            self.champtaille.insert(0,self.size)
     
            tk.Label(frametop,text='Style').grid(column=0,row=3,padx=3,pady=3)
            self.champstl=tk.Entry(frametop)
            self.champstl.bind('<FocusOut>',self.applychange)
            self.champstl.bind('<FocusIn>',self.seltxt)
            self.champstl.bind('<Return>',self.applychange)
            self.champstl.grid(column=1,row=3,padx=3,pady=3)
            self.champstl.insert(0,self.style)
     
            tk.Label(frametop,text='Couleur').grid(column=2,row=3,padx=3,pady=3)
            self.champcolor=tk.Entry(frametop)
            self.champcolor.bind('<FocusOut>',self.applychange)
            self.champcolor.bind('<FocusIn>',self.seltxt)
            self.champcolor.bind('<Return>',self.applychange)
            self.champcolor.grid(column=3,row=3,padx=3,pady=3)
            self.champcolor.insert(0,self.color)
     
            tk.Button(frametop,text='...',width=2,command=self.setBgColor).grid(column=4,row=3,padx=3,pady=3)
     
     
     
        def seltxt(self,event):
            self.txt=int(self.id.cget("text"))
            print self.txt
     
        def applychange(self,event):
            print self.champtaille.get()*(-1)
            self.font=tkFont.Font(family=(self.champfont.get()),size=(int(self.champtaille.get())*(-1)),
                                  weight=(self.champstl.get()))
     
            self.canvas.delete(self.txt)
     
     
            for i in self.Dic_TXT:
                if i[0]==self.txt:
                    self.txt=i[0]
                    self.Dic_TXT.remove(i)
     
     
                else:
                    pass
            self.canvas.find_withtag(self.id)
            self.txt=self.canvas.create_text(self.x,self.y,fill=(self.champcolor.get()),
                                             text=(self.champtxt.get()),font=self.font)
            self.Dic_TXT.append([self.txt,self.x,self.y,(self.champtxt.get()),
                                 (self.champfont.get()),(self.champstl.get()),(self.champtaille.get())])
            self.id.configure(text=self.txt)
     
     
     
            print self.Dic_TXT
     
     
    if __name__ == "__main__":
        app=ajouttexte()
    je pense que je n'ai peut être pas composé mon modéle correctement. Mais je ne sais pas comment appréhender ce type de problème.
    Merci par avance.

  2. #2
    Membre averti
    Avatar de Alain_72
    Inscrit en
    Août 2004
    Messages
    180
    Détails du profil
    Informations forums :
    Inscription : Août 2004
    Messages : 180
    Points : 342
    Points
    342
    Par défaut
    En fait, tu ne peux pas accéder aux objets d'un canvas et les configurer sans les avoir taggés au préalable.
    C'est pourquoi à chaque fois que tu cliquais sur le canvas, une nouvelle instance de texte se créait même si tu cliquais dans un texte.
    Par contre, avec la méthode tag_bind() du canvas, tu peux récupérer l'évènement click sur un objet, et avec la méthode find_closest() récupérer l'objet en question.

    Je t'ai fait un exemple à partir de ton code :

    J'ai fait ça sous forme d'une classe par grande phase du projet.

    Une classe pour la fenêtre principale
    Une classe pour le canvas
    Et une classe pour la fenêtre de modification des attributs

    Tu peux étudier tout ça tout à ton aise...
    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
    #! /usr/bin/env python
    #-*- coding: iso-8859-15 -*-
     
    import Tkinter as tk
    import Image
    import tkFont
    from tkColorChooser import askcolor
     
    class Attributs(tk.Toplevel):
    	def __init__(self, controle, IDText, creation = False):
    		tk.Toplevel.__init__(self)
    		self.creation = creation
    		self.title("Attributs du texte")
    		self.canvas = controle
    		self.objet = IDText
    		self.tag = "obj" + str(self.objet)
    		frametop=tk.Frame(self)
    		frametop.grid()
    		tk.Label(frametop,text='ID texte').grid(column=0,row=0,padx=3,pady=3)
    		self.id=tk.Label(frametop,width=20,text=IDText)
    		self.id.grid(column=1,row=0)
     
    		tk.Label(frametop,text='Texte').grid(column=0,row=1,padx=3,pady=3)
    		self.champtxt=tk.Entry(frametop,width=50)
                    self.champtxt.grid(column=1,row=1,columnspan=3,padx=3,pady=3)
    		self.champtxt.insert(0,self.canvas.itemcget(self.objet, "text"))
     
    		font = self.canvas.GetFont(self.objet)
     
    		tk.Label(frametop,text='Police').grid(column=0,row=2,padx=3,pady=3)
    		self.champfont=tk.Entry(frametop)
    		self.champfont.grid(column=1,row=2,padx=3,pady=3)
    		self.champfont.insert(0,font.cget("family"))
     
    		tk.Label(frametop,text='Taille').grid(column=2,row=2,padx=3,pady=3)
    		self.champtaille=tk.Entry(frametop)
    		self.champtaille.grid(column=3,row=2,padx=3,pady=3)
    		self.champtaille.insert(0,font.cget("size"))
     
    		tk.Label(frametop,text='Style').grid(column=0,row=3,padx=3,pady=3)
    		self.champstl=tk.Entry(frametop)
    		self.champstl.grid(column=1,row=3,padx=3,pady=3)
    		self.champstl.insert(0,font.cget("weight"))
     
    		tk.Label(frametop,text='Couleur').grid(column=2,row=3,padx=3,pady=3)
    		self.champcolor=tk.Entry(frametop)
    		self.champcolor.grid(column=3,row=3,padx=3,pady=3)
    		self.champcolor.insert(0,self.canvas.itemcget(self.objet, "fill"))
     
    		tk.Button(frametop,text='...',width=2,command=self.setBgColor).grid(column=4,row=3,padx=3,pady=3)
    		self.valider = tk.Button(frametop, text="Valider", command=self.Valider)
    		self.valider.grid(column=1, row=4, padx=3,pady=3)
    		self.annuler = tk.Button(frametop, text="Annuler", command=self.Annuler)
    		self.annuler.grid(column=3, row=4, padx=3,pady=3)
     
    	def Annuler(self):
    		if self.creation:
    			self.canvas.delete(self.tag)
    			self.canvas.SupprimeFont(self.objet)
    		self.destroy()
     
    	def Valider(self):
    		self.canvas.itemconfigure(self.tag, text=self.champtxt.get())
    		newfont = tkFont.Font(family=self.champfont.get(),size=str(self.champtaille.get()),weight=self.champstl.get())
    		self.canvas.itemconfigure(self.tag, font=newfont)
    		self.canvas.itemconfigure(self.tag, fill=self.champcolor.get())
    		self.canvas.SetFont(self.objet, newfont)
    		self.destroy()
     
    	def setBgColor(self):
    		(triple, hexstr) = askcolor()
    		if hexstr:
    			self.color= hexstr
    			self.champcolor.delete(0,tk.END)
    			self.champcolor.insert(0,self.color)
                    self.focus_set()
     
    class MonCanvas(tk.Canvas):
    	def __init__(self, parent):
    		tk.Canvas.__init__(self, parent, width=500,height=500,bg='white')
    		self.numTag = 0
    		self.drapeau = False
    		self.MesItemsFonts = {}
    		self.texte='Your Texte'
    		self.size=36
    		self.familly="Helvetica"
    		self.style='normal'
    		self.color='black'
     
    		self.bind('<Button-1>',self.crea)
     
    	def crea(self, event):
    		if self.drapeau:
    			self.drapeau = False
    		else:
    			font=tkFont.Font(family=(self.familly),size=(self.size),weight=(self.style))
    			self.numTag += 1
    			tag = "obj" + str(self.numTag)
    			txt=self.create_text(event.x,event.y,fill=self.color,text=self.texte,font=font, tags=tag)
    			self.tag_bind(tag, '<Button-1>',self.modif)
    			self.MesItemsFonts[txt]=font
    			attrib = Attributs(self, txt, True)
     
    	def GetFont(self, IDItem):
    		return self.MesItemsFonts[IDItem]
     
    	def SetFont(self, IDItem, font):
    		self.MesItemsFonts[IDItem] = font
     
    	def SupprimeFont(self, IDItem):
    		del self.MesItemsFonts[IDItem]
     
    	def modif(self, event):
    		self.drapeau = True
    		objet = event.widget.find_closest(event.x, event.y)[0]
    		attrib = Attributs(self, objet)
     
    class Fenetre(tk.Tk):
    	def __init__(self, titre):
    		tk.Tk.__init__(self)
    		self.title(titre)
    		canvas = MonCanvas(self)
    		canvas.grid()
    		quitter=tk.Button(self,text='quitter',command=self.quit)
    		quitter.grid()
     
    if __name__ == "__main__":
    	root = Fenetre("Création de fenêtre")
    	root.mainloop()
    Je ne traite pas les problèmes techniques par MP...
    Les forums sont là pour ça...

    Les contributions du bipede

  3. #3
    Membre éclairé
    Avatar de airod
    Homme Profil pro
    Gérant Associé, DMP Santé et Directeur technique
    Inscrit en
    Août 2004
    Messages
    767
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 48
    Localisation : France, Essonne (Île de France)

    Informations professionnelles :
    Activité : Gérant Associé, DMP Santé et Directeur technique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Août 2004
    Messages : 767
    Points : 891
    Points
    891
    Par défaut
    merci beaucoup pour cet exemple,

    je vais etudier tout ca.

    merci.

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

Discussions similaires

  1. Réponses: 0
    Dernier message: 04/04/2015, 09h12
  2. modification texte dans animation flash
    Par étudiante3 dans le forum Flash
    Réponses: 1
    Dernier message: 07/05/2007, 16h08
  3. modification texte dans fichier
    Par Mick_Lisah dans le forum Langage
    Réponses: 1
    Dernier message: 08/03/2007, 07h54
  4. Modification d'un texte dans une fenetre "d'erreur"
    Par PAUL87 dans le forum Access
    Réponses: 8
    Dernier message: 21/10/2005, 13h12
  5. Modification texte dans un fichier
    Par byloute dans le forum Shell et commandes GNU
    Réponses: 9
    Dernier message: 04/10/2005, 15h34

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