When I run my code, I can get any file filepath for further use and put it in the Entry box. When I try to get a filepath of a shortcut, another window opens up, saying "catastrophic error". The console remains quiet all the time. Here's my code:
from tkinter import *
from PIL import *
import os
from tkinter import filedialog
root = Tk()
def create_game():
# Defining the function for choosing the filepath
def add_data():
root.filename = filedialog.askopenfilename(initialdir="",title="Select A File",filetypes=((".EXE files", "*.exe"),("all", "*.*")))
enter_filepath.insert(0,str(root.filename))
enter_filepath = Entry(root,width=30)
enter_filepath.pack()
btn_filepath = Button(root,text="Choose file",command=add_data)
btn_filepath.pack()
create_game()
root.mainloop()
This is what I'm getting:
I have a tkinter window and need to press a button to open a csv file. For example:
root = Tk()
def open_file():
# show the csv file to the user
open_button = Button(root, text="Open", command=open_file)
open_button.pack()
Is there a way to do this, or something similar? I have tried using askopenfilename, but this doesn't seem to work for me, as it only opens the home directory.
Have a look at this link. As you can see from the link, the approaches differ a bit for python 2.7 and 3. Since python 2.7 is reaching the end of its life, I will demonstrate for python 3:
from tkinter import filedialog
from tkinter import *
root = Tk()
root.filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
print (root.filename)
If you correctly installed tkinter using pip and filled all the arguments correctly it should work. Make sure the root directory actually exists and you specified syntactically correct (types of slashes matter).
You can also open the file picker even though it starts in the wrong directory. You can browse to the correct root directory and click ok and have the program print the directory. Then you'll know how to specify the root directory.
The following code show tkinter window with a button. When the user click the button and point to a CSV file, it would show the first few lines into a message box for show. I use pandas to open the CSV file.
import tkinter as tk
from tkinter import filedialog
import tkinter.messagebox as msgBox
import os
import pandas as pd
def open_file():
filename = filedialog.askopenfilename(initialdir=os.getcwd())
if(filename!=''):
df = pd.read_csv(filename, encoding = "ISO-8859-1", low_memory=False)
mR,mC=df.shape
cols = df.columns
num=5
pd.options.display.float_format = '{:.2f}'.format
msg=str(df.iloc[:num,:]) + '\n' + '...\n' + \
df.iloc[-num:,:].to_string(header=False) + '\n\n' + \
str(df.describe())
msgBox.showinfo(title="Data", message=msg)
root = tk.Tk()
frame = tk.Frame(root)
frame.pack()
button = tk.Button(frame, text="Open", command=open_file)
button.pack(side = tk.LEFT)
root.mainloop()
I want to make a Tkinter interface for a program I just wrote. The interface needs to have a widget where the user can insert an image for the program to process. I couldn't find such a widget online. How would I make such an interface?
Below is an example of tkinter entry widget that takes in images right away:
try: # In order to be able to import tkinter for
import tkinter as tk # either in python 2 or in python 3
import tkinter.filedialog as tkfd
except ImportError:
import Tkinter as tk
import tkFileDialog as tkfd
if __name__ == '__main__':
root = tk.Tk()
entry = tk.Entry(root)
entry.pack()
path = tkfd.askopenfilename(initialdir = "/", title = "Select file",
filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
entry.insert('0', path)
root.mainloop()
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
Right now, I have a GUI program that allows you to change parameters and stuff like that. I want to make it so you can choose a picture instead of only having one for the whole thing.
I have this:
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
When I try to use this, it will just say that it cannot import filedialog.
EDIT:
Okay, so I just fixed that error by using:
import tkFileDialog as filedialog
Now I just need help making the file I choose be the one that appears on the canvas. Right now, I have this:
__dir__ = os.path.dirname(os.path.abspath(__file__))
filename = os.path.join(__dir__, root.filename)
img = PIL.Image.open(filename)
shrek= img.resize((100,100))
root = Tk() # create main window; must be done before using ImageTk
root.filename = filedialog.askopenfilename(initialdir = "E:/Images",title = "choose your file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
print (root.filename)
I am trying to make the file that I choose from the explorer replace the current file.
This is for Python 2.x import tkFileDialog as filedialog
I guess you use Python 2.x..