I am creating a Blackjack game using Python Tkinter and trying to get a simple card image on to a canvas in a Window. I have tried everything but still cannot get this to work. I think the problem is getting the path to the file into my code but I copy and pasted it directly from properties of this image.
Below is the code I have used recently:
from PIL import Image, ImageTk
import random
from tkinter import *
root = Tk()
root.title("Blackjack")
canvas = Canvas(root, bg="green", height=1200, width=800)
canvas.create_image(
600, 400, image=r"C:/Users/dskim/OneDrive/Desktop/GUI/Images/Cards/2_of_clubs.png")
card_img = ImageTk.PhotoImage(
file=r"C:/Users/dskim/OneDrive/Desktop/GUI/Images/Cards/2_of_clubs.png")
canvas.pack()
root.mainloop()
And this is the error I keep getting: _tkinter.TclError: image "C:/Users/dskim/OneDrive/Desktop/GUI/Images/Cards/2_of_clubs.png" doesn't exist
I have tried different path names and also different types of code but still no luck.
CodePudding user response:
You can load the image in .gif
format using tk.PhotoImage()
then add it into canvas
test_gif = PhotoImage(file=r"C:\Users\dskim\OneDrive\Desktop\GUI\Images\Cards\2_of_clubs.gif")
canvas.create_image(600, 400, image=test_gif)
The code should be:
from PIL import Image, ImageTk
import random
from tkinter import *
root = Tk()
root.title("Blackjack")
canvas = Canvas(root, bg="green", height=1200, width=800)
test_gif = PhotoImage(file=r"C:\Users\dskim\OneDrive\Desktop\GUI\Images\Cards\2_of_clubs.gif")
canvas.create_image(600, 400, image=test_gif)
card_img = ImageTk.PhotoImage(file=r"C:\Users\dskim\OneDrive\Desktop\GUI\Images\Cards\2_of_clubs.png")
canvas.pack()
root.mainloop()
You can change your image format from .png
to .gif
through here.
If it doesn't fix the problem, you should check again if there is any typo in the file path.
CodePudding user response:
The image
option of .create_image()
expects an instance of PhotoImage
instead of a full path, so you need to move the line card_img = ImageTk.PhotoImage(...)
before calling .create_image()
:
card_img = ImageTk.PhotoImage(file="C:/Users/dskim/OneDrive/Desktop/GUI/Images/Cards/2_of_clubs.png")
canvas.create_image(600, 400, image=card_img)