Tkinter: Difference between revisions
No edit summary |
|||
Line 2: | Line 2: | ||
==Images== | ==Images== | ||
To display an image | To display an image | ||
{{ hidden | Example | | |||
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
import tkinter as tk | import tkinter as tk | ||
Line 27: | Line 28: | ||
canvas.itemconfigure(canvas_image, image=photo_img) | canvas.itemconfigure(canvas_image, image=photo_img) | ||
</syntaxhighlight> | </syntaxhighlight> | ||
}} | |||
;Notes | ;Notes | ||
* Make sure the <code>ImageIk.PhotoImage</code> does not get garbage collected. | * Make sure the <code>ImageIk.PhotoImage</code> does not get garbage collected. |
Revision as of 16:25, 1 February 2021
Tkinter is a Python API for the Tk GUI. It is built into the Python standard library and is cross platform.
Images
To display an image
Example
import tkinter as tk
from PIL import Image, ImageTk
import requests
image_url = 'https://via.placeholder.com/256/0000FF/'
image = Image.open(requests.get(image_url, stream=True).raw)
window = tk.Tk()
main_frame = tk.Frame(window)
main_frame.pack()
canvas = tk.Canvas(main_frame,
width=image.size[0],
height=image.size[1])
canvas.pack()
photo_img = ImageTk.PhotoImage(image=image)
canvas_image = canvas.create_image(0, 0, image=photo_img, anchor=tk.NW)
window.mainloop()
# To update the image later on..
image_url2 = 'https://via.placeholder.com/256/FF00FF/'
image2 = Image.open(requests.get(image_url, stream=True).raw)
photo_img = ImageTk.PhotoImage(image=image2)
canvas.itemconfigure(canvas_image, image=photo_img)
- Notes
- Make sure the
ImageIk.PhotoImage
does not get garbage collected.