self.tk.call - in photo image python - python-3.x

I'm trying to import an image and recognize by text in Python using below commands but it shows error.
My code:
from Tkinter import *
import pygame
import pyttsx3
pygame.init()
engine = pyttsx3.init()
root = Tk()
root.title('Application')
root.geometry('1352x652+100+100')
root.config(background='white')
str1 = StringVar()
str1.set('Application name')
frame1 = Frame(root,bg='white')
frame1.grid()
Disp = Canvas(frame1, width=160,height=120,bg='white')
Disp.grid(row=1,column=3)
img =PhotoImage(file='Icone.png')
image = Disp.create_image(85,62,image = img)
error stack trace:
img =PhotoImage(file='Icone.png')
Image.__init__(self, 'photo', name, cnf, master, **kw)
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize data in image file "Icone.png"

Related

Tkinter throws exception, but the code still works, why?

I am working on a comic book reader and my code so far seems to be working great, except for a small result that happens when I update my canvas to display a jpg of the page of the comic book.
The Code:
from tkinter import *
from tkinter import filedialog, Tcl
from PIL import ImageTk, Image
from pyunpack import Archive
import shutil
import tempfile
import os
def open_comic():
os.mkdir('tmp/')
text_file = filedialog.askopenfilename(title="Open Comic Book File", filetypes=(("CBR Files", "*.cbr"), ("CBZ Files", "*.cbz"), ))
tempdir = tempfile.mkdtemp(suffix='.tmp', dir='tmp/')
print('Created temp directory', tempdir)
Archive(text_file).extractall(tempdir)
file_list = os.listdir(tempdir)
file_list.sort()
img = ImageTk.PhotoImage(Image.open(tempdir + "/" + file_list[1]))
my_image = comic_canvas.create_image(0, 0, anchor=NW, image=img)
canvas.update()
# Create the Main Window of the Application
mainWindow = Tk()
mainWindow.title("Comic Reader")
mainWindow.geometry("1200x1500")
buttonFrame = LabelFrame(mainWindow)
canvasFrame = LabelFrame(mainWindow, bg="light gray", border=2)
statusFrame = LabelFrame(mainWindow, bg="black", border=2)
comic_canvas = Canvas(canvasFrame, width="1100", height="1400", bg="light gray")
# Create the Menu Bar for the Application
main_menu = Menu(mainWindow)
mainWindow.config(menu=main_menu)
# The File Menu
file_menu = Menu(main_menu, tearoff=False)
main_menu.add_cascade(menu=file_menu, label="File")
file_menu.add_command(label="Open", command=open_comic)
file_menu.add_separator()
file_menu.add_command(label="Quit", command=quit_it)
# The Edit Menu
edit_menu = Menu(main_menu, tearoff=False)
main_menu.add_cascade(menu=edit_menu, label="Edit")
edit_menu.add_command(label="Cut", accelerator="(CTRL+X)")
edit_menu.add_command(label="Copy", accelerator="(CTRL+C)")
edit_menu.add_command(label="Paste", accelerator="(CTRL+V)")
button_back = Button(buttonFrame, text="<=", command=back)
button_exit = Button(buttonFrame, text="Exit", command=quit_it)
button_next = Button(buttonFrame, text="=>", command=lambda: forward(2))
buttonFrame.pack()
canvasFrame.pack()
statusFrame.pack()
button_back.grid(row=1, column=0)
button_exit.grid(row=1, column=1)
button_next.grid(row=1, column=2)
comic_canvas.grid(row=2, column=1)
# Start the Application Here
mainWindow.mainloop() # Creates the GUI for the Application
Now as it is above, it works to update the canvas, and lets you see the image, but throws the error:
> Exception in Tkinter callback Traceback (most recent call last):
> File
> "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/__init__.py",
> line 1884, in __call__
> return self.func(*args) File "/Users/kb2mob/Python Projects/Comic Reader/comicreader.py", line 28, in open_comic
> canvas.update() NameError: name 'canvas' is not defined
Which, yeah it should because the canvas is named "comic_canvas". But then I do use the correct name for the .update() method, it flashes quickly and then vanishes, and of course doesn't throw an error because it's the correct use.
Does anyone know why that is?
This is in Python 3.9.1 on a latest Mac OS.
Found the issue:
Wasn't keeping the image reference at the end of my function open_comic()
comic_canvas.img = img
dropped that on the end of it and it worked.

displaying an image full screen in Python

The following program works the for the first .jpg in the directory.
When called the second time it gets a "_tkinter.TclError: image
"pyimage2" doesn't exist" exception. Why does it get the error? Is
there a way to reuse the first image rather than creating a second?
import sys, os
if sys.version_info[0] == 2:
import Tkinter
tkinter = Tkinter
else:
import tkinter
from PIL import Image, ImageTk
def showPIL(pilImage):
root = tkinter.Tk()
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
root.overrideredirect(1)
root.geometry("%dx%d+0+0" % (w, h))
root.focus_set()
root.bind("<Escape>", lambda e: (e.widget.withdraw(), e.widget.quit()))
canvas = tkinter.Canvas(root,width=w,height=h)
canvas.pack()
canvas.configure(background='black')
imgWidth, imgHeight = pilImage.size
# resize photo to full screen
ratio = min(w/imgWidth, h/imgHeight)
imgWidth = int(imgWidth*ratio)
imgHeight = int(imgHeight*ratio)
pilImage = pilImage.resize((imgWidth,imgHeight), Image.ANTIALIAS)
image = ImageTk.PhotoImage(pilImage)
print(image)
imagesprite = canvas.create_image(w/2,h/2,image=image)
root.mainloop()
names = os.listdir("E://Users//scott//Pictures")
print(names)
for file in names:
print(file)
if file[-4:] == ".jpg":
file=Image.open("E://Users//scott//Pictures//"+file)
showPIL(file)
Here is the console output. Traceback (most recent call last): File
"e:\Users\scott\Documents\Python\image test.py", line 36, in
showPIL(file) File "e:\Users\scott\Documents\Python\image test.py", line 27, in showPIL
imagesprite = canvas.create_image(w/2,h/2,image=image) File "C:\Program Files\Python37\lib\tkinter__init__.py", line 2486, in
create_image
return self._create('image', args, kw) File "C:\Program Files\Python37\lib\tkinter__init__.py", line 2477, in _create
*(args + self._options(cnf, kw))))
_tkinter.TclError: image "pyimage2" doesn't exist
>
after searching around I discovered that the first problem that tkinter.Tk() was being called multiple times whereas it must be called
only once so I moved it out of the showPIL function and into the
initialization. The next problem is that mainloop blocks so I
replaced it with the combination of root.update_idletasks() and
root.update(). The following works as I expect and need:
import sys, os
if sys.version_info[0] == 2: # the tkinter library changed it's name from Python 2 to 3.
import Tkinter
tkinter = Tkinter #I decided to use a library reference to avoid potential naming conflicts with people's programs.
else:
import tkinter
from PIL import Image, ImageTk
import time
root = tkinter.Tk()
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
root.overrideredirect(1)
root.geometry("%dx%d+0+0" % (w, h))
root.focus_set()
canvas = tkinter.Canvas(root,width=w,height=h)
canvas.pack()
canvas.configure(background='black')
def showPIL(pilImage):
imgWidth, imgHeight = pilImage.size
# resize photo to full screen
ratio = min(w/imgWidth, h/imgHeight)
imgWidth = int(imgWidth*ratio)
imgHeight = int(imgHeight*ratio)
pilImage = pilImage.resize((imgWidth,imgHeight), Image.ANTIALIAS)
image = ImageTk.PhotoImage(pilImage)
imagesprite = canvas.create_image(w/2,h/2,image=image)
root.update_idletasks()
root.update()
# root.bind("<Escape>", lambda e: (e.widget.withdraw(), e.widget.quit()))
names = os.listdir("E://Users//scott//Pictures")
print(names)
for file in names:
print(file)
if file[-4:] == ".jpg":
file=Image.open("E://Users//scott//Pictures//"+file)
showPIL(file)
time.sleep(5)

How can i get data from file path using tkinter and PdFileReader

I use this method :
from PyPDF2 import PdfFileReader
from tkinter import *
from tkinter import filedialog
import os
root = Tk()
def browsefunc():
filename = filedialog.askopenfilename()
pathlabel.config(text=filename)
browsebutton = Button(root, text="Browse", command=browsefunc)
browsebutton.pack()
pathlabel = Label(root)
pathlabel.pack()
def get_info(path):
with open(path, 'rb') as f:
pdf = PdfFileReader(f)
info = pdf.getDocumentInfo()
number_of_pages = pdf.getNumPages()
print(info)
author = info.author
creator = info.creator
producer = info.producer
subject = info.subject
title = info.title
if __name__ == '__main__':
path = pathlabel.pack()
get_info(path)
mainloop()
However, i get the following error:
TypeError: invalid file: None
How can i get the file from pathlabel?
Is it possible to open the file from file path?
I see a couple problems here.
Delete this:
if __name__ == '__main__':
path = pathlabel.pack()
get_info(path)
what this is doing is making path = to the result of pathlabel.pack(). That result will always be None as pack() is always going to return None. Then you are passing None to the get_info() function.
Instead lets call get_info from your brousefunc() functions.
Change brousefunc() to this:
def browsefunc():
filename = filedialog.askopenfilename()
pathlabel.config(text=filename)
get_info(filename)
This will update your label and then also send the correct file path to the get_info function.
If you still wish to use the label's text for the file path you can do path = pathlabel["text"] as this will assign the value of the text to the path.
I can't test PyPDF2 on my end but the below should work for you.
from PyPDF2 import PdfFileReader
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
def get_info(path):
with open(path, 'rb') as f:
pdf = PdfFileReader(f)
info = pdf.getDocumentInfo()
number_of_pages = pdf.getNumPages()
author = info.author
creator = info.creator
producer = info.producer
subject = info.subject
title = info.title
print(number_of_pages, author, creator, producer, subject, title)
def browsefunc():
filename = filedialog.askopenfilename()
pathlabel.config(text=filename)
get_info(filename)
browsebutton = tk.Button(root, text="Browse", command=browsefunc)
browsebutton.pack()
pathlabel = tk.Label(root)
pathlabel.pack()
root.mainloop()
To address your question in the comments here is an example that displays in the GUI.
from PyPDF2 import PdfFileReader
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
label_list = []
def get_info(path):
with open(path, 'rb') as f:
pdf = PdfFileReader(f)
info = pdf.getDocumentInfo()
label_list[0].config(text=pdf.getNumPages())
label_list[1].config(text=info.author)
label_list[2].config(text=info.creator)
label_list[3].config(text=info.producer)
label_list[4].config(text=info.subject)
label_list[5].config(text=info.title)
def browsefunc():
filename = filedialog.askopenfilename()
pathlabel.config(text=filename)
get_info(filename)
browsebutton = tk.Button(root, text="Browse", command=browsefunc)
browsebutton.pack()
pathlabel = tk.Label(root)
pathlabel.pack()
for i in range(6):
label_list.append(tk.Label(root, text=""))
label_list[i].pack()
root.mainloop()

get the zdata with event from a orthoviewer of medical image

I want get the zdata, from navigation toolbar, when I load a .nii file. I want do that with the event def _onclick(event):
import matplotlib
matplotlib.use('TkAgg')
from tkinter import filedialog
from tkinter import *
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from nibabel.loadsave import read_img_data
from nibabel.loadsave import load as load_nii
from viewers import OrthoSlicer3D
from matplotlib.figure import Figure
import numpy as np
import sys
if sys.version_info[0] < 3:
import Tkinter as Tk
else:
import tkinter as Tk
root = Tk.Tk()
root.wm_title("Orthoslicer3D for brain segmentation")
f = Figure()
sagital = f.add_subplot(221)
sagital.set_position([0,0,0.5,0.5])
sagital.set_axis_off()
coronal = f.add_subplot(222)
coronal.set_axis_off()
coronal.set_position([0,0.5,0.5,0.5])
axial = f.add_subplot(223)
axial.set_position([0.5,0.5,0.5,0.5])
axial.set_axis_off()
axes = (sagital, coronal, axial)
# a tk.DrawingArea
canvas = FigureCanvasTkAgg(f, master=root)
canvas.get_tk_widget().pack(side=Tk.RIGHT, fill=Tk.BOTH, expand=1)
toolbar = NavigationToolbar2TkAgg(canvas, root)
toolbar.update()
canvas._tkcanvas.pack(side=Tk.RIGHT, fill=Tk.BOTH, expand=0)
def _load():
data = filedialog.askopenfilename(initialdir = "/", title = "Select file", filetypes = (("nii files","*.nii"),("gz files", "*.gz"),("all files","*.*")))
data_load = load_nii(data)
data_read = read_img_data(data_load)
data_read = np.asanyarray(data_read)
OrthoSlicer3D(data_read, axes=axes).show()
coords = []
def _onclick(event):
coords.append((event.xdata, event.ydata, event.zdata))
return coords
canvas.mpl_connect('button_press_event', _onclick)
buttonLoad = Tk.Button(master=root, text='Load', command=_load)
buttonLoad.pack(side=Tk.LEFT, expand = 1)
Tk.mainloop()
But the traceback is:
Traceback (most recent call last):
File "C:\Users\migue\Documents\IM\TFG\venv\lib\site-packages\matplotlib\cbook\__init__.py", line 388, in process
proxy(*args, **kwargs)
File "C:\Users\migue\Documents\IM\TFG\venv\lib\site-packages\matplotlib\cbook\__init__.py", line 228, in __call__
return mtd(*args, **kwargs)
File "C:/Users/migue/Documents/IM/TFG/pruebsd.py", line 58, in _onclick
coords.append((event.xdata, event.ydata, event.zdata))
AttributeError: 'MouseEvent' object has no attribute 'zdata'

Using Tkinter and suprocess.call

I would like to use tkinter to open a window that will allow a user to select two separate files that will be manipulated several times within my script. I am having trouble finding a way to set the file that will be selected using the button in my tkinter window as a variable so that it can be used within subprocess.call. I have found invoke() but it doesn't seem to have any affect. Any ideas on what I might do would be greatly appreciated.
import os
import sys
import gdal
from gdalconst import *
import numpy as np
import math
import subprocess
from subprocess import call
import math
import datetime
import shutil
import tkinter
from tkinter import *
from tkinter import filedialog
newpath = os.path.expanduser('~\\Desktop\\Components\\Float32')
if not os.path.exists(newpath):
os.makedirs(newpath)
newpath_2 = os.path.expanduser('~\\Desktop\\Components\\Zeros')
if not os.path.exists(newpath_2):
os.makedirs(newpath_2)
newpath_3 = os.path.expanduser('~\\Desktop\\Components\\db_Files')
if not os.path.exists(newpath_3):
os.makedirs(newpath_3)
if __name__== '__main__':
# Set all of the necessary constants so that the script can create and save the pertinent files
# on the users desktop
#tk1 = Tk()
#tk2 = Tk()
#callTK = 'src_dataset =' + tk1
#callTK_2 = 'srcVH =' + tk2
gdalTranslate = 'C:\Program Files (x86)\GDAL\gdal_translate.exe'
tk1.fileName = filedialog.askopenfilename(text="Open HV File")
tk2.fileName = filedialog.askopenfilename(text="Open VH File")
dst_dataset = os.path.expanduser('~\\Desktop\\Components\\Float32\\newHV32.img')
dstVH = os.path.expanduser('~\\Desktop\\Components\\Float32\\newVH32.img')
sttime = datetime.datetime.now().strftime('(Time_Run = %Y-%d-%m_%H:%M:%S)')
wheel_install_1 = os.path.expanduser('~\\Desktop\\Components\\Sigma_Test\\wheel_install.py')
wheel_install_2 = os.path.expanduser('~\\Desktop\\Components\\Sigma_Test\\wheel_install2.py')
ridofz = os.path.expanduser('~\\Desktop\\Components\\Sigma_Test\\ridofZsv2.py')
to_dB = os.path.expanduser('~\\Desktop\\Components\\Sigma_Test\\to_dBv2.py')
db_HV = os.path.expanduser('~\\Desktop\\Components\\dB_Files\\newHVdB.img')
db_VH = os.path.expanduser('~\\Desktop\\Components\\dB_Files\\newVHdB.img')
cmd = "-ot float32 -of HFA" # hopefully this works
# Install necessary packages, which are GDAL and Numpy
# try:
#os.system(wheel_install_1)
#print ("GDAL intalled")
#os.system(wheel_install_2)
#print ("Numpy installed")
#except:
#print ("The packages are't installing properly")
#sys.exit()
# Create three new folders which will house the files that will be created
# along each sequential step of the script
#newpath = os.path.expanduser('~\\Desktop\\Components\\Float32')
#if not os.path.exists(newpath):
#os.makedirs(newpath)
#newpath_2 = os.path.expanduser('~\\Desktop\\Components\\Zeros')
#if not os.path.exists(newpath_2):
#os.makedirs(newpath_2)
#newpath_3 = os.path.expanduser('~\\Desktop\\Components\\db_Files')
#if not os.path.exists(newpath_3):
#os.makedirs(newpath_3)
root = Tk()
#root.fileName = filedialog.askopenfilename()
root.title("Utilis Sigma Test")
root.iconbitmap(r"C:\Users\jack.UTILIS\Desktop\images\sigma.ico")
root.configure(background="#179EBB")
topFrame = Frame(root)
topFrame.pack()
photo = PhotoImage(file="C:\\Users\\jack.UTILIS\\Desktop\\images\\Utilis_Branding2015_FINAL_Small.gif")
label = Label(root, image=photo)
label.pack(side=RIGHT)
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)
button1 = Button(root, text="Open HV File", fg="black", command=filedialog.askopenfilename)
button2 = Button(root, text="Open VH FIle", fg="black", command=filedialog.askopenfilename)
button1.pack(side=LEFT)
button2.pack(side=RIGHT)
hvfullCmd = ' '.join([gdalTranslate, cmd, tk1.fileName,dst_dataset])
subprocess.call(hvfullCmd)
vhfullCmd = ' '.join([gdalTranslate,cmd, tk2.fileName,dstVH])
subprocess.call(vhfullCmd)
root.mainloop()
You have to create own function which get filename from askopenfilename and does something with this file. Then you can assign this file to button using command=
import tkinter as tk
from tkinter import filedialog
# --- functions ---
def on_click():
filename = filedialog.askopenfilename()
if filename:
print("Filename:", filename)
else:
print("Filename: not selected")
# --- main ---
root = tk.Tk()
btn = tk.Button(root, text='Click Me', command=on_click)
btn.pack()
root.mainloop()

Resources