I am getting the error in the open_img when I try to run it. I am making an Emotion detector. I want to upload an image in tkinter. That's what my code is about.
Any help or advice would be appreciated.
Here is my script, my environment, the error traceback, and what have investigated so far.
import tkinter as tk
from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog
root = Tk()
root.title("Emotion Detector")
canvas1 = tk.Canvas(root, width = 1200, height = 700, bg='blue')
canvas1.pack()
root.resizable(width=True, height=True)
btn = Button(root, text='open image', command=open_img).grid(row=1,columnspan=4)
root.mainloop
def openfn():
filename = filedialog.askopenfilename(title='open')
return filename
def open_img():
x = openfn()
img = Image.open(x)
img = img.resize((250, 250), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
print(img)
panel = Label(root, image=img)
panel.image = img
panel.grid(row=2)
My error is attached below:
Traceback (most recent call last):
File "C:/Users/hiler/Desktop/Internship/Frontend Python Final.py", line 11, in <module>
btn = Button(root, text='open image', command=open_img).grid(row=1,columnspan=4)
NameError: name 'open_img' is not defined
I have seen an error of the same name here, but that appears to be a separate issue. So, I don't understand what to rectify in the code.
I am using IDLE python 3.9.7
move the function at the begin of the file. you are also missing () in
root.mainloop
change into root.mainloop()
Related
I am currently working on building an UI to show the images in my JupyterLab to my Tkinter UI, that is running on a same script. In my script, I hope that after entering the values in Tkinter, it will take in the input and run again, and show the image on Tkinter UI again, so that I can do try and error. Can anyone guide me or give me a little tips to know where to find the answer and how to work on it?
from tk import *
from tkinter import ttk
from PIL import ImageTk, Image
import tkinter as tk
import os
window = tk.Tk()
def show_result(a,b,c,d):
#display the image result
#run the again to test the result
x1 = tk.IntVar()
x2 = tk.IntVar()
y1 = tk.IntVar()
y2 = tk.IntVar()
# set textbox to capture variables
x1_value = ttk.Entry(textvariable=x1).place(x=50, y=50)
x2_value = ttk.Entry(textvariable=x2).place(x=50, y=100)
y1_value = ttk.Entry(textvariable=y1).place(x=50, y=150)
y2_value = ttk.Entry(textvariable=y2).place(x=50, y=200)
display_button = ttk.Button(text="Run", command= lambda: show_result(x1.get(),x2.get(),y1.get(),y2.get())).place(x=50, y=300)
window.geometry("900x750")
window.mainloop( )
plt.figure(figsize = (50,8))
plt.imshow(crop_img, cmap='gray')
fig1 = plt.gcf()
fig1.savefig('crop_img.png', dpi=100)
open_img()
# Open img to show on tkinter
def open_img():
x = 'crop_img.png'
img = Image.open(x)
left=2000
top=0
right=3000
bottom=800
img = img.crop((left, top, right, bottom))
img = img.resize((800, 600), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
panel = Label(window, image=img)
panel.image = img
panel.place(x=200, y=0)
I'm working on a python project that takes an image that the user selects and removes a certain color from it, I'm trying to display the selected image along with a button that takes you to the selection menu on the file explorer on the user's computer, the button works just fine, but the image is not being displayed at all. any help would be appreciated.
the code:
#import
from PIL import Image, ImageTk
from fileinput import filename
import tkinter as tk
from tkinter import filedialog
from tkinter import *
root = Tk()
root.geometry("750x500")
root.title("Shibly Letter Head")
canvas = Canvas(root, width = 500, height = 500)
canvas.pack()
#uploaded info
def UploadAction(event=None):
from PIL import Image
filename = filedialog.askopenfilename()
print('Selected:', filename)
img = Image.open(filename)
img.show()
image_data = img.load()
height,width = img.size
for loop1 in range(height):
for loop2 in range(width):
r,g,b = image_data[loop1,loop2]
image_data[loop1,loop2] = 0,g,b
img.save('changed.jpeg')
#display image
canvas.create_image(10,
10,
anchor=NW,
image= filename
)
#button
button = tk.Button(root, text='Open', height=5, width=45, command=UploadAction)
button.place(x=220, y=419)
root.mainloop()
PS, apologies if this is a dumb question but I'm still a beginner and couldn't fix this problem myself.
I am trying to run following code, which run successfully... but when I am trying to import matplotlib it give error ----> _tkinter.TclError: image "pyimage1" doesn't exist while using PyCharm, but with python IDLE it works without error.
import cv2
from tkinter import *
from PIL import Image, ImageTk
import datetime
import openpyxl
#from matplotlib import pyplot as plt
def show_frames():
im = cap.read()[1]
Image1= cv2.cvtColor(im,cv2.COLOR_BGR2RGB)
img = Image.fromarray(Image1)
imgtk = ImageTk.PhotoImage(image = img)
label.imgtk = imgtk
label.configure(image=imgtk)
label.after(20, show_frames)
def capture():
I = cap.read()[1]
save_name = str(datetime.datetime.now().today()).replace(":", " ") + ".jpg"
cv2.imwrite(save_name, I)
#here creating window and GUI
win = Tk()
win.geometry("1200x650")
win.title('Portable Optical Spectrometer')
L2 = Label(win,text = " Camera ",font=("times new roman",20,"bold"),bg="white",fg="red").grid(row=0, column=0)
L2 = Label(win,text = " Spectrum Graph ",font=("times new roman",20,"bold"),bg="white",fg="red").grid(row=0, column=2)
label =Label(win)
label.grid(row=1, column=0)
cap = cv2.VideoCapture(0)
show_frames()
B1 = Button(win,text="Capture",font=("Times new roman",20,"bold"),bg="white",fg="red",command=capture()).grid(row=3, column=0, )
B1 = Button(win,text="Analysis",font=("Times new roman",20,"bold"),bg="white",fg="red",).grid(row=4, column=0)
L1 = Label(win,text = "Detected Material is: ",font=("times new roman",20,"bold"),bg="white",fg="red").grid(row=4, column=1)
Output = Text(win, height = 3,width = 25,bg = "light cyan").grid(row=4, column=2)
win.mainloop()
cap.release()
can someone suggest how to solve this error
Yeah, the PhotoImage is poorly documented, but it seems that if you have more than one Tkinter root then you need to specify which root that the PhotoImage should use — with the "master" argument. This applies to both the basic Tkinter PhotoImage and Pillow's ImageTk wrapper. Matplotlib usually uses Tk as its backend so that will usually invoke the problem. IDLE also uses Tk so it's anybody's guess what that combination would do.
See the following example. If the "master=" argument is removed from either of the two PhotoImage creation lines below then it errors out.
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
import tkinter as tk
root = tk.Tk()
photimg = tk.PhotoImage(width=100,height=100, master=root)
tk.Label(root, image=photimg).pack()
from PIL import Image, ImageTk
pilimg = Image.new(mode="RGB", size=(200, 200))
imgtk = ImageTk.PhotoImage(image=pilimg, master=root)
tk.Label(root, image=imgtk).pack()
I am trying to display an image in Tkinter canvas along with some text and I am running into the following error. Also, my mac doesn't show background colors for buttons when run using Spyder in anaconda (Spyder up-to-date).
My python code is:
from tkinter import *
from PIL import ImageTk,Image
def plot_best_batsmen():
best_batsmen = dataset.loc[dataset.loc[dataset['Innings']>=15,'Average'].idxmax(),'Names']
message = ("The best Batsman of the Tournament could possibly be: ", best_batsmen)
canvas_width = 500
canvas_height = 500
root = Tk()
root.geometry("600x600")
root.title("New Window")
canvas = Canvas(root, width=canvas_width, height=canvas_height)
canvas.create_text(1, 10, anchor=W, text=message)
img = ImageTk.PhotoImage(Image.open("prediction.jpg"))
canvas.create_image(20, 20, anchor=NW, image=img)
canvas.image = img
canvas.pack()
root.mainloop()
It's displaying an error message as follows when running:
Exception in Tkinter callback
Traceback (most recent call last):
File "/anaconda3/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
return self.func(*args)
File "/Users/vivekchowdary/Documents/PS3_Final_Project/Batsmen.py", line 110, in plot_best_batsmen
canvas.create_image(20, 20, anchor=NW, image=img)
File "/anaconda3/lib/python3.7/tkinter/__init__.py", line 2489, in create_image
return self._create('image', args, kw)
File "/anaconda3/lib/python3.7/tkinter/__init__.py", line 2480, in _create
*(args + self._options(cnf, kw))))
_tkinter.TclError: image "pyimage3" doesn't exist
Code for buttons is as follows:
b1 = Button(root, text="Elbow Method", command=plot_elbow, bg="green", fg="white").pack(side = LEFT)
b2 = Button(root, text="K-Means Clustering", command=plot_kmeans, bg="blue", fg="white").pack(side = LEFT)
b3 = Button(root, text="Batsmen who scored 4 or more Hundreds", command=plot_hundreds, bg="#D35400", fg="white").pack(side = LEFT)
b4 = Button(root, text="Runs Scored by Various Players", command=plot_runs, bg="#117A65", fg="white").pack(side = LEFT)
b5 = Button(root, text="Best Batsmen", command=plot_best_batsmen, bg="#34495E", fg="white").pack(side = LEFT)
b6 = Button(root, text="Stop", command=root.destroy, bg="red", fg="white").pack(side = BOTTOM)
I want Tkinter to display the following image. But it's reporting an error instead. Can anyone please help me in solving this error?
tkinter also has a class/function called Image. You also imported Image from PIL. You need to make sure which Image.open you are trying to use. tkinter.Image doesn't have an attribute 'open'.
it seems that the error has nothing to do with your tkinter. To identify the problem, can you please just
from PIL import Image
print(Image.open)
the result should look like the following if you have installed everything correctly.
< function open at 0x0000000008A26488 >
I figured out the answer myself and just felt like sharing it to help someone with the same doubt.
We need to import PIL after Tkinter as Tkinter also has its own class Image which doesn't have 'open' functionality and this Image from Tkinter replaces the Image from PIL if imported after PIL.
and the second thing which has to be done is to replace root = Tk() with root = Toplevel() because the problem is when Python/Tkinter is trying to build canvas from the button, it's essentially trying to create two windows under root and falling over.
Now, the code is importing the photo into the GUI and is working fine.
So, finally the code below is working fine:
def plot_best_batsmen():
best_batsmen = dataset.loc[dataset.loc[dataset['Innings']>=15,'Average'].idxmax(),'Names']
message = ("The best Batsman of the Tournament could possibly be: ",best_batsmen)
canvas_width = 400
canvas_height = 500
root = Toplevel()
root.geometry("700x600")
root.title("New Window")
canvas = Canvas(root, width=canvas_width, height=canvas_height)
canvas.create_text(1, 10, anchor=W, text=message)
img = ImageTk.PhotoImage(Image.open("virat.jpg"))
canvas.create_image(150, 20, anchor=NW, image=img)
canvas.image = img
canvas.pack()
root.mainloop()
I am new to this site, and I am trying to create a simple image viewer in Python 2.7 using Tkinter, But when I try to load an image in it,it does not show anything!, I bet it is something embarassingly obvious, but I dont know what's wrong. I am using Windows XP. Here's my code:
from Tkinter import *
import tkFileDialog
from PIL import ImageTk, Image
root = Tk(className="Image viewer")
canvas_width = 800
canvas_height = 600
root.config(bg="white")
def openimage():
picfile = tkFileDialog.askopenfilename()
img = ImageTk.PhotoImage(file=picfile)
canvas.create_image(0,0, anchor=NW, image=img)
yscrollbar = Scrollbar(root)
yscrollbar.pack(side=RIGHT, fill=Y)
xscrollbar = Scrollbar(root, orient=HORIZONTAL)
xscrollbar.pack(side=BOTTOM, fill=X)
canvas = Canvas(root, width=canvas_width, height=canvas_height, yscrollcommand=yscrollbar.set, xscrollcommand=xscrollbar.set)
button = Button(root,text="Open",command=openimage)
button.pack(side=BOTTOM)
canvas.pack(side=TOP)
yscrollbar.config(command=canvas.yview)
xscrollbar.config(command=canvas.xview)
mainloop()
Update: It works when i remove the file browser, and give it the path to a file, but i want the file browser, and using a label works, but scroll bars dont work with it, and i want to be able to scroll the picture.
I found on "The Tkinter PhotoImage Class" that PhotoImage can't be assigned to local variable in function because garbage collector remove it.
So you can use global variable:
img = None
def openimage():
global img
picfile = tkFileDialog.askopenfilename()
img = ImageTk.PhotoImage(file=picfile)
canvas.create_image(0,0, anchor=NW, image=img)
or assign image to existing widget (for example canvas)
def openimage():
picfile = tkFileDialog.askopenfilename()
canvas.img = ImageTk.PhotoImage(file=picfile)
canvas.create_image(0,0, anchor=NW, image=canvas.img)
by the way: you should check if file was selected
def openimage():
picfile = tkFileDialog.askopenfilename()
if picfile:
canvas.img = ImageTk.PhotoImage(file=picfile)
canvas.create_image(0,0, anchor=NW, image=canvas.img)
add scrollregion and you have file viewer with working scrollbars
def openimage():
picfile = tkFileDialog.askopenfilename()
if picfile:
canvas.img = ImageTk.PhotoImage(file=picfile)
canvas.create_image(0,0, anchor=NW, image=canvas.img)
canvas.configure(canvas, scrollregion=(0,0,canvas.img.width(),canvas.img.height()))
Dont know about problem in your code but You can use this function in place of your one:
def openimage():
try:
Artwork.destroy()
except Exception:
pass
picfile = tkFileDialog.askopenfilename()
img = ImageTk.PhotoImage(file=picfile)
#canvas.create_image(0,0, anchor=NW, image=img)
Artwork=Label(root,image=img)
Artwork.img=img
Artwork.pack(side=BOTTOM)#do packing urself
Note that is is the minimal implementation.