I'm writing a function that allows my Tkinter GUI app user browse a directory and choose a file from it. So far, I have the code to open the directory but I'm having problems with saving a selected file from that directory to a variable that I can play around with.
The code I have so far - :
import os
def browsetone(self):
os.startfile("C:\Users\Chidumaga\Music\music")
The music directory is opened but how do I register the selection of a file ? Thanks in advance.
It is not very clear for me what you are trying to do. Anyway, it is tagged with Tkinter so I guess this is what you need:
from tkinter import *
from tkinter import filedialog
guiRoot = Tk()
startDir = "C:\Users\Chidumaga\Music\music"
someFileName = filedialog.askopenfilename(parent=guiRoot,title='Choose a file',initialdir=startDir)
if(someFileName!=""):
someFile = open(someFileName,'rb')
#read file contents
someFile.close()
guiRoot.mainloop()
Obviously opening a file dialog should be triggered by a button click or some similar event. It is up to you. Example of how to read binary file: Reading binary file in Python and looping over each byte
Related
I'm building an application using tkinter (and pygubu, this is relevant). In my application I need to browse a directory. This is the code of a button click callback (it's just inserting the path of the directory in a textbox object.
def chose_folder(self):
folder = fd.askdirectory()
txt = self.builder.get_object('folder_txt')
txt.delete(0, tk.END)
txt.insert(0, folder)
I've tried this code on Linux Mint 20.2, and it works fine, but on Windows 10, when I click the button, the program hangs and need to be forcibly terminated. However, if I change fd.askdirectory() with fd.askopenfilename(), or literally any other type of dialog, it works fine. The main difference I can see is that on linux, tkinter uses a custom dialog, while on Windows is uses the native Windows Explorer dialog.
Weirdly enough, I tried this minimal code
from tkinter import *
from tkinter.messagebox import *
from tkinter import filedialog as fd
file_name = fd.askdirectory()
print (file_name)
and it works perfectly, so I'm guessing the problem must be that I'm using pygubu to design the ui, but I can't figure out where the problem precisely is. I've found some old issues about this.
as I say in the title, when I click on a button (analyse) another windows open and I don't want it. The problems is, in the analyse function, the first line is an import of my tkinter file.
Thanks in advance for any help.
I tried to delete the import and the second windows does not pop up, so I am pretty sure it is the problem. Moreover I need to do this import in the analyse function because I already import the other module in my tkinter file
tkinter file :
import fileb
def analyser():
output=fileb.analyse(name)
fenetre = Tk()
fenetre.geometry("800x500")
label = Label(fenetre, text='Emotion Video')
label.pack()
boutonanalyse=Button(fenetre, text='analyze', command=analyser)
boutonanalyse.pack(side=BOTTOM)
fileb :
def analyse(name):
import tkinter_essais
When you import your Tkinter file, you are running that file. This means that the code is run twice and so you have two windows opened up. A way to bypass this is by putting your tkinter setup into a function, and having that run if it is the main program only using something like this:
import fileb
def analyser():
output=fileb.analyse(name)
def tkSetup():
fenetre = Tk()
fenetre.geometry("800x500")
label = Label(fenetre, text='Emotion Video')
label.pack()
boutonanalyse=Button(fenetre, text='analyze', command=analyser)
boutonanalyse.pack(side=BOTTOM)
if "__name__" == "__main__":
tkSetup()
The if name == main checks if the program is being run originally (best way I can think to describe it) and so it wont be run if you import the file.
I have a question about the askdirectory() in tkinter. Is it posible to use that function and also se what´s inside the folder that i want to select the directory from?
Because now when i use the function i can open the explorer and get the directory path to the folder i need but i can´t se what the folder contains (I just now that now before hand for now)... With the askdirectory function the folder says "No items match your search.". So i came up with this:
filepath_ask = filedialog.askdirectory(
initialdir=os.path.dirname(filedialog.askopenfilename(title ="Pick a folder in directory with .log files")),
title = "Press 'Select Folder'")
But it´s not that "user friendly". First it opens a window with askopenfilename so that i can see the content in the folder, then it closes when i select a file and opens a new window with askdirectory to "Select Folder" that has the content/file i chose in the window before. There must be a better way? I have been reding upp on the dokumentatin but can´t find anything that works. Help would be appreciated! Thanks
If you think that it isn't as much of a bother to have the user select a file in the askopenfilename dialog, then why not just run with that (and skip askdirectory altogether):
import tkinter as tk
from tkinter import filedialog
import pathlib
root = tk.Tk()
ask = filedialog.askopenfilename(title="Select a directory", filetypes = [("log",".log"),("All Files",".*")])
print(f"User selected Directory: {pathlib.Path(ask).resolve().parent}")
root.destroy()
I would like to open a new browser by clicking Button from python tkinker GUI and new directory need to be saved and display on GUI.
I am able to open current directory with command below;
import os
subprocess.Popen('explorer "C:\temp"')
cur_path = os.path.dirname(__file__)
my question is how to save the active browser dir and display on GUI after Step A/B above?
First of all, the imports needed for this answer:
import os
import tkinter as tk # if using Python 3
import Tkinter as tk # if using Python 2
Let's say that your button has been defined.
Here is some sample code which will get the current directory:
curr_directory = os.getcwd() # will get current working directory
If you're looking to set up a GUI to ask the user to select a file, use:
name = tkinter.tkFileDialog.askopenfilename(initialdir = curr_directory,title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
print(name)
Which will store the file that they have chosen, with the directory they start at set to curr_directory which is the current directory.
If you are instead looking to set up a GUI in which the user chooses a directory, you can use:
dir_name = tk.tkFileDialog.askdirectory()
This will store the name of the directory they have chosen in the dir_name variable.
For more information, check out this link on how to use the file dialog. Alternatively, you can check the general tkinter documentation here (for Python 2) and here (for Python 3). If you need a reference to the file dialog, this is a good source.
I am making a program to manage a database and i need a nice way of choosing the save locations of files within the program. I was wondering if it is possible to open windows explore from my program, select a folder to save a file in, enter the file name and return the file path as a string to the main program.
Look up the Tkinter options in tkFileDialog
I don't think you necessarily need to put together a fully working GUI, you can simply call the method and select a folder location and then use that selected location in your code.
A simplistic example would be:
import Tkinter, tkFileDialog
root = Tkinter.Tk()
x = tkFileDialog.askopenfilename() # Can pass optional arguments for this...
root.destroy()