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
Related
I am new to programming but am trying to create a PDF reader. There are two functions I have made: getting the filepath from the explorer and reading the PDF information. The current format is this:
import tkinter
from tkinter import *
from tkinter import filedialog
import PyPDF2
from PyPDF2 import PdfFileReader
class Main():
def reader():
filetext = open(filepath,'rb')
PDFreader = PyPDF2.PdfFileReader(filetext)
pageObj = reader.getPage(0)
print(pageObj.extractText())
filetext.close()
def open_file():
filepath = filedialog.askopenfilename(title="Open Report", filetypes=(("PDF Files","*.pdf"), ("All Files","*.*")))
print(filepath)
reader()
win=Tk()
win.geometry("700x300")
Label(win, text="PDF Reader", font='Arial 16 bold').pack(pady=15)
button = Button(win, text="Open", command=Main.open_file)
button.pack()
win.mainloop()
Essentially I am trying to make the button the GUI open the PDF and once that is finished, read the data to the PDF. I want to keep them in separate functions to understand how functions can be made separately but used together. Thanks!
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 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);
}
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
Hi i have some python scripts. I need to create a GUI with few buttons, to open those files by browsing. I have to run those scripts just by clicking the GUI button, and should write the output into a n excel sheet. I tried with the below code, but with that i can just read the file! please help?
Thank you
from Tkinter import *
from tkFileDialog
import askopenfilename
def callback():
r = open(askopenfilename(),'r')
a = Button(text='click me', command=callback)
a.pack()
mainloop()
inside the callback() instead of opening the file, execute the file using execfile("abc.py")
def callback():
abc = askopenfilename()
execfile("abc.py")
This code below is a simple example that reads each line from the selected input file and then writes it to a new excel file called output.xls. It use the excellent xlwt library for creating the excel file. You could also chose to create a csv file using the csv module that is part of the python standard library which is also readable by excel. The advantages of using xlwt is that you can apply formating, merge cells, formulas, and so many other features that are part of the xls file format.
import xlwt
from Tkinter import *
from tkFileDialog import askopenfilename
def callback():
filename = askopenfilename()
wb = xlwt.Workbook()
ws0 = wb.add_sheet('Sheet1')
with open(filename, 'r') as f:
for i, line in enumerate(f):
ws0.write(i, 0, line.strip())
wb.save('output.xls')
errmsg = 'Error!'
a = Button(text='click me', command=callback)
a.pack()
mainloop()
import Tkinter, tkFileDialog
root = Tkinter.Tk()
root.withdraw()
dirname=tkFileDialog.askdirectory(parent=root,initialdir="/",title='Please select a directory')
do something with dirname
print dirname
#This code for file selection:
from Tkinter import Tk
from tkFileDialog import askopenfilename
Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file
print(filename)