Embed Another Application inside tkinter window - python-3.x

I want to embed an application to my Tkinter windows:
Here is my file tree:
Here is my code:
from tkinter import *
import os
window=Tk()
window.geometry('1000x700')
app_1= open('./Applications/App_1.lnk')
app_1_img= open('./Images/App_Icons/App_1.png')
L1=Label(window, text=os.system(app_1))
L2=Label(window, img=app_1_img)
L1.pack()
L2.pack()
window.mainloop()
Here is what I get:
Traceback (most recent call last):
File "C:\Users\asmit\Desktop\App\Index.py", line 7, in <module>
L1=Label(window, text=os.system(app_1))
TypeError: system() argument 1 must be str, not _io.TextIOWrapper
Here is what I want:
Thank You in advance

When you:
app_1 = open('./Applications/App_1.lnk')
The app_1 name will point to a file object. Same for the image.
You'll have to read the file to get its contents. See Reading and Writing Files.
Usually this is implemented as:
with open(filename, 'r') as file:
contents = file.read()

Related

AttributeError: 'NoneType' object has no attribute 'languages'

Goal : 1.Select PDF 2.OCR PDF 3.Write tabels to excel with onefile .exe
Script is working in Pycharm perfect but after compiling to exe i am getting this traceback.
Traceback (most recent call last):
File "OCR_Menu.py", line 26, in <module>
File "ocrmypdf\api.py", line 340, in ocr
File "ocrmypdf\_validation.py", line 240, in check_options
AttributeError: 'NoneType' object has no attribute 'languages'
[11220] Failed to execute script 'OCR_Menu' due to unhandled exception!
Any help to get this script working as a single executable file will be very appreciated!
Thank you!
import ocrmypdf
import camelot
from tkinter import Tk
from tkinter.filedialog 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)
# if filename is not None:
if __name__ == '__main__': # To ensure correct behavior on Windows and macOS
ocrmypdf.ocr (filename, 'output.pdf', deskew=True,)
file = "output.pdf"
tables = camelot.read_pdf(file, pages = "1-end", flavor='stream')
print(tables.n)
tables=camelot.read_pdf(file, pages='1-end', flavor='stream')
tables.export(filename + ".xlsx", f='excel')
if you're currently using googletrans==3.0.0, please switch to googletrans==3.1.0a0 for the temporary fix.

Is there a way to specify and then open a file with Python?

I'm attempting to make a program which will allow the user to pick a file from their computer and then open it. I've been trying to do this with Python, and...
filedialog.askopenfilenames()
...with this Tkinter widget.
I can get the filepath from this successfully, but how to I use it to actually open the file? (I'm trying to open it in its default app, not just print it to the Python console.) I've tried using
from subprocess import call
call(['xdg-open','filename'])
with 'files' (the variable that the filename is stored in) replacing 'filename', but I get the following error:
Traceback (most recent call last):
File "/Users/charlierubinstein/Documents/Search Engine.py", line 9, in <module>
call(['xdg-open', files])
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 267, in call
with Popen(*popenargs, **kwargs) as p:
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 709, in __init__
restore_signals, start_new_session)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 1275, in _execute_child
restore_signals, start_new_session, preexec_fn)
TypeError: expected str, bytes or os.PathLike object, not tuple
my code so far:
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from subprocess import call
files = filedialog.askopenfilenames()
call(['xdg-open', files])
window.mainloop()
As stated earlier, ideally this program would let the user pick a file, and then open that file in its default app.
You use askopenfilenames() (with s at the end of name)
It let you select many files so it returns tuple with all selected files - even if you selected only one file
(or empty tuple if you cancel selection)
So you have to get first element from tuple
call(['xdg-open', files[0] ])
Or use askopenfilename() (without s at the end of name) and you will get single string.
filename = filedialog.askopenfilename() # without `s` at the end
call(['xdg-open', filename])

Writing pdf with pypdf2 gives error

I'm trying to write a simple script to merge two PDFs but have run into an issue when trying to save the output to disk. My code is
from PyPDF2 import PdfFileWriter, PdfFileReader
import tkinter as tk
from tkinter import filedialog
### Prompt the user for the 2 files to use via GUI ###
root = tk.Tk()
root.update()
file_path1 = tk.filedialog.askopenfilename(
filetypes=[("PDF files", "*.pdf")],
)
file_path2 = tk.filedialog.askopenfilename(
filetypes=[("PDF files", "*.pdf")],
)
###Function to combine PDFs###
output = PdfFileWriter()
def append_pdf_2_output(file_handler):
for page in range(file_handler.numPages):
output.addPage(file_handler.getPage(page))
#Actually combine the 2 PDFs###
append_pdf_2_output(PdfFileReader(open(file_path1, "rb")))
append_pdf_2_output(PdfFileReader(open(file_path2, "rb")))
###Prompt the user for the file save###
output_name = tk.filedialog.asksaveasfile(
defaultextension='pdf')
###Write the output to disk###
output.write(output_name)
output.close
The problem is that I get an error of
UserWarning: File to write to is not in binary mode. It may not be written to correctly. [pdf.py:453] Traceback (most recent call last): File "Combine2Pdfs.py", line 44, in output.write(output_name) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/pytho‌​n3.5/site-packages/P‌​yPDF2/pdf.py", line 487, in write stream.write(self.header + b("\n")) TypeError: write() argument must be str, not bytes
Where have I gone wrong?
I got it by adding mode = 'wb' to tk.filedialog.asksaveasfile. Now it's
output_name = tk.filedialog.asksaveasfile(
mode = 'wb',
defaultextension='pdf')
output.write(output_name)
Try to use tk.filedialog.asksaveasfilename instead of tk.filedialog.asksaveasfile. You just want the filename, not the file handler itself.
###Prompt the user for the file save###
output_name = tk.filedialog.asksaveasfilename(defaultextension='pdf')

For py2exe, is there a way to choose the save location of the executable?

I know there's already a question like this, but I got this error when I used it:
Traceback (most recent call last):
File "C:/Users/rperera/PycharmProjects/PythonToExe/test.py", line 12, in <module>
save_path = filedialog.asksaveasfilename(defaultextension="*.exe", filetypes=("Executable File", "*.exe"))
File "C:\Python34\lib\tkinter\filedialog.py", line 380, in asksaveasfilename
return SaveAs(**options).show()
File "C:\Python34\lib\tkinter\commondialog.py", line 48, in show
s = w.tk.call(self.command, *w._options(self.options))
_tkinter.TclError: bad file type "*.exe", should be "typeName {extension ?extensions ...?} ?{macType ?macTypes ...?}?"
Can anyone help me on how to fix this? Here's my code:
from distutils.core import setup
import py2exe, sys
import tkinter as tk
from tkinter import filedialog
input('Press Enter to continue and select your Python file you want to convert when the dialog shows up...')
tk.Tk().withdraw()
file_path = tk.filedialog.askopenfilename()
sys.argv.append("py2exe")
input("Press Enter to continue and choose where you want to save the new executable file when the dialog shows up...")
save_path = filedialog.asksaveasfilename(defaultextension="*.exe", filetypes=("Executable File", "*.exe"))
setup(console=[file_path], options={'py2exe': {'compressed': 1, 'bundle_files': 1, 'dist_dir': save_path + "dir"}})

Error when Unzipping with Pyside Qtgui

When I run my program, I get the following error and am not sure on how to correct it. Can someone help with explaining what this error is and how to correct it? Newb here so details are appreciated. Thanks for your time in advance!
Code:
#!/usr/bin/python
import zipfile
from PySide import QtGui
import re
#Select file to extract
app = QtGui.QApplication([])
dialog = QtGui.QFileDialog()
dialog.setFileMode(QtGui.QFileDialog.AnyFile)
if (dialog.exec()):
fileName = dialog.selectedFiles()
#Select Directory to extract to
dialog = QtGui.QFileDialog()
dialog.setFileMode(QtGui.QFileDialog.Directory)
dialog.setOption(QtGui.QFileDialog.ShowDirsOnly)
if (dialog.exec()):
dirName = dialog.selectedFiles()
print("Extracting.....")
zFile= zipfile.ZipFile(fileName)
zFile.extractall(dirName)
Error output:
Traceback (most recent call last):
File "C:\Users\Jennifer\Documents\BatchScripts\unzip.py", line 22, in <module>
zFile= zipfile.ZipFile(fileName)
File "C:\Python33\lib\zipfile.py", line 933, in __init__
self._RealGetContents()
File "C:\Python33\lib\zipfile.py", line 970, in _RealGetContents
endrec = _EndRecData(fp)
File "C:\Python33\lib\zipfile.py", line 237, in _EndRecData
fpin.seek(0, 2)
AttributeError: 'list' object has no attribute 'seek'
In your file and target directory code blocks, dialog.selectedFiles() returns a list. zipfile.ZipFile can only handle one file at a time, hence your error. To iterate over the list being provided by dialog.selectedFiles(), use the following:
for archive in fileName: # you should probably change it to fileNames to reflect its true nature
zfile = zipfile.ZipFile(archive)
print("Extracting " + str(zfile.filename) + "...")
zfile.extractall(dirName[0]) # also a list, extract to first item and ignore rest
and you should be all set.

Resources