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 :

[résolu] récupérer nom fichier avec tkFileDialog


Sujet :

Tkinter Python

  1. #1
    Futur Membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Janvier 2013
    Messages
    19
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Janvier 2013
    Messages : 19
    Points : 6
    Points
    6
    Par défaut [résolu] récupérer nom fichier avec tkFileDialog
    Bonjour,
    J'essaie de me lancer dans les interfaces graphiques avec Python. J'aimerais construire une fenêtre comportant plusieurs éléments, dont 1 bouton permettant d'ouvrir un fichier, un autre permettant de sauvegarder un fichier et un autre permettant d'appeler un script avec le nom des fichiers en paramètre.

    Suite à mes recherches j'ai vu que ça pouvait se faire avec tkFileDialog, j'ai d'ailleurs trouvé un petit exemple ici.
    Seul hic, je ne parviens pas à récupérer le chemin du fichier... Voici ce que j'ai fait :

    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
    import Tkinter, Tkconstants, tkFileDialog
     
    class TkFileDialogExample(Tkinter.Frame):
     
    	def __init__(self, root):
     
    		Tkinter.Frame.__init__(self, root)
     
    		# define buttons
    		Tkinter.Label(self, text="Input file").grid(row=0, column=0, sticky='W')
    		input_tb = Tkinter.Entry(self, width=20)
    		input_tb.grid(row=0, column=1)
    		Tkinter.Button(self, text='browse', command=self.askopenfilename, width=3).grid(row=0, column=2)
     
    		Tkinter.Label(self, text="Output file").grid(row=1, column=0, sticky='W')
    		output_tb = Tkinter.Entry(self, width=20)
    		output_tb.grid(row=1, column=1)
    		Tkinter.Button(self, text='browse', command=self.asksaveasfilename, width=3).grid(row=1, column=2)
     
    		Tkinter.Button(self, text='send', command=self.send, width=5).grid(row=2, column=1)
     
    	def askopenfilename(self):
    		self.file_opt = options = {}
    		options['filetypes'] = [('all files', '.*'), ('text files', '.txt')]
    		return tkFileDialog.askopenfilename(**self.file_opt)
     
    	def asksaveasfilename(self):
    		self.file_opt = options = {}
    		options['filetypes'] = [('all files', '.*'), ('text files', '.txt')]
    		options['defaultextension'] = '.txt'
    		options['initialfile'] = 'myfile.txt'
    		return tkFileDialog.asksaveasfilename(**self.file_opt)
     
    	def send(self):
    		print 'Opened file: '
    		print 'Saved file: '
     
    if __name__=='__main__':
    	root = Tkinter.Tk()
    	TkFileDialogExample(root).pack()
    	root.title("Test")
    	root.geometry("300x100")
    	root.mainloop()
    Je ne sais pas quoi mettre dans mon print pour afficher les fichiers sélectionnés. Par ailleurs j'aimerais également mettre à jour les champs de text à gauche des boutons mais même problème.

    Un petit coup de main ?
    Merci !

  2. #2
    Expert éminent

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

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

    Les fonctions appelées par les boutons se terminent par un return.

    return à qui ? au bouton ?

  3. #3
    Futur Membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Janvier 2013
    Messages
    19
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Janvier 2013
    Messages : 19
    Points : 6
    Points
    6
    Par défaut
    Citation Envoyé par VinsS Voir le message
    Salut,

    Les fonctions appelées par les boutons se terminent par un return.

    return à qui ? au bouton ?
    Justement je sais pas trop, j'ai tiré ça de l'exemple.

  4. #4
    Invité
    Invité(e)
    Par défaut
    Citation Envoyé par roipoussiere Voir le message
    Bonjour,
    J'essaie de me lancer dans les interfaces graphiques avec Python. J'aimerais construire une fenêtre comportant plusieurs éléments, dont 1 bouton permettant d'ouvrir un fichier, un autre permettant de sauvegarder un fichier et un autre permettant d'appeler un script avec le nom des fichiers en paramètre.

    Suite à mes recherches j'ai vu que ça pouvait se faire avec tkFileDialog, j'ai d'ailleurs trouvé un petit exemple ici.
    Seul hic, je ne parviens pas à récupérer le chemin du fichier... Voici ce que j'ai fait :

    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
    import Tkinter, Tkconstants, tkFileDialog
     
    class TkFileDialogExample(Tkinter.Frame):
     
    	def __init__(self, root):
     
    		Tkinter.Frame.__init__(self, root)
     
    		# define buttons
    		Tkinter.Label(self, text="Input file").grid(row=0, column=0, sticky='W')
    		input_tb = Tkinter.Entry(self, width=20)
    		input_tb.grid(row=0, column=1)
    		Tkinter.Button(self, text='browse', command=self.askopenfilename, width=3).grid(row=0, column=2)
     
    		Tkinter.Label(self, text="Output file").grid(row=1, column=0, sticky='W')
    		output_tb = Tkinter.Entry(self, width=20)
    		output_tb.grid(row=1, column=1)
    		Tkinter.Button(self, text='browse', command=self.asksaveasfilename, width=3).grid(row=1, column=2)
     
    		Tkinter.Button(self, text='send', command=self.send, width=5).grid(row=2, column=1)
     
    	def askopenfilename(self):
    		self.file_opt = options = {}
    		options['filetypes'] = [('all files', '.*'), ('text files', '.txt')]
    		return tkFileDialog.askopenfilename(**self.file_opt)
     
    	def asksaveasfilename(self):
    		self.file_opt = options = {}
    		options['filetypes'] = [('all files', '.*'), ('text files', '.txt')]
    		options['defaultextension'] = '.txt'
    		options['initialfile'] = 'myfile.txt'
    		return tkFileDialog.asksaveasfilename(**self.file_opt)
     
    	def send(self):
    		print 'Opened file: '
    		print 'Saved file: '
     
    if __name__=='__main__':
    	root = Tkinter.Tk()
    	TkFileDialogExample(root).pack()
    	root.title("Test")
    	root.geometry("300x100")
    	root.mainloop()
    Je ne sais pas quoi mettre dans mon print pour afficher les fichiers sélectionnés. Par ailleurs j'aimerais également mettre à jour les champs de text à gauche des boutons mais même problème.

    Un petit coup de main ?
    Merci !
    Bonjour,

    Des réponses récentes à des pbs similaires ont été données ici :

    http://www.developpez.net/forums/d14...ory-image-jpg/

    http://www.developpez.net/forums/d14...-filtre-sepia/

    @+.

  5. #5
    Expert éminent

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

    Informations forums :
    Inscription : Octobre 2008
    Messages : 4 300
    Points : 6 780
    Points
    6 780
    Par défaut
    Je ne sais pas ce que tu comptes faire avec le fichier mais admettons que tu veuilles le lire et que tu as créer pour ça une fonction read_text(self, filename)

    Alors ton code devra ressembler à ceci:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
     
    	def askopenfilename(self):
    		self.file_opt = options = {}
    		options['filetypes'] = [('all files', '.*'), ('text files', '.txt')]
    		path = tkFileDialog.askopenfilename(**self.file_opt)
                    self.read_text(path)
     
            def read_text(self, filename):
                ...

  6. #6
    Futur Membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Janvier 2013
    Messages
    19
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Janvier 2013
    Messages : 19
    Points : 6
    Points
    6
    Par défaut
    Citation Envoyé par tarball69 Voir le message
    Bonjour,

    Des réponses récentes à des pbs similaires ont été données ici :

    http://www.developpez.net/forums/d14...ory-image-jpg/

    http://www.developpez.net/forums/d14...-filtre-sepia/

    @+.
    Merci, du coup j'ai placé mes nom de fichiers dans des self.input_file et self.output_file.
    J'appelle self.input_tb.insert(0, self.input_file) dans chacune des mes fonctions de selection de fichier pour mettre à jour le champ.

    Mon programme ressemble maintenant à 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
    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
    import Tkinter, Tkconstants, tkFileDialog
     
    class TkFileDialogExample(Tkinter.Frame):
    	input_file = ''
    	output_file = ''
     
    	def __init__(self, root):
    		Tkinter.Frame.__init__(self, root)
     
    		# define buttons
    		Tkinter.Label(self, text="Input file").grid(row=0, column=0, sticky='W')
    		self.input_tb = Tkinter.Entry(self, width=30)
    		self.input_tb.grid(row=0, column=1)
    		Tkinter.Button(self, text='browse', command=self.askopenfilename, width=3).grid(row=0, column=2)
     
    		Tkinter.Label(self, text="Output file").grid(row=1, column=0, sticky='W')
    		self.output_tb = Tkinter.Entry(self, width=30)
    		self.output_tb.grid(row=1, column=1)
    		Tkinter.Button(self, text='browse', command=self.asksaveasfilename, width=3).grid(row=1, column=2)
     
    		Tkinter.Button(self, text='send', command=self.send, width=5).grid(row=2, column=1)
     
    	def askopenfilename(self):
    		self.file_opt = options = {}
    		options['filetypes'] = [('all files', '.*'), ('text files', '.txt')]
    		self.input_file = tkFileDialog.askopenfilename(**self.file_opt)
    		self.input_tb.insert(0, self.input_file)
     
    	def asksaveasfilename(self):
    		self.file_opt = options = {}
    		options['filetypes'] = [('all files', '.*'), ('text files', '.txt')]
    		options['defaultextension'] = '.txt'
    		options['initialfile'] = 'myfile.txt'
    		self.output_file = tkFileDialog.asksaveasfilename(**self.file_opt)
    		self.output_tb.insert(0, self.output_file)
     
    	def send(self):
    		print 'input file: ', self.input_file
    		print 'output file: ', self.output_file
     
    if __name__=='__main__':
    	root = Tkinter.Tk()
    	TkFileDialogExample(root).pack()
    	root.title("Test")
    	root.geometry("400x100")
    	root.mainloop()
    Merci beaucoup !
    @VinsS : bien noté, ceci dit le script derrière est assez complexe et je préfère l’appeler en une seule fois avec tous les paramètres.

    Tant qu'à faire, comme je débute, vous avez peut-être des conseils ou remarques à me donner sur ce code, ça vous parait correct et pythonique ?

  7. #7
    Invité
    Invité(e)
    Par défaut
    Citation Envoyé par roipoussiere Voir le message
    Merci, du coup j'ai placé mes nom de fichiers dans des self.input_file et self.output_file.
    J'appelle self.input_tb.insert(0, self.input_file) dans chacune des mes fonctions de selection de fichier pour mettre à jour le champ.
    (snip)(snip)
    Tant qu'à faire, comme je débute, vous avez peut-être des conseils ou remarques à me donner sur ce code, ça vous parait correct et pythonique ?
    Bonjour,

    bah, tant que ça fonctionne OK...

    Après, si vous voulez vraiment chercher le détail, oui, il y a toujours moyen d'améliorer le 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
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
     
    import Tkinter as TK
     
    import tkFileDialog as FD
     
     
    class TkFileDialogExample(TK.Tk):
        """
            cette classe bla bla bla... explications
        """
     
        def __init__(self):
     
            # superclass inits
            TK.Tk.__init__(self)
     
            # member inits
            self.file_in = ""
            self.file_out = ""
     
            # widget inits
            TK.Label(
                self,
                text="Input file",
            ).grid(row=0, column=0, sticky=TK.W)
     
            self.input_tb = TK.Entry(self, width=30)
            self.input_tb.grid(row=0, column=1)
     
            TK.Button(
                self,
                text="browse",
                command=self.dlg_file_open, # avoid confusing names /!\
            ).grid(row=0, column=2)
     
            TK.Label(
                self,
                text="Output file",
            ).grid(row=1, column=0, sticky=TK.W)
     
            self.output_tb = TK.Entry(self, width=30)
            self.output_tb.grid(row=1, column=1)
     
            TK.Button(
                self,
                text="browse",
                command=self.dlg_file_save_as,
            ).grid(row=1, column=2)
     
            TK.Button(
                self,
                text="send",
                command=self.send,
            ).grid(row=2, column=1)
     
        # end def
     
     
        def dlg_file_open(self):
            """
                cette méthode bla bla bla... explications
            """
     
            self.file_in = FD.askopenfilename(
     
                filetypes=[("all files", ".*"), ("text files", ".txt")],
            )
     
            self.input_tb.delete(0, TK.END)
     
            self.input_tb.insert(0, self.file_in)
     
        # end def
     
     
        def dlg_file_save_as(self):
            """
                cette méthode bla bla bla... explications
            """
     
            self.file_out = FD.asksaveasfilename(
     
                filetypes=[("all files", ".*"), ("text files", ".txt")],
     
                defaultextension=".txt",
     
                initialfile="myfile.txt",
            )
     
            self.output_tb.delete(0, TK.END)
     
            self.output_tb.insert(0, self.file_out)
     
        # end def
     
     
        def send(self):
            """
                cette méthode bla bla bla... explications
            """
     
            print "input file:", self.file_in
     
            print "output file:", self.file_out
     
        # end def
     
    # end class TkFileDialogExample
     
     
    if __name__ == "__main__":
     
        TkFileDialogExample().mainloop()
     
    # end if
    Sinon, il reste l'éternelle PEP 8 : http://legacy.python.org/dev/peps/pep-0008/

    @+.

Discussions similaires

  1. Récupérer un fichier avec cURL
    Par pcayrol dans le forum Langage
    Réponses: 1
    Dernier message: 23/04/2010, 09h33
  2. Récupérer nom fichier sans extension
    Par Newenda dans le forum MATLAB
    Réponses: 3
    Dernier message: 07/12/2009, 15h49
  3. Probléme nom fichier avec WIMNN.dll
    Par miabi dans le forum VB.NET
    Réponses: 2
    Dernier message: 12/10/2009, 22h57
  4. Réponses: 2
    Dernier message: 30/08/2007, 23h15
  5. [VBA]récupérer nom fichier
    Par jackfred dans le forum Général VBA
    Réponses: 4
    Dernier message: 27/04/2007, 19h57

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