我正在尝试用 Python 编写纸牌游戏并想要放置图像,但图像不会出现在 Tkinter 的画布上 [英] I am attempting to code a card game in Python and want to place an image, but the image wont appear on the canvas in Tkinter
问题描述
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 类可以从文件中读取 GIF 和 PGM/PPM 图像:
The PhotoImage class can read GIF and PGM/PPM images from files:
photo = PhotoImage(file="image.gif")
photo = PhotoImage(file="lenna.pgm")
PhotoImage 还可以从字符串中读取 base64 编码的 GIF 文件.您可以使用它在 Python 源代码中嵌入图像(使用 base64 模块中的函数将二进制数据转换为 base64 编码的字符串):
The PhotoImage can also read base64-encoded GIF files from strings. You can use this to embed images in Python source code (use functions in the base64 module to convert binary data to base64-encoded strings):
photo = """
R0lGODdhEAAQAIcAAAAAAAEBAQICAgMDAwQEBAUFBQY GBgcHBwgICAkJCQoKCgsLCwwMDA0NDQ4O
Dg8PDxAQEBERERISEhMTExQUFBUVFRYWFhcXFxgYGBkZ GRoaGhsbGxwcHB0dHR4eHh8fHyAgICEh
...
AfjHtq1bAP/i/gPwry4AAP/yAtj77x+Af4ABAwDwrzAAAP8S
A /j3DwCAfwAA/JsM4J/lfwD+/QMA
4B8AAP9Ci/4HoLTpfwD+qV4NoHVAADs=
"""
photo = PhotoImage(data=photo)
如果您需要处理其他文件格式,Python 图像库 (PIL) 包含的类可让您加载 30 多种格式的图像,并将它们转换为与 Tkinter 兼容的图像对象:
If you need to work with other file formats, the Python Imaging Library (PIL) contains classes that lets you load images in over 30 formats, and convert them to Tkinter-compatible image objects:
from PIL import Image, ImageTk
image = Image.open("lenna.jpg")
photo = ImageTk.PhotoImage(image)
您可以在 Tkinter 接受图像对象的任何地方使用 PhotoImage 实例.一个例子:
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()
您必须在 Python 程序中保留对图像对象的引用,方法是将其存储在全局变量中,或将其附加到另一个对象.
You must keep a reference to the image object in your Python program, either by storing it in a global variable, or by attaching it to another object.
尝试运行:
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()
如果这不起作用,请尝试添加参考
If this does not work try adding a reference
这篇关于我正在尝试用 Python 编写纸牌游戏并想要放置图像,但图像不会出现在 Tkinter 的画布上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!