python使用Tkinter显示网络图片的方法
本文实例讲述了python使用Tkinter显示网络图片的方法。分享给大家供大家参考。具体实现方法如下:
'''tk_image_view_url_io.py displayanimagefromaURLusingTkinter,PILanddata_stream testedwithPython27andPython33byvegaseat01mar2013 ''' importio #allowsforimageformatsotherthangif fromPILimportImage,ImageTk try: #Python2 importTkinterastk fromurllib2importurlopen exceptImportError: #Python3 importtkinterastk fromurllib.requestimporturlopen root=tk.Tk() #findyourselfapictureonaninternetwebpageyoulike #(rightclickonthepicture,underpropertiescopytheaddress) #url="http://www.google.com/intl/en/images/logo.gif" #oruseimagepreviouslydownloadedtotinypic.com #url="http://i48.tinypic.com/w6sjn6.jpg" url="http://i50.tinypic.com/34g8vo5.jpg" image_bytes=urlopen(url).read() #internaldatafile data_stream=io.BytesIO(image_bytes) #openasaPILimageobject pil_image=Image.open(data_stream) #optionallyshowimageinfo #getthesizeoftheimage w,h=pil_image.size #splitoffimagefilename fname=url.split('/')[-1] sf="{}({}x{})".format(fname,w,h) root.title(sf) #convertPILimageobjecttoTkinterPhotoImageobject tk_image=ImageTk.PhotoImage(pil_image) #puttheimageonatypicalwidget label=tk.Label(root,image=tk_image,bg='brown') label.pack(padx=5,pady=5) root.mainloop()
希望本文所述对大家的Python程序设计有所帮助。