How to select a Python file using Tkinter

Asked

Viewed 2,695 times

2

I have the following Python code using the library tkinter:

from tkinter import *


class Application:
 def __init__(self, master=None):
  self.widget1 = Frame(master)
  self.widget1.pack()
  self.msg = Label(self.widget1, text="Busque o arquivo")
  self.msg["font"] = ("Calibri", "9", "italic")
  self.msg.pack()
  self.sair = Button(self.widget1)
  self.sair["text"] = "Buscar"
  self.sair["font"] = ("Calibri", "9")
  self.sair["width"] = 10
  self.sair["command"] = self.mudarTexto
  self.sair.pack()
  self.msg2 = Label(self.widget1, text="")
  self.msg2["font"] = ("Calibri", "9", "italic")
  self.msg2.pack()

 def mudarTexto(self):
  if self.msg["text"] == "Busque o arquivo":
     #Teria que abrir a pasta do windows aqui
     self.msg2["text"] = "NOME DO ARQUIVO AQUI"



root = Tk()
Application(root)
root.mainloop()

At the moment this code just prints a message when the button is pressed, however, I would like to click the button, open a folder in windows to select only one file, and that after selected and given the Ok, the file name was printed in the program.

2 answers

3


from tkinter import Tk
from tkinter.filedialog import askopenfilename

Tk().withdraw() # Isto torna oculto a janela principal
filename = askopenfilename() # Isto te permite selecionar um arquivo
print(filename) # printa o arquivo selecionado

Follow other functions that may be of interest to you

3

To display file manipulation dialog boxes, use the sub-module functions tkinter.filedialog:

from tkinter import filedialog as dlg
path = dlg.askopenfilename()

Below is a list of the functions of this module, for reference:

askdirectory(**options)

Asks the user for a folder and returns the path to it

askopenfile(mode='r', **options)

Asks the user for a file, and already returns the opened file

askopenfilename(**options)

Asks the user for a file and returns the path to it

askopenfilenames(**options)

Asks the user to select multiple files. Returns a list of file names or an empty list if the user cancels the window.

askopenfiles(mode='r', **options)

Asks the user to select multiple files. Returns a list of already opened files or an empty list if the user cancels the window.

asksaveasfile(mode='w', **options)

Asks the user for a file name to be saved, and returns the file already created and opened for writing

asksaveasfilename(**options)

Asks the user for a file name to be saved, and returns the path to it. If the file already exists, the user will have to confirm overwrite.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.