I am new to Tkinter and i am trying to add an image to a text widget in Tkinter python 2.7
I have looked up some resources on the internet and as far as i have gotten is this code but it is giving error -
"
File "anim.py", line 11, in <module>
text.image_create(END,image=photoImg)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 2976, in image_create
*self._options(cnf, kw))
TypeError: __str__ returned non-string (type file)
"
please tell me where i went wrong. Thanks in advance :)
from PIL import Image,ImageTk
from Tkinter import *
root = Tk()
root.geometry("900x900+100+100")
image1 = open('IMG_20160123_170503.jpg')
photoImg = PhotoImage(image1)
frame = Frame(root)
frame.pack()
text = Text(frame)
text.pack()
text.image_create(END,image=photoImg)
root.mainloop()
You have made just two small mistakes. When you open the image as image1 you are using Python's built-in open keyword rather than Image.open, the method of PIL's Image class. You also reference Tkinter's PhotoImage class when you mean to reference PIL's ImageTk.PhotoImage class. Here is your fixed code:
from Tkinter import *
from PIL import Image,ImageTk
root = Tk()
root.geometry("900x900+100+100")
image1 = Image.open("IMG_20160123_170503.jpg")
photoImg = ImageTk.PhotoImage(image1)
frame = Frame(root)
frame.pack()
text = Text(frame)
text.pack()
text.image_create(END,image=photoImg)
root.mainloop()
Related
I made a tkinter app for displaying images, and I was wondering if there's a way to make an image open by default with this app
At the moment if I try that, I get an error for some non declared icon file (this is the icon that appears near the name of the app at the top)
There's no real goal behin this Gui, I'm just experimenting and learning.
Thanks
Try this:
from PIL import Image, ImageTk
import tkinter as tk
from tkinter import filedialog
my_img = []
def FileImport():
file = filedialog.askopenfilename()
my_img.clear()
my_img.append(ImageTk.PhotoImage(Image.open(file)))
label1.config(image=my_img[0])
root= tk.Tk()
root.title('Main')
root.geometry('400x400')
label = tk.Label(root, text = "Browse", fg="purple")
label.pack()
button = tk.Button(root, text='See Image',fg="blue", command=FileImport)
button.pack()
my_img.append(ImageTk.PhotoImage(Image.open(your_first_image)))
label1 = tk.Label(root, image = my_img[0])
label1.pack(pady= 50)
root.mainloop()
When you run this:
After you tap to see different image from computer:
Hope It helps!
I made a GUI with few buttons and I want to change the gray background to an image.
my code looks like this:
from tkinter import *
from urlread import givenumbers # my function
""" Setting The Main GUI """
GUI = Tk()
GUI.title('Check GUI')
GUI.iconbitmap('test.ico')
GUI.geometry("400x400")
background_image=PhotoImage('pic.jpg')
background_label = Label(GUI, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
""" Reading Images For Buttons """
A_Im = PhotoImage(file='A.gif')
""" Creating Buttons """
# A Button
A_Button = Button(GUI, image=A_Im, command=givenumbers)
A_Button.grid(column=0, row=1)
GUI.mainloop()
The code runs without error but the background is still gray without any effect.
The problem is in the line background_image=PhotoImage('pic.jpg'). The PhotoImage class only supports GIF-files, which means that it cannot read the file you're specifying. You should try something like this:
#Python 2.7
import Tkinter as tk
from PIL import Image, ImageTk
window = tk.Tk()
image = Image.open('image.jpg')
photo_image = ImageTk.PhotoImage(image)
label = tk.Label(window, image = photo_image)
label.pack()
# Python 3
import tkinter as tk
from PIL import Image, ImageTk
window = tk.Tk()
image = Image.open('image.jpg')
photo_image = ImageTk.PhotoImage(image)
label = tk.Label(window, image = photo_image)
label.pack()
The Image class from the PIL module supports a variety of formats, among which jpeg and png. You can install the PIL module by running pip install pillow in a command prompt or terminal.
If you want to put the widgets on top of the Label, you could indeed using grid to get them on top of each other, but using a Canvas would probably be easier. You can find more about the Canvas widget here.
This can be done without pil also:
from tkinter import *
import tkinter as ttk
""" Setting The Main GUI """
GUI = Tk()
F1=Frame(GUI)
F1=Frame(GUI,width=400,height=450)
F1.place(height=7000, width=4000, x=100, y=100)
F1.config()
F1.grid(columnspan=10,rowspan=10)
F1.grid_rowconfigure(0,weight=1)
F1.grid_columnconfigure(0,weight=1)
photo=PhotoImage(file="C:\\Users\\HOME\\Desktop\\Eshita\\12th\\computer
\\python\\GUI\\math3.gif")
label = Label(GUI,image = photo)
label.image = photo # keep a reference!
label.grid(row=0,column=0,columnspan=20,rowspan=20)
b=ttk.Button(GUI,text="Start")
b.grid(row=8,column=8)
GUI.mainloop()
I am making a tkiner application and that shows a user a page with some basic information and a picture before allowing them to click a button to view live Bitcoin price data. However, when I added the image to the 'start up' page, I got this error from my IDE:
BTC_img_label = tk.Label(self, image=BTC_img)
File "C:\Python34\lib\tkinter\__init__.py", line 2609, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "C:\Python34\lib\tkinter\__init__.py", line 2127, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image "pyimage10" doesn't exist
I believe that these are the lines of code that are causing my error (they are the same lines that add the image to the 'start up' page):
BTC_img = tk.PhotoImage(file='bitcoin.png')
BTC_img_label = tk.Label(self, image=BTC_img)
BTC_img_label.image = BTC_img
BTC_img_label.grid(row=2, column=0)
I also noticed that the icon that I set does not show in the GUI window when the program is run, only the default Tkinter feather icon. Here's my icon setting code if anyone is interested (though I'm pretty sure it's not causing my error):
tk.Tk.iconbitmap(self, default='main.ico')
And yes, for anyone wondering, I did import tkinter as tk, so that is not my error. If anyone could also tell me why this error happens, I would be very interested: I haven't seen a lot of other examples of this happening, and the ones I have seen had no mention to my icon problem. Hope somebody can figure this out!
Like #joost-broekhuizen, I've had the same problem using Tkinter together with matplotlib.pyplot functions. Adding a 'master' to the PhotoImage function solved the problem for me.
Broken code (raises: TclError: image "pyimage10" doesn't exist):
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
import Tkinter as tk
from PIL import Image, ImageTk
fig = plt.figure()
root = tk.Tk()
image = Image.open("background.png")
photo = ImageTk.PhotoImage(image)
label = tk.Label(root, image=photo)
label.image = image
label.pack()
root.mainloop()
Adding 'master=root' to PhotoImage solved this error!
photo = ImageTk.PhotoImage(image, master=root)
You can not load a .png format with tkinter. You rather need to use the PIL library for that:
import PIL
image = PIL.Image.open("bitcoin.png")
BTC_img = PIL.ImageTk.PhotoImage(image)
BTC_img_label = tk.Label(self, image=BTC_img)
BTC_img_label.image = BTC_img
BTC_img_label.grid(row=2, column=0)
EDIT:
Please, create a test.py file and run this EXACT code:
import tkinter as tk
from PIL import Image, ImageTk
root = tk.Tk()
image = Image.open("bitcoin.png")
photo = ImageTk.PhotoImage(image)
label = tk.Label(root, image=photo)
label.image = photo
label.grid(row=2, column=0)
#Start the program
root.mainloop()
Tell me if you get an error or not.
I had the same problem. The problem was importing matplotlib.pyplot in the same program or in another py file from which you import definitions. Use Canvas for your plots instead
This problem can be solved by adding master=root in Photoimage Constructor
like for e.g.
pic=Photoimage(master=self.root,file='mypic.png')
Label(self.root,image=pic).pack()
I am trying to display an image to a tkinter GUI using tkinter.Label() widget. The procedure seems simple and straightforward, but this code doesn't work!
code:
import Tkinter as tk
import Image, ImageTk, sys
filename = 'AP_icon.gif'
im = Image.open(filename) # Image is loaded, because the im.show() works
tkim = ImageTk.PhotoImage(im)
root = tk.Tk()
label = tk.Label(root, image = tkim) # Here is the core problem (see text for explanation)
label.image = tkim # This is where we should keep the reference, right?
label.grid (row = 0, column = 0)
tk.Button(root, text = 'quit', command = lambda: sys.exit()).grid(row = 1, column = 1)
root.mainloop()
When we execute this code, it doesn't compile, giving an error:
TclError: image "pyimage9" doesn't exist
When I define label without its parent root, No compilation error occurs, but the GUI does not display any image!
Can anyone identify what could be the issue?
This problem happens when we attempt to run the above code in Ipython. And it can be solved by changing the line
root = tk.Tk() to
root = tk.Toplevel()
You need to create the root widget before you call any other tkinter functions. Move the creation of root to be before the creation of the image.
The general way which I use to display an image in tkinter is:
import Tkinter as tk
root = tk.Tk()
image1 = tk.PhotoImage(file = 'name of image.gif')
# If image is stored in the same place as the python code file,
# otherwise you can have the directory of the image file.
label = tk.Label(image = image1)
label.image = image1 # yes can keep a reference - good!
label.pack()
root.mainloop()
In the above case it works but you have something like:
import Tkinter as tk
image = tk.PhotoImage(file = 'DreamPizzas.gif') #here this is before root = tk.Tk()
root = tk.Tk()
# If image is stored in the same place as the python code file,
# otherwise you can have the directory of the image file.
label = tk.Label(image = image)
label.image = image
label.pack()
root.mainloop()
this gives me a runtime error: too early to create image.
but you have said that your error is image pyimage9 doesn't exist, this is strange because at the top you have set filename to 'AP_icon.gif', so you would think that you get a different error as I dont know where pyimage9 comes from. This makes me think that maybe you are getting the file name incorrect somewhere? You also need to move root = tk.Tk() to the top under imports.
Restart the Kernel to get rid of the error "TclError: image "pyimage9" doesn't exist"
Try the following code as I am able to rectify the same error:
window=Tk()
c=Canvas(window,height=2000,width=2000)
p=PhotoImage(file='flower1.gif',master = c)
c.create_image(500,500,image=p)
I am trying to load images dynamically through browse button to Tkinter window but I am getting the empty window. This is the code of callback function of browse button
supformats = [
('Windows Bitmap','*.bmp'),
('Portable Network Graphics','*.png'),
('JPEG ','*.jpg'),
('CompuServer GIF','*.gif'),
]
filename = askopenfilename(filetypes=supformats)
FILENAME = filename
im=Image.open(FILENAME)
w=im.size[0]
h=im.size[1]
root = Tkinter.Tk()
#canvas = Tkinter.Canvas(root, width=w, height=h)
#canvas.grid(row=0,column=0)
#tk_img = ImageTk.PhotoImage(file = FILENAME)
#canvas.create_image(image=tk_img)
im.show()
root.mainloop()
Thanks in advance for everyone who will help
From effbot's explanation http://effbot.org/tkinterbook/photoimage.htm Note that the file is accessed once only, not twice. This assumes you are using the Python Imaging Library in Tkinter as you did not state what image toolkit is being used.
from PIL import Image, ImageTk
image = Image.open("lenna.jpg")
photo = ImageTk.PhotoImage(image)
You can use a PhotoImage instance everywhere Tkinter accepts an image object.
An example:
label = Label(image=photo)
label.image = photo # keep a reference!
label.pack()