Python/이것저것 파이썬

tkinter 인터넷의 이미지를 출력

컴닥 2021. 11. 30. 05:45
반응형

이미지를 파일로 저장하지 않고 base64로 변환한 뒤 출력한다. 

내장 라이브러리만 이용해서 간편하게...
PIL을 이용해도 좋겠지만...

"""
Tk_Canvas_Image_url.py
display an image obtained from an internet web page in Tkinter
tested with Python33  by  vagaseat   21nov2012
"""
import base64
import tkinter as tk
from urllib.request import urlopen

root = tk.Tk()
root.title("display a website image")

# a little more than width and height of image
w = 520
h = 320
x = 80
y = 100

# use width x height + x_offset + y_offset (no spaces!)
root.geometry("%dx%d+%d+%d" % (w, h, x, y))

image_url = "https://pretagteam.com/globalimg/logo-blue.png"

image_byt = urlopen(image_url).read()
image_b64 = base64.encodebytes(image_byt)
photo = tk.PhotoImage(data=image_b64)

# create a white canvas
cv = tk.Canvas(bg='white')
cv.pack(side='top', fill='both', expand='yes')

# put the image on the canvas with
# create_image(xpos, ypos, image, anchor)
cv.create_image(10, 10, image=photo, anchor='nw')

root.mainloop()

원래 파이썬 2, 3에서 모두 작동하는 코드였습니다만,
파이썬 3만 남겼습니다. 요즘 누가 파이썬 2를...

잘 작동합니다. 

반응형