I have a python script that takes the file path and runs the following script:
file = 'C:/Users/crist/Downloads/Fraction_Event_Report_Wednesday_June_16_2021_20_27_38.pdf'
lines = []
with pdfplumber.open(file) as pdf:
pages = pdf.pages
for page in pdf.pages:
text = page.extract_text()
print(text)
I have created an entry box with tkinter:
import tkinter as tk
master = tk.Tk()
tk.Label(master,
text="File_path").grid(row=0)
e = tk.Entry(master)
e.grid(row=0, column=1)
tk.Button(master,
text='Run Script',
command=master.quit).grid(row=3,
column=0,
sticky=tk.W,
pady=4)
tk.mainloop()
I would like to assign the File_path imputed in the entry box by the user to the "file" in the script and run the script when pressing the "Run Script" button. How can I do that?
It's better to spawn a file dialog instead of using a tkinter.Entry:
# GUI.py
from tkinter.filedialog import askopenfilename
import tkinter as tk
# Create the window and hide it
root = tk.Tk()
root.withdraw()
# Now you are free to popup any dialog that you need
filetypes = (("PDF file", "*.pdf"), ("All files", "*.*"))
filepath = askopenfilename(filetypes=filetypes)
# Now use the filepath
lines = []
with pdfplumber.open(filepath) as pdf:
...
# Destroy the window
root.destroy()
I want to get a music on playlist and load it, but it's returning :
File "c:/Users/User/Documents/Python-testes/teste-2.py", line 25, in play
mixer.music.load(filenames)
pygame.error: Couldn't open 'C:/Python/Playlist/BØRNS - Electric Love.mp3'
I tried to use the .wav archive too but keeps returning this error, I'm using the vsc and the Python 3.8.8 version and pygame 2.0.1, this is my code:
from tkinter import Listbox, Tk
from tkinter import Label
from tkinter import Button
from tkinter import filedialog
from tkinter.constants import ACTIVE, END
from pygame import mixer
import pygame
def play_song():
filenames = list(filedialog.askopenfilenames(initialdir = "C:/Python/Playlist/", title = "Please select a file", filetypes=(("Mp3 Files", "*.mp3"),)))
for song in filenames:
song = song.split("/")
song = song[-1]
Playlist_box.insert(END,song)
def play():
filenames = Playlist_box.get(Playlist_box.curselection())
filenames = (f'C:/Python/Playlist/{filenames}')
mixer.init()
mixer.music.load(filenames)
mixer.music.play(loops=0)
root = Tk()
root.title('music')
label = Label(root,
text="choose the song").pack()
Playlist_box = Listbox(root, bg="black", fg="green", width=60)
Playlist_box.pack()
Button(root, text="choose your songs", command=play_song).pack()
Button(root, text="Play music", padx=12, bg="black", fg="white", command= play).pack()
root.mainloop()
I also tried to put the file path but the error is the same.
the error was in 'filenames' directory call,
i put :
filenames = (f'C:/Python/Playlist/{filenames}')
but it supose to be
filenames = (f'C:/Users/User/Documents/Python/Playlist/{filenames}')
he's working now, thank you people but it was just the call directory!!
I am running a simple python script that opens a window with a button inside of it. When the user clicks the button a dialog box opens and asks the user to select a file directory. I want to pull that directory location out of the function. This is what the code looks like:
from tkinter import *
from tkinter import filedialog
def openFile():
filePath= filedialog.askdirectory()
return filePath
window = Tk()
button = Button(text="open", command=openFile)
button.pack()
window.mainloop()
I would like the file directory to be saved in a variable inside the window. I am able to print the filepath inside the function but I am unable to bring it out of the function.
Any help will be greatly appreciated
You cannot use the return value for functions added to buttons, as there is no way of picking up whatever is returned.
So instead you can write the return to a global variable, or a class variable, instead. Example with global variable below;
from tkinter import *
from tkinter import filedialog
my_path = None
def openFile():
global my_path
filePath = filedialog.askdirectory()
my_path = filePath
window = Tk()
button = Button(text="open", command=openFile)
button.pack()
window.mainloop()
You will then be able to pick up the my_path variable later in your script after clicking the button.
The purpose of my code is to create a GUI that has 4 buttons. 2 of them are to open a "browse" window, allowing the user to select a file from a directory. The third button is to allow the user to choose a directory for the final document to be outputted to. The fourth button applies my python code to both files, creating the outputted document.
In attempting to create the "browse" buttons, through many posts here on stackoverflow and on the internet, most solutions include the "askopenfilename" module that is often imported from tkFileDialog. However no matter how I word it, or whatever variations of tkinter modules that i import, I consistently receive the same error messages of "no module name tkfileDialog" or "askopenfilename is not defined".
Am I doing something wrong with my code? Is this a common error found in tkinter with python 3.6? How would one go about creating a browse button that finds a file and adds its path?
Please let me know!
Thanks.
Below is my code:
import os
#from tkFileDialog import *
from tkinter import filedialog
from Tkinter import *
from tkfileDialog import askopenfilename
content = 'apple'
file_path = 'squarebot'
#FUNCTIONS
def browsefunc(): #browse button to search for files
filename = askopenfilename()
infile = open(filename, 'r')
content = infile.read()
pathadd = os.path.dirname(filename)+filename
pathlabel.delete(0, END)
pathlabel.insert(0, pathadd)
return content
def open_file(): #also browse button to search for files - im trying various things to get this to work!
global content
global file_path
#filename = filedialog.askopenfilename(filetypes = (typeName {.txt},))
filename = askopenfilename()
infile = open(filename, 'r')
content = infile.read()
file_path = os.path.dirname(filename)
entry.delete(0, END)
entry.insert(0, file_path)
return content
def process_file(content): #process conversion code
print(content)
def directoryname():
directoryname = filedialog.askdirectory() # pick a folder
#GUI
root = Tk()
root.title('DCLF Converter')
root.geometry("598x600")
mf = Frame(root)
mf.pack()
f1 = Frame(mf, width=600, height=250) #DC file
f1.pack(fill=X)
f2 = Frame(mf, width=600, height=250) #LF file
f2.pack(fill=X)
f3 = Frame(mf, width=600, height=250) #destination folder
f3.pack(fill=X)
f4 = Frame(mf, width=600, height=250) #convert button
f4.pack()
file_path = StringVar
Label(f1,text="Select Your DC File (Only txt files)").grid(row=0, column=0, sticky='e') #DC button
entry = Entry(f1, width=50, textvariable=file_path)
entry.grid(row=0,column=1,padx=2,pady=2,sticky='we',columnspan=25)
Label(f2,text="Select Your LF File (Only csv files)").grid(row=0, column=0, sticky='e') #LF button
entry = Entry(f2, width=50, textvariable=file_path)
entry.grid(row=0,column=1,padx=2,pady=2,sticky='we',columnspan=25)
Label(f3,text="Select Your Destination Folder").grid(row=0, column=0, sticky='e') #destination folder button
entry = Entry(f3, width=50, textvariable=directoryname)
entry.grid(row=0,column=1,padx=2,pady=2,sticky='we',columnspan=25)
Button(f1, text="Browse", command=browsefunc).grid(row=0, column=27, sticky='ew', padx=8, pady=4)#DC button
Button(f2, text="Browse", command=browsefunc).grid(row=0, column=27, sticky='ew', padx=8, pady=4)#LF button
Button(f3, text="Browse", command=browsefunc).grid(row=0, column=27, sticky='ew', padx=8, pady=4)#destination folder button
Button(f4, text="RECONCILE NOW", width=32, command=lambda: process_file(content)).grid(sticky='ew', padx=10, pady=10)#convert button
root.mainloop()
P.S If you have found any other errors in my code please let me know. I am just starting with tkinter, and as such this may be attributed to something completely unrelated!
Much Appreciated
This is what I use in my code so it will work with the Tkinter module in both Python 2 and 3:
try:
import Tkinter as tk
import ttk
from tkFileDialog import askopenfilename
import tkMessageBox
import tkSimpleDialog
from tkSimpleDialog import Dialog
except ModuleNotFoundError: # Python 3
import tkinter as tk
from tkinter import ttk
from tkinter.filedialog import askopenfilename
import tkinter.messagebox as tkMessageBox
import tkinter.simpledialog as tkSimpleDialog
from tkinter.simpledialog import Dialog
You asked to be notified any of other errors and I noticed the way you're using askopenfilename doesn't look right. Specifically, the filetypes keyword argument should be a sequence of two-element tuples containing file type names and patterns that will select what appears in the file listing. So for text files you would use:
filename = askopenfilename(filetypes=[('text files', '*.txt')])
I usually also include a generic pattern to allow easy access to files with other extensions thusly:
filename = askopenfilename(filetypes=[('text files', '*.txt'), ("all files", "*")])
Either way, it's important to remember to check the value returned because it might be the empty string it the user didn't select anything.
The problem was actually that I needed to append askopenfilename() to filedialog as mentioned by Roars in a now deleted comment!(it looks like this --> filedialog.askopenfilename().
The module name is misnamed.
Since the python version is 3.6 you need to use filedialog library. The includes should look something like this:
import os
from tkinter import *
import tkinter.filedialog
or
import os
from tkinter import *
from tkinter import filedialog
You can try this:
from tkinter.filedialog import askopenfilename
I'm trying to create a simple button that allows me to choose files such as text doc/pictures(jpg/png). I tried searching for answers here but didn't had any luck. I'm using Tkinter for my GUI interface.
This are my codes so far.
from Tkinter import *
root = Tk()
root.title("Hashing Tool")
root.geometry("600x300")
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
button = Button(frame, text="Choose File", fg="black")
button.pack( side = BOTTOM)
from tkFileDialog import askopenfilename
filename = askopenfilename()
print(filename)
root.mainloop()
Currently, you ask for a file as soon as the program starts. You have to put that part of the code into a callback function and pass that to the button's command parameter.
def getfile():
filename = askopenfilename()
print(filename)
button = Button(frame, text="Choose File", fg="black", command=getfile)