簡體   English   中英

使用Tkinter庫顯示圖像-“太早創建圖像”

[英]Displaying an image with the Tkinter library — “too early to create image”

這是我的代碼,用於顯示來自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實例。 您應該始終先創建根元素,然后再創建其余的小部件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM