Bild in Python 3.12.1 anzeigen lassen?
Wie kann man in Python 3.12.1 ein Bild anzeigen lassen? Ich verwende Visual Studio Code. Ich hab es mit "tkinter" und "pygame" versucht, aber das funktioniert beides nicht.
import tkinter
from tkinter import *
root = Tk()
canvas = Canvas(root, width=200, height=200)
canvas.pack()
yourImage = PhotImage(file="path/of/the/image.png")
canvas.create_image(0, 0, image=yourImage)
mainloop()
pygame kann ich gar nicht importieren in VSC. Hat jemand eine Lösung?
1 Antwort
Von gutefrage auf Grund seines Wissens auf einem Fachgebiet ausgezeichneter Nutzer
Code, Programmiersprache, Python
Beispiel:
import tkinter as tk
root = tk.Tk()
image = tk.PhotoImage(file="path\\to\\image")
label = tk.Label(root, image=image)
label.pack()
root.mainloop()
Einmal davon abgesehen, dass der Bildpfad passen muss, werden von tkinter nur bestimmte Bildformate unterstützt (GIF, PGM, PNG, PPM). Wenn du JPG-Bilder darstellen möchtest, musst du dir eine zusätzliche Bibliothek wie Pillow zu Hilfe nehmen.
from PIL import Image, ImageTk
# ...
image = Image.open(file="path\\to\\image")
photo = ImageTk.PhotoImage(image)
label = tk.Label(root, image=photo)
# ...