Saving file path in a variable using tkinter - python

I'm using tkinter to create a GUI for an old script I have, but I'm stuck right now.
I want to click a button to open the "Search File" window, choose a specific file and save its path in a variable.
The code I have is able to open the window, then I can select the file and display it's path, but I couldn't find a way to save this path in a variable.
This is what I have:
from tkinter import *
from tkinter import filedialog
def get_file_path():
# Open and return file path
file_path= filedialog.askopenfilename(title = "Select A File", filetypes = (("mov files", "*.png"), ("mp4", "*.mp4"), ("wmv", "*.wmv"), ("avi", "*.avi")))
l1 = Label(window, text = "File path: " + file_path).pack()
window = Tk()
# Creating a button to search the file
b1 = Button(window, text = "Open File", command = get_file_path).pack()
window.mainloop()
Does anyone know a good way to do this?

Use global variable:
from tkinter import *
from tkinter import filedialog
def get_file_path():
global file_path
# Open and return file path
file_path= filedialog.askopenfilename(title = "Select A File", filetypes = (("mov files", "*.png"), ("mp4", "*.mp4"), ("wmv", "*.wmv"), ("avi", "*.avi")))
l1 = Label(window, text = "File path: " + file_path).pack()
window = Tk()
# Creating a button to search the file
b1 = Button(window, text = "Open File", command = get_file_path).pack()
window.mainloop()
print(file_path)
Once your windows closed, you'll get your file_path.

You could declare file_path as global variable in get_file_path
def get_file_path():
global file_path
# Open and return file path
file_path= filedialog.askopenfilename(title = "Select A File", filetypes = (("mov files", "*.png"), ("mp4", "*.mp4"), ("wmv", "*.wmv"), ("avi", "*.avi")))
l1 = Label(window, text = "File path: " + file_path).pack()
Then you can access that variable from anywhere in the script
------Edit------
According to what you said in your comment, i say you could use tkinter.StringVar to save the file path, and then to access it later when calling count_frames as an argument.
It could be implemented as the following:
from tkinter import *
from tkinter import filedialog
file_path_var = StringVar()
def get_file_path():
# Open and return file path
file_path= filedialog.askopenfilename(title = "Select A File", filetypes = (("mov files", "*.png"), ("mp4", "*.mp4"), ("wmv", "*.wmv"), ("avi", "*.avi")))
file_path_var.set(file_path) #setting the variable to the value from file path
#Now the file_path can be acessed from inside the function and outside
file_path_var.get() # will return the value stored in file_path_var
l1 = Label(window, text = "File path: " + file_path).pack()
window = Tk()
# Creating a button to search the file
b1 = Button(window, text = "Open File", command = get_file_path).pack()
# will also return the value saved in file_path_var
file_path_var.get()
window.mainloop()
print(file_path)
So now where ever your count_frames function is, as long as you have selcted a file first you should be able to just do
count_frames(file_path_var.get())

Related

Update Label in Tkinter to prevent overlapping text

I'm new to Tkinter and I'm trying to create a simple Button that opens a file dialog box, where the user chooses which CSV file to open. Under the button there is a label that should display the file path for the file that was opened.
When I click on the button once, everything works as expected. However, if I click on it a second time and select a different file, the new filepath overlaps with the previous one, instead of replacing it.
Here is the code for the implementation function (please let me know if you need more bits of code for context):
def open_csv_file():
global df
global filename
global initialdir
initialdir = r"C:\Users\stefa\Documents\final project models\Case A"
filename = filedialog.askopenfilename(initialdir=initialdir,
title='Select a file', filetypes = (("CSV files","*.csv"),("All files","*.*")))
df = pd.read_csv(os.path.join(initialdir,filename))
lbl_ok = tk.Label(tab2, text = ' ') #tab2 is a ttk.Notebook tab
lbl_ok.config(text='Opened file: ' + filename)
lbl_ok.grid(row=0,column=1)
Here is how to do it with .config(), create the label instance just once (can then grid as much as you want but probably just do that once too), then just configure the text:
from tkinter import Tk, Button, Label, filedialog
def open_file():
filename = filedialog.askopenfilename()
lbl.config(text=f'Opened file: {filename}')
root = Tk()
Button(root, text='Open File', command=open_file).grid()
lbl = Label(root)
lbl.grid()
root.mainloop()
You can use a StringVar for this. Here is an example that may help you:
from tkinter import *
from tkinter.filedialog import askopenfilename
root = Tk()
root.geometry('200x200')
def openCsv():
csvPath.set(askopenfilename())
csvPath = StringVar()
entry = Entry(root, text=csvPath)
entry.grid(column=0, row=0)
btnOpen = Button(root, text='Browse Folder', command=openCsv)
btnOpen.grid(column=1, row=0)
root.mainloop()

Get the entry directory as a string in Tkinter Python

I am trying to make a Windows software using Tkinter from Python, the purpose of this app is to move specific types of files to a specified directory.
But the error comes here, it looks like that my move function ins't getting my entry text and also the extension text, so thats why I think there is the error, the code is here....
import tkinter.filedialog as filedialog
import tkinter as tk
import os
import shutil
def input_source():
input_path = tk.filedialog.askdirectory()
input_entry.delete(1, tk.END) # Remove current text in entry
input_entry.insert(0, input_path) # Insert the 'path'
def output():
output_path = tk.filedialog.askdirectory()
output_entry.delete(1, tk.END) # Remove current text in entry
output_entry.insert(0, output_path) # Insert the 'path'
def move():
files = os.listdir(input_entry.get())
for file in files: # for every file in the source directory
file_name, extension = os.path.splitext(file) # lets split the name of the file and its extension
if extension == f".{file_extension.get()}": # knowing what type of extension or type of file, lets just move
# those
# files to the new directory
shutil.move(f"{input_entry.get()}/{file}", output_entry.get())
else: # if there are any files with that extension, lets just pass\skip\terminate the process
pass
master = tk.Tk()
top_frame = tk.Frame(master)
bottom_frame = tk.Frame(master)
line = tk.Frame(master, height=1, width=400, bg="grey80", relief='groove')
# input path
input_path = tk.Label(top_frame, text="Input File Path:")
input_entry = tk.Entry(top_frame, text="", width=40)
browse1 = tk.Button(top_frame, text="Browse", command=input_source)
# output path
output_path = tk.Label(bottom_frame, text="Output File Path:")
output_entry = tk.Entry(bottom_frame, text="", width=40)
browse2 = tk.Button(bottom_frame, text="Browse", command=output)
# File extension
file_extension_ = tk.Label(bottom_frame, text="File type:")
file_extension = tk.Entry(bottom_frame, text="", width=40)
file_extension.insert(0, 'Type file extension: .')
move = tk.Button(bottom_frame, text='Move!', command=move)
top_frame.pack(side=tk.TOP)
line.pack(pady=10)
bottom_frame.pack(side=tk.BOTTOM)
input_path.pack(pady=5)
input_entry.pack(pady=5)
browse1.pack(pady=5)
output_path.pack(pady=5)
output_entry.pack(pady=5)
browse2.pack(pady=5)
file_extension.pack(pady=5)
file_extension.pack(pady=5)
move.pack(pady=20, fill=tk.X)
master.mainloop()
Simplify this and it should work. If you're just trying to move files to the typed path, why not do it this way?
from tkinter import *
import os
root = Tk()
root.title("File Mover")
def move_file():
firstpath = entry1.get()
secondpath = entry2.get()
os.replace(firstpath, secondpath)
label1 = Label(text="Enter File Directory to Move")
label2 = Label(text="Enter New File Directory")
entry1 = Entry(width=20, justify="center")
entry2 = Entry(width=20, justify="center")
button = Button(text="Move File", command=move_file)
label1.grid(row=0, column=0)
label2.grid(row=1,column=0)
entry1.grid(row=0,column=1)
entry2.grid(row=1, column=1)
button.grid(row=2,column=0)
root.mainloop()
this requires they include the name of the file in the path, but I guarantee that it will get the text, and that it works moving the files on my machine.

Python Tkinter Browsing a File- Issue

I am experiencing some issues when displaying the location of the image selected. Is there a reason why it displays <_io.TextIOWrapper name =along with mode='r'encoding ='cp1252>? I just want it to display the location of the image along with the name of the image not those extra stuff. Is there something that I am doing that is causing this to occur? Please advise.
def button(self):
self.button = ttk.Button(self.labelFrame, text = "Upload Image", command = self.fileDialog)
self.button.grid(column = 1, row = 1)
def fileDialog(self):
self.filename = filedialog.askopenfile(initialdir = "/", title = "Select a File", filetype = (("jpeg", "*.jpg"), ("All files", "*.")))
self.label = ttk.Label(self.labelFrame, text = "")
self.label.grid(column = 1, row = 2)
self.label.configure(text = self.filename)
filedialog.askopenfile gives file object, not file name.
You have to display self.filename.name instead of self.filename
Full working example
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
file_object = filedialog.askopenfile(title="Select file")
print('file_object:', file_object)
print('file_object.name:', file_object.name)
#data = file_object.read()
label = tk.Label(root, text=file_object.name)
label.pack()
root.mainloop()
Or use askopenfilename instead of askopenfile and you get file name.
Full working example
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
filename = filedialog.askopenfilename(title="Select file")
print('filename:', filename)
#data = open(filename).read()
label = tk.Label(root, text=filename)
label.pack()
root.mainloop()

How do I get the filename of a file to open and the filename of a file to save in python

I'm sorry about the unclear title, I don't really know how to put it, but I am trying to make a text editor in python. I want to get the filename of a file the user open or saves in python:
def openFile():
file = filedialog.askopenfile(parent=main_window, mode='rb', title='Select a file')
contents = file.read()
textArea.delete('1.0', END)
textArea.insert('1.0', contents)
file.close()
Here the user gets an dialog to select the file he wants to open. But how can I get the filename of the file he selects?
def saveFileas():
file = filedialog.asksaveasfile(mode='w')
data = textArea.get('1.0', END+'-1c')
file.write(data)
file.close()
Here the user gets a dialog to save his file, and input the name they want. Again, I need the name the user inputs. Both are using the default windows open and save dialog.
Here is all my code:
from tkinter import Tk, scrolledtext, Menu, filedialog, END
main_window = Tk(className = " Text Editor")
textArea = scrolledtext.ScrolledText(main_window, width=100, height=80)
# def newFile():
def openFile():
file = filedialog.askopenfile(parent=main_window, mode='rb', title='Select a file')
contents = file.read()
textArea.delete('1.0', END)
textArea.insert('1.0', contents)
file.close()
def saveFileas():
file = filedialog.asksaveasfile(mode='w')
data = textArea.get('1.0', END+'-1c')
file.write(data)
file.close()
def saveFile():
content = textArea.get('1.0', END+'-1c')
if content:
print("There is content")
else:
print("There is no content")
#Menu options
menu = Menu(main_window)
main_window.config(menu=menu)
fileMenu = Menu(menu)
menu.add_cascade(label="File", menu=fileMenu)
fileMenu.add_command(label="New")
fileMenu.add_command(label="Open", command=openFile)
fileMenu.add_command(label="Save As", command=saveFileas)
fileMenu.add_command(label="Save", command=saveFile)
fileMenu.add_separator()
fileMenu.add_command(label="Print")
fileMenu.add_separator()
fileMenu.add_command(label="Exit")
textArea.pack()
main_window.mainloop()
Something like this should work for getting the filename.
from tkinter import filedialog
root = Tk()
root.filename = filedialog.askopenfilename(initialdir = "Path Where the dialog should open first",title =
"Title of the dialog",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
print (root.filename)
root.withdraw()
The documentation seems to imply that askopenfile returns the filename, if one were selected, or an empty string, if the user clicked cancel. In other words, it's a string, not a file pointer. You'd need to open the file first.
askopenfile returns a handle to the file object like Brian Oakley said you can get the file name like so:
filePath = filedialog.askopenfile(parent=main_window, mode='rb', title='Select a file')
fileName = filePath.name.split('/').pop()

How to set to see end of text in Tkinter Entry widget?

I am making a gui interface to make my script available to general user. My question is - I have a entry widget which takes 'file path' as value when user picks a file using browse button. Problem is entry widget shows the beginning (left end) of file path but I would prefer to see the right end of the file path.
And here is my script.
from Tkinter import *
from tkFileDialog import askopenfilename
app = Tk()
app.title("ABC")
app.geometry("300x100")
def browse_for_file(entry_name, filetype):
File_path = askopenfilename(filetypes = filetype)
entry_name.delete(0, END)
entry_name.insert(0, File_path)
templ_filename = StringVar()
templ_entry = Entry(app, textvariable = templ_filename, width = 30)
templ_entry.grid(row = 3, column = 1, sticky=W)
filetype_fasta = [('fasta files', '*.fasta'), ('All files', '*.*')]
button_templ = Button(app, text = 'Browse', width =6, command = lambda:browse_for_file(templ_entry, filetype_fasta))
button_templ.grid(row = 3, column = 2)
app.mainloop()
Use
entry.xview_moveto(1)
xview_moveto() takes fractions, where 0 defines the left and 1 the right part.

Categories

Resources