How to communicate between functions and perform functions asychronously - python

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!

Related

equivalent code of 'open with' in python script

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

Open a file from pc into tkinter

It is possible to open a file in tkinter from pc using right click->Open with->My Program.
I just want the file path when using this method.
You can't open a file using the method you are asking for( right-click > Open with > My Program) but you can create a program to open and edit files within a GUI using the Tkinter file dialog library and the open() function.
An example of the Method I am talking about:
from tkinter import *
from tkinter.filedialog import askopenfilename
windows = Tk()
windows.title("File Dialog Example")
windows.geometry("500x500")
def file_open():
text_window.delete('1.0', END)
filePath = askopenfilename(
initialdir='C:/', title='Select a File', filetype=(("Text File", ".txt"), ("All Files", "*.*")))
with open(filePath, 'r+') as askedFile:
fileContents = askedFile.read()
text_window.insert(INSERT, fileContents)
print(filePath)
open_button = Button(windows, text="Open File", command=file_open).grid(row=4, column=3)
text_window = Text(windows, bg="white",width=200, height=150)
text_window.place(x=50, y=50)
windows.mainloop()
And in order to save the changes to the file, you can read the contents in the Text Box and then write the contents to the Opened file.
Thanks

How to get a user-selected file and feed it to a python program in Tkinter

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

Python Directory Reader Tkinter GUI not working properly

Hi Everyone I am working on my final project and I am creating a directory snooper
So here is the bottomline of this script:
GUI with Tkinter that asks user for directory and prompts user to
save a cvs file to the space of their choosing. CSV will contain
filename,file extension and file size taken from the directory that
the user inputed.
My GUI has a text scroll box that should print the process of the
script and print when it is done,
My problems:
When saving CSV. It does not produce a CSV and I get this error
"ValueError: I/O operation on closed file".asksaveasfilename() is
not working
GUI text scroll box is not working and printing out the information
i need
How do I add headers to my CSV so that my CSV will have
filename,extension,size, and comment
Attached below is my script. Can anyone help me with this?
from Tkinter import Tk
from tkFileDialog import askdirectory
from array import *
import os
version = '1.0'
import os
import csv
from Tkinter import BOTH, LEFT, TOP, END, StringVar
from ttk import Frame, Entry, Button, Label
from ScrolledText import ScrolledText
from tkFileDialog import askdirectory
from tkFileDialog import asksaveasfilename
class FileWalkerWindow(Frame):
def __init__(self):
Frame.__init__(self)
self.pack(expand=True, fill=BOTH)
self.master.title("Directory Snooper v" + version)
self.master.iconname("Directory Snooper")
self.dir = StringVar() # tkinter does not work with standard python variables
self.dir.set(os.getcwd()) # set to current working directory
description = "This program walks through a directories " \
+ "print out name of directory file path. " \
+ "prints out mumber of files in your in your directory. " \
+ "It list files and tests for corrupted zipfiles and " \
+ "creates a CSV file of the findings"
row1 = Frame(self)
Label(row1, text="Choose Directory:").pack(side=LEFT, pady=10)
self.dir_ent = Entry(row1, width=80, textvariable=self.dir)
self.dir_ent.pack(side=LEFT)
Button(row1, text="Browse", width=10, command=self.browse).pack(side=LEFT, padx=5)
row1.pack(side=TOP, ipadx=15)
row2 = Frame(self)
btn = Button(row2, text="Snoop", command=self.savefile, width=15)
btn.pack(side=LEFT, padx=5, pady=10)
row2.pack(side=TOP)
self.output = ScrolledText(self, height=15, state="normal",
padx=10, pady=10,
wrap='word')
self.output.insert(END, description)
self.output.pack(side=LEFT, fill=BOTH, expand=True, padx=5, pady=5)
self.bind('<Key-Return>', self.savefile) # bind enter press to walk
def browse(self):
dirpath = askdirectory(parent=self, title="Select Directory")
self.dir.set(dirpath)
def savefile (self):
self.output.delete(1.0, END)
name=asksaveasfilename()
with open(name,'w') as csvfile:
dirList = os.listdir(self.dir.get())
data = ((fname, str(os.path.getsize(self.dir.get() + "/" + fname)), str(os.path.splitext(fname)[1]),) for
fname in
dirList)
for entry in data:
create=csv.writer(csvfile)
create.writerow(','.join(entry) + '\n')
csvfile.close()
if __name__ == '__main__':
FileWalkerWindow().mainloop()
When saving CSV. It does not produce a CSV and I get this error
"ValueError: I/O operation on closed file"
You do close the file in your for loop:
for entry in data:
create=csv.writer(csvfile)
create.writerow(','.join(entry) + '\n')
csvfile.close()
Unindent it to close the file after the for loop. You should move the csv.writer() outside of the for loop as well (as mentioned in comments):
create=csv.writer(csvfile)
for entry in data:
create.writerow(','.join(entry) + '\n')
csvfile.close()
GUI text scroll box is not working and printing out the information i need
The question is when you want to display the information!
You can add a button to print the content of the chosen directory or print it automatically when the user selects a folder to browse.
To do the latter, you can edit you browse method, which should look like:
def browse(self):
dirpath = askdirectory(parent=self, title="Select Directory")
self.dir.set(dirpath)
self.output.insert(END, "\n" + "\n".join(os.listdir(dirpath)))
How do I add headers to my CSV so that my CSV will have
filename,extension,size, and comment
Just write a Python string containing your headers before writing actual values:
with open(name,'w') as csvfile:
csvfile.write("filename,extension,size,comment")
dirList = os.listdir(self.dir.get())
# some other stuff after...
Please note also that, while it is strongly discouraged by Python guidelines to use from module import * in general, the standard way to import Tkinter is from Tkinter import * :)

Browse files to open and run using GUI python

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)

Categories

Resources