2012-04-13 89 views
13

¿Cómo agrego una imagen en Tkinter?¿Cómo agregar una imagen en Tkinter?

Esto me dio un error de sintaxis:

root = tk.Tk() 
img = ImageTk.PhotoImage(Image.open(path)) 
panel = tk.Label(root, image = img) 
panel.pack(side = "bottom", fill = "both", expand = "yes") 
root.mainloop() 
+0

le recomiendo que lea el libro "programación Python y Tkinter". Muy buen libro, completo. Probablemente pueda encontrarlos en eBay a precios más bajos. Eso es asumiendo que realmente quieres usar TKinter. Sin embargo, recomiendo Qt en lugar de Tkinter – frankliuao

Respuesta

5

No hay un "error de sintaxis" en el código anterior - ya sea ocurrio en alguna otra línea (lo anterior no es todo el código, ya que hay no importa, ni la declaración de su variable path) o tiene algún otro tipo de error.

El ejemplo anterior funcionó bien para mí, probando en el intérprete interactivo.

4

siguiente código funciona en mi máquina

  1. es probable que tenga algo que falta en su código.
  2. compruebe también la codificación de los archivos de código.
  3. asegúrese de tener instalado el paquete PIL

    import Tkinter as tk 
    from PIL import ImageTk, Image 
    
    path = 'C:/xxxx/xxxx.jpg' 
    
    root = tk.Tk() 
    img = ImageTk.PhotoImage(Image.open(path)) 
    panel = tk.Label(root, image = img) 
    panel.pack(side = "bottom", fill = "both", expand = "yes") 
    root.mainloop() 
    
10

Python 3.3.1 [MSC v.1600 32 bits (Intel)] en win32 14.May.2013

Esto funcionó para yo, siguiendo el código anterior

from tkinter import * 
from PIL import ImageTk, Image 
import os 

root = Tk() 
img = ImageTk.PhotoImage(Image.open("True1.gif")) 
panel = Label(root, image = img) 
panel.pack(side = "bottom", fill = "both", expand = "yes") 
root.mainloop() 
2

No es una lib estándar de Python 2.7. Así que para que éstos funcionen correctamente y si está utilizando Python 2.7 se deben descargar la biblioteca PIL primera: enlace de descarga directa: http://effbot.org/downloads/PIL-1.1.7.win32-py2.7.exe Después de instalarlo, siga estos pasos:

  1. asegurarse de que su guión .py es en la misma carpeta conimagen que desea mostrar.
  2. Editar su script.py

    from Tkinter import *   
    from PIL import ImageTk, Image 
    
    app_root = Tk() 
    
    #Setting it up 
    img = ImageTk.PhotoImage(Image.open("app.png")) 
    
    #Displaying it 
    imglabel = Label(app_root, image=img).grid(row=1, column=1)   
    
    
    app_root.mainloop() 
    

Espero que ayude!

-1

Aquí se muestra un ejemplo para Python 3 que se puede editar para Python 2;)

from tkinter import * 
from PIL import ImageTk, Image 
from tkinter import filedialog 
import os 

root = Tk() 
root.geometry("550x300+300+150") 
root.resizable(width=True, height=True) 

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) 
    panel = Label(root, image=img) 
    panel.image = img 
    panel.pack() 

btn = Button(root, text='open image', command=open_img).pack() 

root.mainloop() 

enter image description here

0

Es un problema de la versión de Python. Si está utilizando lo último, entonces su sintaxis anterior no funcionará y le dará este error. Por favor, sigue el código de @ Josav09 y estarás bien.

0

Su código actual puede devolver un error basado en el formato del archivo path puntos a. Dicho esto, algunos formatos de imagen como .gif, .pgm (y .png si tk.TkVersion> = 8.6) ya son compatibles con la clase PhotoImage.

A continuación se muestra un ejemplo que muestra:

Lenna (.png)

o si tk.TkVersion < 8.6:

Lenna (.gif)

try:      # In order to be able to import tkinter for 
    import tkinter as tk # either in python 2 or in python 3 
except ImportError: 
    import Tkinter as tk 


def download_images(): 
    # In order to fetch the image online 
    try: 
     import urllib.request as url 
    except ImportError: 
     import urllib as url 
    url.urlretrieve("https://i.stack.imgur.com/IgD2r.png", "lenna.png") 
    url.urlretrieve("https://i.stack.imgur.com/sML82.gif", "lenna.gif") 


if __name__ == '__main__': 
    download_images() 
    root = tk.Tk() 
    widget = tk.Label(root, compound='top') 
    widget.lenna_image_png = tk.PhotoImage(file="lenna.png") 
    widget.lenna_image_gif = tk.PhotoImage(file="lenna.gif") 
    try: 
     widget['text'] = "Lenna.png" 
     widget['image'] = widget.lenna_image_png 
    except: 
     widget['text'] = "Lenna.gif" 
     widget['image'] = widget.lenna_image_gif 
    widget.pack() 
    root.mainloop() 
Cuestiones relacionadas