howto:main.py,新类带有kivy carousel的代码,kv文件

时间:2019-03-27 15:14:53

标签: python kivy kivy-language

我正在调整kivy的橱窗。主要是kv文件,它们通过screenmanager定义了单独的屏幕。

我的目标是创建一个屏幕(DiashowApp),该屏幕将启动kivy应用轮播(https://kivy.org/doc/stable/api-kivy.uix.carousel.html)。因此,我设置了两个类,分别加载轮播和显示图像,这些类在kv文件(diashowapp.kv)中定义。

请给我帮助,以使代码运行。

问候 斯蒂芬

不要让这些类运行,带有print-Statements的调试例程会告诉我,这两个新类的代码都没有执行。

from time import time
from kivy.app import App
from os.path import dirname, join
from kivy.lang import Builder
from kivy.properties import NumericProperty, StringProperty, BooleanProperty,\
    ListProperty
from kivy.clock import Clock
from kivy.animation import Animation
from kivy.uix.screenmanager import Screen
from kivy.uix.carousel import Carousel
from kivy.uix.image import AsyncImage

from subprocess import call
import subprocess
from kivy.logger import Logger
import random

Logger.info('title: This is a info message.')
Logger.debug('title: This is a debug message.')

skript_axis_all = "data/screens_axis.sh"
skript_kill_axis = "data/screens_kill_axis.sh"
skript_axis_01 = "data/screens_axis01.sh"
skript_axis_02 = "data/screens_axis02.sh"
skript_axis_03 = "data/screens_axis03.sh"
skript_axis_04 = "data/screens_axis04.sh"

class CarouselApp(Carousel):
    def __init__(self, **kwargs):
        super(CarouselApp, self).__init__(**kwargs)
        self.direction = "right"
        bilderliste = []
        cmd2 = ['find', '/home/pi/Bilder/', '-maxdepth', '2', '-type', 'f', '-name', '*.JPG']
        proc2 = subprocess.Popen(cmd2, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        o2, e2 = proc2.communicate()
        #print('Output: ' + o2.decode('utf-8'))
        #print('Error: '  + e2.decode('utf-8'))
        #print('code: ' + str(proc2.returncode))
        o2_zeilen = o2.split('\n')
        counter = 0
        for zeile2 in o2_zeilen:
            bilderliste.append(zeile2.replace('\n',''))
        random.shuffle(bilderliste, random.random)
        for bildpfad in bilderliste:
            if counter < 50:
                counter = counter + 1
                print(counter)
                src = "%s" % bildpfad
                print type(bildpfad)
                if bildpfad is not None:
                    print('Bildpfad ist: %s') % src
                    image = AsyncImage(source = src, keep_ratio = True, allow_stretch = True)
                    try:
                        self.add_widget(image)
                    except Exception:
                        Logger.exception('Something happened in the add.widget!')
                else:
                    pass
        self.loop = True
        Clock.schedule_interval(self.load_next, 5)
        #print(self.slides)

class ShowcaseScreen(Screen):
    fullscreen = BooleanProperty(False)

    def add_widget(self, *args):
        if 'content' in self.ids:
            return self.ids.content.add_widget(*args)
        return super(ShowcaseScreen, self).add_widget(*args)

class ShowcaseApp(App):

    index = NumericProperty(-1)
    current_title = StringProperty()
    time = NumericProperty(0)
    show_sourcecode = BooleanProperty(False)
    sourcecode = StringProperty()
    screen_names = ListProperty([])
    hierarchy = ListProperty([])

    def build(self):
        self.title = 'hello world'
        Clock.schedule_interval(self._update_clock, 1 / 60.)
        self.screens = {}
        self.available_screens = sorted([
            'CarouselApp', 'Carousel', 'Scatter', 'Cameras'])
        self.screen_names = self.available_screens
        curdir = dirname(__file__)
        self.available_screens = [join(curdir, 'data', 'screens',
            '{}.kv'.format(fn).lower()) for fn in self.available_screens]
        self.go_next_screen()

carouselapp.kv

ShowcaseScreen:
    name: 'CarouselApp'
    fullscreen: True

    CarouselApp:

预期: diashow,会自动旋转。

实际: 图片显示正确,手动滑动操作正常。

2 个答案:

答案 0 :(得分:0)

欢迎来到SO:)

我不会修复您的代码。但是,如果您以该示例为例,则再次链接到kivy carousel
如果您需要自动轮播,则可以使用kivy的Clock来安排轮播轮播之间的2秒间隔。
尝试以下操作:(编辑:在kv屏幕中实现)

from kivy.app import App
from kivy.uix.carousel import Carousel
from kivy.uix.image import AsyncImage

from kivy.clock import Clock
from kivy.lang import Builder

class MyCarousel(Carousel):

    def __init__(self, **kwargs):
        super(MyCarousel, self).__init__(**kwargs)
        self.direction = "right"
        for i in range(10):
            src = "http://placehold.it/480x270.png&text=slide-%d&.png" % i
            image = AsyncImage(source=src, allow_stretch=True)
            self.add_widget(image)

        self.loop = True
        Clock.schedule_interval(self.load_next,2)

KV = """

ScreenManager:
    Screen:
        name: "scr1"
        BoxLayout:
            Button:
                text: "Carousel"
                on_release: root.current = "scr2"
    Screen:
        name: "scr2"
        BoxLayout:
            Button:
                text: "Back"
                on_release: root.current = "scr1"
            MyCarousel:

"""

class CarouselApp(App):
    def build(self):
        return Builder.load_string(KV)


CarouselApp().run()

答案 1 :(得分:0)

@ el3ien 预先感谢您。您是个好人,这使我走上了理解的道路。 :-) 在进一步集成到sreenmanager中之前,我会尝试调整您提供给我的代码。

在这里我遇到了一个问题,到目前为止我还无法调试。我实现了带有文件路径的列表的创建。我会遍历该列表,但无法加载该文件。是否存在限制,即asyncimage源必须位于main.py存在的目录中?

致谢! 斯蒂芬

from kivy.app import App
from kivy.uix.carousel import Carousel
from kivy.uix.image import AsyncImage

from kivy.clock import Clock
from subprocess import call
import subprocess


class CarouselApp(App):
    def build(self):
        carousel = Carousel(direction='right')
        bilderdirliste = []
        bilderliste = []
        cmd2 = ['find', '/photo/imac-Backup/', '-maxdepth', '2', '-type', 'f', '-name', '*.JPG']
        proc2 = subprocess.Popen(cmd2, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        o2, e2 = proc2.communicate()
        print('Output: ' + o2.decode('utf-8'))
        print('Error: '  + e2.decode('utf-8'))
        print('code: ' + str(proc2.returncode))
        o2_zeilen = o2.split('\n')
        counter = 0
        for zeile2 in o2_zeilen:
            bilderliste.append(zeile2.replace('\n','').replace(' ','\ '))
        for bildpfad in bilderliste:
            if counter < 10:
                counter = counter + 1
                print(counter)
                src = "%s" % bildpfad
                print('Bildpfad ist: %s') % src
                image = AsyncImage(source = src, keep_ratio=True)
                carousel.add_widget(image)
        carousel.loop = True
        Clock.schedule_interval(carousel.load_next, 3)
        print(carousel.index)
        return carousel

CarouselApp().run()

控制台输出为:

...
/photo/imac-Backup/4. März 2014/IMG_1704.JPG
/photo/imac-Backup/29. März 2012/IMG_0100.JPG
/photo/imac-Backup/25. September 2014/IMG_3018.JPG
/photo/imac-Backup/25. September 2014/IMG_3017.JPG
/photo/imac-Backup/25. September 2014/IMG_3015.JPG
/photo/imac-Backup/25. September 2014/IMG_3016.JPG
/photo/imac-Backup/25. September 2014/IMG_3019.JPG
/photo/imac-Backup/18. Mai 2015/IMG_3966.JPG
/photo/imac-Backup/18. Mai 2015/IMG_3965.JPG
/photo/imac-Backup/7. Mai 2013/IMG_0843.JPG
/photo/imac-Backup/1. Oktober 2016/IMG_6076.JPG
/photo/imac-Backup/1. Oktober 2016/IMG_6077.JPG

Error:
code: 0
1
Bildpfad ist: /photo/imac-Backup/13.\ Juni\ 2014/IMG_2484.JPG
[INFO   ] [Loader      ] using a thread pool of 2 workers
2
Bildpfad ist: /photo/imac-Backup/13.\ Juni\ 2014/IMG_2483.JPG
3
Bildpfad ist: /photo/imac-Backup/9.\ August\ 2015/IMG_4254.JPG
4
Bildpfad ist: /photo/imac-Backup/8.\ Dezember\ 2016/IMG_6187.JPG
5
Bildpfad ist: /photo/imac-Backup/3.\ Januar\ 2013/IMG_0643.JPG
0
Unable to connect to X server
[INFO   ] [ProbeSysfs  ] device match: /dev/input/event1
[INFO   ] [MTD         ] Read event from </dev/input/event1>
[INFO   ] [ProbeSysfs  ] device match: /dev/input/event0
[INFO   ] [MTD         ] Read event from </dev/input/event0>
[INFO   ] [ProbeSysfs  ] device match: /dev/input/event1
[INFO   ] [HIDInput    ] Read event from </dev/input/event1>
[INFO   ] [ProbeSysfs  ] device match: /dev/input/event0
[INFO   ] [HIDInput    ] Read event from </dev/input/event0>
[INFO   ] [Base        ] Start application main loop
[INFO   ] [MTD         ] </dev/input/event1> range position X is 0 - 4095
[INFO   ] [MTD         ] </dev/input/event0> range position X is 0 - 0
[INFO   ] [MTD         ] </dev/input/event1> range position Y is 0 - 4095
[INFO   ] [HIDMotionEvent] using <USBest Technology SiS HID Touch Controller>
[INFO   ] [MTD         ] </dev/input/event0> range position Y is 0 - 0
[INFO   ] [MTD         ] </dev/input/event1> range touch major is 0 - 0
[INFO   ] [HIDMotionEvent] <USBest Technology SiS HID Touch Controller> range ABS X position is 0 - 4095
[INFO   ] [MTD         ] </dev/input/event0> range touch major is 0 - 0
[INFO   ] [MTD         ] </dev/input/event1> range touch minor is 0 - 0
[INFO   ] [MTD         ] </dev/input/event0> range touch minor is 0 - 0
[INFO   ] [HIDMotionEvent] <USBest Technology SiS HID Touch Controller> range ABS Y position is 0 - 4095
[INFO   ] [HIDMotionEvent] using <PC Camera: PC Camera>
[INFO   ] [MTD         ] </dev/input/event1> range pressure is 0 - 255
[INFO   ] [MTD         ] </dev/input/event0> range pressure is 0 - 255
[INFO   ] [HIDMotionEvent] <USBest Technology SiS HID Touch Controller> range position X is 0 - 4095
[INFO   ] [MTD         ] </dev/input/event1> axes invertion: X is 0, Y is 0
[INFO   ] [MTD         ] </dev/input/event0> axes invertion: X is 0, Y is 0
[INFO   ] [HIDMotionEvent] <USBest Technology SiS HID Touch Controller> range position Y is 0 - 4095
[INFO   ] [MTD         ] </dev/input/event1> rotation set to 0
[INFO   ] [MTD         ] </dev/input/event0> rotation set to 0

显示的是一个黑色屏幕,带有运动图标(左侧的圆圈),如进度条。