简体   繁体   中英

howto: main.py, new class with code for kivy carousel, kv file

I am adapting the showcase-Dashboard of kivy. Mainly there are kv-files, that define a separate screen via screenmanager.

My target is to create a screen (DiashowApp), that starts the kivy app carousel ( https://kivy.org/doc/stable/api-kivy.uix.carousel.html ). Therfore I set up two classes, that load carousel and display the images, which are defined in the kv file (diashowapp.kv).

Please, give me help in getting the code running.

Regards Stefan

Do not get the classes run, debug routines with print-Statements show me, that no code of the two new classes is executed.

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:

Expected: A diashow, that is rotating automatically.

Actual: The pictures are displayed correctly, the manual swiping does work correctly.

Wellcome to SO :)

I am not going to fix your code. But if you take the example you linket to: kivy carousel again.
If you want an automated carousel, then you can use kivy's Clock to schedule a interval of 2 seconds between rolling the carousel.
Try this: (edit: implemented in screens in 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()

@el3ien Thanks to you in advance. you are a nice guy, bringing me on the road of understanding. :-) Before I get further with integrating in sreenmanager, I try to adapt the code you have given me.

Here I ran into a problem, that I cannot debug so far. I implemented a creation of a list with file path. that list I iterate through, but that files cannot be loaded. Is there a limitation, that the asyncimage source has to be in the directory, the main.py exist?

Regards! Stefan

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()

The console output is:

...
/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

shown is a black screen with a motion icon (left wise circling points), like a progress bar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM