Kivy + Python + Raspberry - Как реализовать обратный отсчет - PullRequest
0 голосов
/ 13 мая 2018

Я довольно новичок в программировании на Python, и в настоящее время я создаю фотобудку с использованием Kivy и Python.

В целом это работает (я могу нажать кнопку, и он запускает функцию, чтобы сделать 3 снимка и обновляет миниатюру на экране), но я не могу изменить текст метки (actionLabel), чтобы показать обратный отсчет до запуска функции takePhotos.

import os, time, Image, sys, datetime, subprocess,glob


import kivy
kivy.require('1.10.0') # replace with your current kivy version !

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.image import Image as kivyImage
from kivy.clock import Clock
from kivy.graphics import Color, Rectangle

import RPi.GPIO as GPIO 

#GPIO varialbes
#buttonPin = 23
GPIO.setmode(GPIO.BCM)
GPIO.setup(23,GPIO.IN)
GPIO_status = False

# Some variables
photoTitle = "My first Photobox!"
total_photos = 3 #Number of photos to be takes

#Function for photo taking
def takePhotos():

    #Take first picture - Folder for inbound pictures /home/pi/PB_Inbox/photobooth%H%M%S.jpg
    time.sleep(3)
    subprocess.call("gphoto2 --capture-image-and-download --filename /home/pi/PB_Inbox/photobooth%H%M%S.jpg", shell=True)
        #Take all other picture
        for x in range (0,total_photos-1):
            subprocess.call("gphoto2 --capture-image-and-download --filename /home/pi/PB_Inbox/photobooth%H%M%S.jpg", shell=True)
    #Process pictures
    subprocess.call("sudo sh /home/pi/Documents/Photo_Booth/Image_prep_3", shell=True)
    print('done')


class MyApp(App):
    # Display the latest thumbnail
    photo = kivyImage(source="/home/pi/PB_Thumb/Thumb.png")
    actionLabel = Label(text="Push the button", size_hint=(1, 0.2),color=[1,0,0,1],font_size='40sp')

    def build(self):
            # Set up the layout
            photobox = GridLayout(rows=3, spacing=10, padding=10)

            # Create the UI objects (and bind them to callbacks, if necessary)
            headerLabel = Label(text="The Greatest Photobox", size_hint=(1, 0.1),font_size='40sp') # Button: 20% width, 100% height

            # Add the UI elements to the layout
            photobox.add_widget(headerLabel)
            photobox.add_widget(self.photo)
            photobox.add_widget(self.actionLabel)

            # Periodically refresh the displayed photo using the callback function
            Clock.schedule_interval(self.callback, 0.3)

            return photobox      

    # Callback for thumbnail refresh and listening to GPIO for input
    def callback(self, instance):
        self.photo.reload()
        if self.readSensor() == False:
            pass
            #print('waiting')
        else:
            #provided as an argument
            takePhotos()

    #Read status of the sensor and return True if Buzzer has been pushed
    def readSensor(self):
        sensor = GPIO.input(23)
        if sensor == 1:
            return True
        else:
            return False

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

Может кто-нибудь показать мне, как это сделать?

Thx

1 Ответ

0 голосов
/ 13 мая 2018
  1. Используйте Clock.create_trigger для запуска обратного отсчета.
  2. Удалить функцию time.sleep (3), takePhotos ().
  3. Используйте Clock.schedule_once для вызова функции takePhotos (), т.е. Clock.schedule_once(takePhotos, 3)
  4. Разделите приложение Kivy на скрипт Python и файл kv.

Руководство по программированию »События и свойства

В приложениях Kivy вы должны избегать длинных / бесконечных циклов или сна.

Пример * * тысяча двадцать-одна main.py import os, time, sys, datetime, subprocess, glob from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.clock import Clock from kivy.properties import ObjectProperty, NumericProperty import RPi.GPIO as GPIO # GPIO variables # buttonPin = 23 GPIO.setmode(GPIO.BCM) GPIO.setup(23, GPIO.IN) GPIO_status = False # Some variables total_photos = 3 # Number of photos to be takes # Function for photo taking def takePhotos(dt): # Take 3 picture for x in range(total_photos): subprocess.call("gphoto2 --capture-image-and-download --filename /home/pi/PB_Inbox/photobooth%H%M%S.jpg", shell=True) # Process pictures subprocess.call("sudo sh /home/pi/Documents/Photo_Booth/Image_prep_3", shell=True) print('done') class PhotoBox(BoxLayout): photo = ObjectProperty(None) action_button = ObjectProperty(None) count_down_trigger = ObjectProperty(None) count = NumericProperty(3) def __init__(self, **kwargs): super(PhotoBox, self).__init__(**kwargs) # Display the latest thumbnail self.photo.source = "/home/pi/PB_Thumb/Thumb.png" self.count_down_trigger = Clock.create_trigger(self.count_down, 1) def on_press_camera_button(self): self.count = 3 self.count_down_trigger() def count_down(self, dt): self.action_button.text = str(self.count) self.count -= 1 if self.count >= 0: self.count_down_trigger() else: self.action_button.text = "Say Cheese!" # Periodically refresh the displayed photo using the callback function # Clock.schedule_interval(self.callback, 0.3) # infinite loop Clock.schedule_once(self.callback, 0.3) self.action_button.text = "Push the button" # reset text # Callback for thumbnail refresh and listening to GPIO for input def callback(self, dt): self.photo.reload() if self.readSensor(): # provided as an argument Clock.schedule_once(takePhotos, 3) # call takePhotos method once after 3 seconds else: pass #print('waiting') # Read status of the sensor and return True if Buzzer has been pushed def readSensor(self): sensor = True # GPIO.input(23) if sensor == 1: return True else: return False class MyApp(App): title = "My first Photobox!" def build(self): return PhotoBox() if __name__ == '__main__': MyApp().run() my.kv #:kivy 1.10.0 <PhotoBox>: photo: photo action_button: action_button orientation:'vertical' spacing: 10 padding: 10 Label: text: "The Greatest Photobox" size_hint: (1, 0.1) font_size: '40sp' AsyncImage: id: photo Button: id: action_button text: "Push the button" size_hint: (1, 0.2) color: [1,0,0,1] font_size: '40sp' on_press: root.on_press_camera_button() выход

Img01 - App Startup Img02 - Count down

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...