从网址获取图片时出错

时间:2016-02-21 01:46:24

标签: python kivy

我正试图在kivy的Image小部件中显示来自url(存储在列表中)的图像,这是我的功能:

class ImageScreen(Screen):

    image_source = ObjectProperty()

    def get_image(self):
        filename = 'imagelist.txt'
        txt = open(filename, 'r')

        with txt as file:
            images = [line.rstrip('\n') for line in txt]

        n = random.randint(0, len(images))

        self.image_source.source = str(images[n])

这是我在.kv中的小部件:

<ImageScreen>:
    image_source: imagesource
    on_enter: root.get_image()
    Image:
        id: imagesource
        source: 'preload.jpg'

当我调用该函数时,我收到此错误:

[ERROR] [Image] Error reading file http://www.webcomics.it/scottecscomics/files/2015/09/342-Gelado.jpg

我尝试使用AsyncImage小部件而不是Image:

    AsyncImage:
        id: imagesource
        source: 'preload.jpg'

但是我收到了这个错误:

Exception: Unknown <jpe> type, no loader found.
an integer is required

我可以在浏览器中打开图像,从错误中复制网址,如果在本地加载,可以显示它...我做错了什么?

编辑:我尝试加载在互联网上找到的许多图像文件,问题在于.jpg文件,与.png文件一起正常工作......但我没有问题显示本地保存的.jpg文件...我真的有不知道如何解决这个问题......

1 个答案:

答案 0 :(得分:0)

以下代码适用于kivy 1.8.0和1.9.1

import kivy
import datetime

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.factory import Factory
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.scatter import Scatter
import random
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.properties import *



Builder.load_string("""
<ImageScreen>:
    image_source: imagesource
    on_enter: root.get_image()
    AsyncImage:
        id: imagesource
        source: 'preload.jpg'
""")

images = []
class ImageScreen(Screen):

    image_source = ObjectProperty()

    def get_image(self):
        filename = 'imagelist.txt'

        with  open(filename, 'r') as filetxt:
            images = [line.rstrip('\n') for line in filetxt]
        print images
        img = random.choice(images)

        self.image_source.source = img


sm = ScreenManager()
sm.add_widget(ImageScreen(name='img'))
class MyApp(App):


    def build(self):
        return sm


if __name__ == '__main__':
    MyApp().run()

imagelist.txt:

http://www.webcomics.it/scottecscomics/files/2015/09/342-Gelado.jpg