Tkinter 变幻无常的图片,有些是空白的,有些则不是

Tkinter being fickle with pictures, some are blank, others are not

注意:主要问题尚未解决,但代码在 Windows PC 上运行,问题与我使用的计算机有关。

如标题所示,在我的代码中,一张图片工作得很好,但另一张图片显示不正确。

我觉得我忽略了一些非常明显的东西,无论如何,这是我遇到问题的代码段。

from Tkinter import *
from StringIO import StringIO
from PIL import Image,ImageTk
from urllib import urlopen


url1 = 'https://lh3.googleusercontent.com/-bnh6_0GlqbA/VUKUsl1Pp9I/AAAAAAACGoM/Vx9yu1QGIKQ/s650/Sunset.png'
url2 = 'https://lh3.googleusercontent.com/-_J57qf7Y9yI/VUPaEaMbp9I/AAAAAAACGuM/3f4551Kcd0I/s650/UpsideDawn.png'

window = Tk()

imagebytes = urlopen(url1).read()
imagedata = StringIO(imagebytes)
imagePIL = Image.open(imagedata)
imageready = ImageTk.PhotoImage(imagePIL)

imagelabel = Label(window, image = imageready)
imagelabel.image = imageready

imagelabel.pack()
window.mainloop()

如果您运行此代码,您会发现 url1 将显示空白 window,但 url2 将显示图像。

以下代码在 Python 3 中对我有用,显示任一图像都很好。

from tkinter import *
from PIL import Image,ImageTk
import urllib.request
import io

url1 = 'https://lh3.googleusercontent.com/-bnh6_0GlqbA/VUKUsl1Pp9I/AAAAAAACGoM/Vx9yu1QGIKQ/s650/Sunset.png'
url2 = 'https://lh3.googleusercontent.com/-_J57qf7Y9yI/VUPaEaMbp9I/AAAAAAACGuM/3f4551Kcd0I/s650/UpsideDawn.png'

window = Tk()

imagebytes = urllib.request.urlopen(url1).read()
imagedata = io.BytesIO(imagebytes)
imagePIL = Image.open(imagedata)
imageready = ImageTk.PhotoImage(imagePIL)

imagelabel = Label(window, image = imageready)
imagelabel.image = imageready

imagelabel.pack()
window.mainloop()

以下是我对上述 Python 2 版本的最佳猜测:

from Tkinter import *
from PIL import Image,ImageTk
from urllib import urlopen
import io # try this

url1 = 'https://lh3.googleusercontent.com/-bnh6_0GlqbA/VUKUsl1Pp9I/AAAAAAACGoM/Vx9yu1QGIKQ/s650/Sunset.png'
url2 = 'https://lh3.googleusercontent.com/-_J57qf7Y9yI/VUPaEaMbp9I/AAAAAAACGuM/3f4551Kcd0I/s650/UpsideDawn.png'

window = Tk()

imagebytes = urlopen(url1).read()
imagedata = io.BytesIO(imagebytes) # use bytesio instead of stringio
imagePIL = Image.open(imagedata)
imageready = ImageTk.PhotoImage(imagePIL)

imagelabel = Label(window, image = imageready)
imagelabel.image = imageready

imagelabel.pack()
window.mainloop()