Using python 3.3 on a unix platform. I have seen many examples where the following code works but I am having an issue. When I select multiple files, I get an error message dialog box: "File /python/input_files/file1.txt file2.txt" does not exist. The error makes sense (tries to open a string of multiple files) but don't understand why others don't see it and how do I correct it. selectFiles is called via a button select. Appreciate any help.
from tkinter import *
from tkinter import ttk
from tkinter.filedialog import askopenfilenames
def selectFiles(self):
files = askopenfilenames(filetypes=(('Text files', '*.txt'),
('All files', '*.*')),
title='Select Input File'
)
fileList = root.tk.splitlist(files)
print('Files = ', fileList)
Here is the complete code:
#!/usr/local/bin/python3.3
from tkinter import *
from tkinter import ttk
from tkinter.filedialog import askopenfilenames
class multifilesApp(Frame):
def __init__(self,master=None):
Frame.__init__(self,master)
def initializeUI(self):
self.master.title('Select Files Application')
self.grid(row=0, column=0,sticky=W)
# Create the button to select files
self.button1 = Button(self.master, text='Select Files', command=self.selectFiles, width=10)
self.button1.grid(row=30, column=0)
def selectFiles(self):
files = askopenfilenames(filetypes=(('Text files', '*.txt'),
('All files', '*.*')),
title='Select Input File'
)
InputFileList = root.tk.splitlist(files)
print('Files = ', InputFileList)
# Begin Main
if __name__ == "__main__":
root = Tk()
root.minsize(width=250, height=400)
root.geometry("1200x800")
# Call the parser GUI application
app = multifilesApp(master=root)
app.initializeUI()
app.mainloop()
Maybe there is problem with Tcl/Tk on Sun4u
Try to run example in Tcl/Tk (example.tcl)
package require Tk
set filename [tk_getOpenFile -multiple true]
puts $filename
Run (probably):
tclsh example.tcl
Related
import sys
sys. argv[1]
is the code equivalent of the above image. Please reply me
You need to get the os which is in-built library to Python. Then you can use
os.startfile(_filepath_)
to open the file.
finally i got the answer. yes it is right I wanted to create a pdf reader application using python tkinter which i will use to open any pdf file. When i will click a pdf file it will show my tkinter app and i will open it via my pdf app this tkinter app will show that pdf file.And finally i successfully completed it. This is full code
from tkinter import *
from tkinter import filedialog
from tkPDFViewer import tkPDFViewer as pdf
import os
import sys
root = Tk()
root.geometry('630x700+400+100')
root.title('Python Pdf Reader')
root.configure(bg='white')
try:
filepath = str(sys.argv[1])
except:
filepath = ''
v2 = pdf.ShowPdf().pdf_view(root, pdf_location=filepath,
width=77, height=100)
def browseFiles():
global v2
try:
filename = filedialog.askopenfilename(initialdir=os.getcwd(),
title="Select pdf file",
filetypes=(('PDF File', '.pdf'),
('PDF file', '.PDF'),
('All file', '.txt')))
v1 = pdf.ShowPdf()
v1.img_object_li.clear()
v2.destroy()
v2 = v1.pdf_view(root, pdf_location=filename,
width=77, height=100)
v2.pack(pady=(0, 0))
except Exception as e:
print(f'{e}')
Button(root, text='Open', command=browseFiles, width=40, font='arial 20', bd=4).pack()
v2.pack(pady=(0, 0))
root.mainloop()
And when you will build this code into windows installer and install this in your windows pc. You will get that result. This is my details answer so share this answer. I think it will really help anybody
I am trying to build a simple app with Tkinter that can select multiple files and get their full path + filenames respectively.
Currently, the app can select multiple files but seems fail to get the full path, any pointer on this would be great.
from tkinter import *
from tkinter.ttk import *
from tkinter.filedialog import askopenfile
import os
root = Tk()
root.geometry('200x100')
def browse():
filename = askopenfile(mode ='r', filetypes =[('files', '*.csv')], multiple=True)
pathlabel.config(text=filename)
browsebutton = Button(root, text="Browse", command=browse)
browsebutton.pack()
pathlabel = Label(root)
pathlabel.pack()
mainloop()
You can make use of the askopenfilename() instead of askopenfile() this will return a tuple containing the file paths of the files chosen. To obtain the file names, you can make use of the os.path.basename(file/path) this will return the corresponding file name (along with the extension). You can refer to the modified code below:
from tkinter import *
from tkinter.ttk import *
from tkinter.filedialog import askopenfilename
import os
root = Tk()
def browse():
files = askopenfilename(filetypes =[('files', '*.csv')], multiple=True)
file_paths=''
file_names=''
for file in files:
file_paths+=file+'\n'
file_names+=os.path.basename(file)+'\n'
pathlabel.config(text=file_paths)
namelabel.config(text=file_names)
browsebutton = Button(root, text="Browse", command=browse)
browsebutton.pack()
path_head=Label(root,text='File Paths').pack()
pathlabel = Label(root)
pathlabel.pack()
name_head=Label(root,text='File Names').pack()
namelabel=Label(root)
namelabel.pack()
mainloop()
I am currently messing about with Tkinter creating an interface for a project I created. The program takes in a bunch of file paths as inputs for it to run. I'm trying to create a tkinter interface where I can upload the 4 files I need or at least somehow get the filepaths and the. feed those to the program. Here is what I have:
import sys
import os
import comparatorclass
from tkinter import *
from tkinter.ttk import *
from tkinter.filedialog import askopenfile
root=Tk()
root.geometry('1000x1000')
def open_file():
file = askopenfile(mode ='r', filetypes =[('Python Files', '*.py')])
if file is not None:
content = file.read()
print(content)
def run_comparator():
comparatorclass.main()
button2 = Button(root, text ='Open', command = lambda:open_file())
button2.pack(side = TOP, pady = 10)
button1 = Button(root,text="hello",command= run_comparator)
button1.pack()
root.mainloop()
as you can see, I have two buttons. The issue I'm having is how to connect my openfile function to my run_comparator function such that the 4 files I need to open are passed on to the run_comparator
I am trying to develop a GUI with tkinter. I have created a function (as a button) to browse for a directory folder ('input folder'). I have a routine linked to another button ('execute') that needs the path from 'input folder'.
I am getting errors when I try to pass the path from 'input folder' into os.chdir inside 'execute'. Example is as follows:
import sys
import os
from tkinter import filedialog
from tkinter import *
window = Tk()
def Input():
filename = filedialog.askdirectory()
global filename
def Extraction():
in_loc = filename
os.chdir(in_loc)
btn = Button(window, text="Extract", bg="black", fg="white", command=Extraction)
btn.pack()
btn2 = Button(text="Input", command=Input).pack()
window.mainloop()
Can anyone reproduce this and tell me what I am doing wrong here?
Thanks :)
Try this:
import sys
import os
from tkinter import filedialog
from tkinter import *
filename = ''
def input_function():
global filename
filename = filedialog.askdirectory()
def extraction():
global filename
in_loc = filename
os.chdir(in_loc)
window = Tk()
btn = Button(window, text="Extract", bg="black", fg="white", command=extraction)
btn.pack()
btn2 = Button(text="Input", command=input_function).pack()
window.mainloop()
I want to use extensions list example : [".txt",".html",".css"] for save as option in file dialog popup window. when I use this method
file_opt = options = {}
options['defaultextension'] = '.txt',I can able to write any file with .txt as default extension without choose in save as option but I want to choose extensions for save as in file dialog popup window from using my extensions list.
I'm using Python 3.5 based Anaconda IDE
If you look at the documentation here you can see that you can pass in the filetypes keyword which specifies a list of tuples that have the name, and file extension respectively for the different types of filetypes you want to be able to save as.. So you can do something along the lines of:
import tkinter as tk
from tkinter import filedialog as fd
def save_file():
filename = fd.asksaveasfilename(defaultextension='.txt',
filetypes= [('Text','.txt'), ('HTML', '.html'), ('CSS', '.css')])
if filename:
print("User saved the filename with extension:", filename.split(".")[-1])
root = tk.Tk()
button = tk.Button(root, text='Save File', command=save_file)
button.pack()
root.mainloop()
Or if you really want to use a dictionary for this:
import tkinter as tk
from tkinter import filedialog as fd
SAVE_OPTS = {'defaultextension':'.txt',
'filetypes': [('Text','.txt'), ('HTML', '.html'), ('CSS', '.css')]}
def save_file():
filename = fd.asksaveasfilename(**SAVE_OPTS)
if filename:
print("User saved the filename with extension:", filename.split(".")[-1])
root = tk.Tk()
button = tk.Button(root, text='Save File', command=save_file)
button.pack()
root.mainloop()
SaveFileDialog sd = new SaveFileDialog();
sd.Filter = "Text File (*.txt)|*.txt|PNG File (*.txt)|*.png"|...;
if(sd.ShowDialog() == DialogResult.OK) {
richTextBox1.SaveFile(sd.FileName, RichTextBoxStreamType.PlainText);
}