gpt4 book ai didi

python - 使用 Tkinter 库显示图像 -- "too early to create image"

转载 作者:太空狗 更新时间:2023-10-30 01:09:08 26 4
gpt4 key购买 nike

这是我的代码,用于显示来自 URL 的图像:

def display_image(image_url):
# create image
image = Image.open(StringIO(urllib2.urlopen(image_url).read()))
image = ImageTk.PhotoImage(image)

# create display
root = tk.Tk()
root.title('captcha')
root.geometry("%dx%d+%d+%d" % (image.width(), image.height(), 0, 0))

# draw image
panel1 = tk.Label(root, image=image)
panel1.pack(side='top', fill='both', expand='yes')
panel1.image = image

# run display
root.mainloop()

我在我的控制台上得到以下输出:

Traceback (most recent call last):
File "vote.py", line 119, in <module>
display_image(recaptcha.get_image_url(challenge_field))
File "vote.py", line 89, in display_image
image = ImageTk.PhotoImage(image)
File "c:\Python27\lib\site-packages\PIL\ImageTk.py", line 113, in __init__
self.__photo = apply(Tkinter.PhotoImage, (), kw)
File "c:\Python27\lib\lib-tk\Tkinter.py", line 3244, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "c:\Python27\lib\lib-tk\Tkinter.py", line 3185, in __init__
raise RuntimeError, 'Too early to create image'
RuntimeError: Too early to create image
Exception AttributeError: "PhotoImage instance has no attribute '_PhotoImage__poto'" in <bound method PhotoImage.__del__ of <PIL.ImageTk.PhotoImage instance at 0x0000000002EB8148>> ignored

我做错了什么?任何帮助将不胜感激。

最佳答案

您在使用 ImageTk 之后创建了 Tk 实例。您应该始终首先创建根元素,然后再创建其余的小部件。

关于python - 使用 Tkinter 库显示图像 -- "too early to create image",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16257788/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com