我试图编写一个简单的程序,将图像(从网站上)插入按钮按下的标签中。这是我到目前为止所拥有的
# Import the function for downloading web pages
from urllib import urlopen
# Import the regular expression function
from re import findall
# Import the Tkinter functions
from Tkinter import *
# Import a constructor for converting byte data to character strings
from StringIO import *
import io
# Import the Python Imaging Library module (comment this line out
# if you do not intend to use PIL in your solution)
from PIL import Image, ImageTk
#create window
root = Tk()
def button():
url = 'http://www.technologyreview.com/topnews.rss'
html = urlopen(_url).read()
img_url = findall('<<media:content url="(.+\.jpg)"',html)
url = img_url[0] #First instance of image url ending in JPG.
image_bytes = urlopen(url).read()
# internal data file
data_stream = io.BytesIO(image_bytes)
# open as a PIL image object
pil_image = Image.open(data_stream)
#resize
pil_image= pil_image.resize((400, 400),Image.ANTIALIAS)
# optionally show image info
# get the size of the image
w, h = pil_image.size
# split off image file name
fname = url.split('/')[-1]
sf = "{} ({}x{})".format(fname, w, h)
root.title(sf)
# convert PIL image object to Tkinter PhotoImage object
tk_image = ImageTk.PhotoImage(pil_image)
#lastly, put the image into label
label['image'] = tk_image
# create label widget and button widgets.
label =Label(root, bg='black')
label.grid(column = 0, row = 0)
button=Button(root, text = 'Press me', command = button)
button.grid(column = 0, row = 1)
#run
root.mainloop()
我知道图片网址的工作原理。目前,它只是将标签显示为400x400黑色方块,按钮上没有图像。
原谅可怕的编码。 :) 感谢