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

↘锁芯ラ 提交于 2019-12-13 06:51:27

问题


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()

回答1:


The PhotoImage class can read GIF and PGM/PPM images from files:

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

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

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)

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)

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()

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.

Try running:

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



来源:https://stackoverflow.com/questions/43413849/i-am-attempting-to-code-a-card-game-in-python-and-want-to-place-an-image-but-th

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!