Python 2.7 我正在尝试用Python编写一个纸牌游戏,并希望放置一个图像,但该图像不会出现在Tkinter的画布上

Python 2.7 我正在尝试用Python编写一个纸牌游戏,并希望放置一个图像,但该图像不会出现在Tkinter的画布上,python-2.7,tkinter,tkinter-canvas,Python 2.7,Tkinter,Tkinter Canvas,PhotoImage类可以从以下文件中读取GIF和PGM/PPM图像: from Tkinter import * frame = Tk() frame.geometry("1200x900") w = Canvas(frame,width=250,height=450) w.place(x=30,y=300) img=PhotoImage(file="card2.ppm") w.create_image(100,100,anchor=NW,image=img) frame.mainloo

PhotoImage类可以从以下文件中读取GIF和PGM/PPM图像:

from Tkinter import *
frame = Tk()
frame.geometry("1200x900")

w = Canvas(frame,width=250,height=450)
w.place(x=30,y=300)

img=PhotoImage(file="card2.ppm")
w.create_image(100,100,anchor=NW,image=img)

frame.mainloop()
PhotoImage还可以从字符串中读取base64编码的GIF文件。您可以使用它在Python源代码中嵌入图像使用base64模块中的函数将二进制数据转换为base64编码字符串:

photo = PhotoImage(file="image.gif")

photo = PhotoImage(file="lenna.pgm")

如果需要使用其他文件格式,Python Imaging Library PIL包含的类可用于加载30多种格式的图像,并将其转换为与Tkinter兼容的图像对象:

    AfjHtq1bAP/i/gPwry4AAP/yAtj77x+Af4ABAwDwrzAAAP8S 
  A /j3DwCAfwAA/JsM4J/lfwD+/QMA
4B8AAP9Ci/4HoLTpfwD+qV4NoHVAADs=
"""

photo = PhotoImage(data=photo)
只要Tkinter接受图像对象,就可以使用PhotoImage实例。例如:

from PIL import Image, ImageTk

image = Image.open("lenna.jpg")
photo = ImageTk.PhotoImage(image)
必须在Python程序中保留对image对象的引用,方法是将其存储在全局变量中,或将其附加到另一个对象

尝试运行:

label = Label(image=photo)
label.image = photo # keep a reference!
label.pack()
如果这不起作用,请尝试添加引用

label = Label(image=photo)
label.image = photo # keep a reference!
label.pack()
import Tkinter as tk
 root = tk.Tk()
root.title("display a website image")
photo = tk.PhotoImage(file= 
r "C:\Some\Local\location\smile.ppm")
cv = tk.Canvas()
cv.pack(side='top', fill='both', expand='yes')
cv.create_image(10, 10, image=photo, anchor='nw')
root.mainloop()