Как вы передаете переменные между 2 классами в kivy? - PullRequest
0 голосов
/ 25 февраля 2020

Я недавно начал использовать kivy для своего проекта. Я пытаюсь сделать простую цифровую доску меню кофе.

Я пытаюсь показать, что выбрал пользователь. В MenuScreen пользователю предоставляется меню, которое затем пользователь может выбрать. После выбора я бы хотел перейти на другой экран и отобразить «выбор», например: Espresso поверх изображения кофейной чашки. Я попал на этап, когда я могу вручную написать строковое значение для отображения. Но я не смог отобразить выбранное название кофе пользователем.

Я буквально застрял с этой проблемой в течение 2 дней подряд или около 17 часов интенсивного поиска в Google и чтения документации, но с моими ограниченными умозаключениями я не смог ее решить. Я посмотрел на связывание, передавая переменные между двумя классами, и т. Д. c. Любая помощь будет принята с благодарностью !!

короткая версия python код

    class MenuScreen(Screen):
        def __init__(self,  **kwargs):
                super(MenuScreen, self).__init__(**kwargs)
        def buttonEspresso(self):
            print ('Espresso Selected')
            global selectedDrink
            selectedDrink = self.coffeeName.text #<-------
            sm.current = 'settings'
    class SettingsScreen(Screen):
        coffeeName = ObjectProperty(None)
        def __init__(self,  **kwargs):
            super(SettingsScreen, self).__init__(**kwargs)
            self.ids.coffeeName.text = selectedDrink #<-------
        def backToMenu(self):
            print('going back to menu')
            sm.current = 'menu'     

короткая версия кивий код : coffeeName: coffeeName GridLayout : cols: 2

        GridLayout:
            cols:2
            Button:
                id: coffeeName
                text: 'Espresso'
                on_press: 
                    root.manager.transition = FadeTransition()
                    root.text = 'Espresso'
                    root.buttonEspresso()
<SettingsScreen>:
    coffeeName: coffeeName
    GridLayout:
        cols:2

        GridLayout:
            cols:1
            Button:
                text: 'Back to menu'
                size_hint: None, None
                size: 200, 50
                on_press: 
                    root.manager.transition  = SlideTransition(direction="left")
                    root.backToMenu()

            Label:
                id: coffeeName #<-------
                text: 'coffeeName'
                font_size: 70
                size_hint: None, None
                size: 960, 50
            AnchorLayout:
                anchor_x: 'center'
                anchor_y: 'center'
                Image:
                    source: 'cappuccino.png'
                    size_hint: None, None
                    size: 1000, 1000    

coffee menu screen Если я выберу «Эспрессо», то желаемым результатом будет отображение «Эспрессо» на красной границе. enter image description here Вышеуказанное изображение с myDesiredOutcome было сделано путем редактирования

self.ids.coffeeName.text = selectedDrink #<-------

для иллюстрации

PythonCode

import kivy
from kivy.app import App
from kivy.logger import Logger
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.video import Video
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.properties import StringProperty
from kivy.properties import ObjectProperty


import subprocess
import os
from omxplayer.player import OMXPlayer


class Player(Video):
    def __init__(self,  **kwargs):
        super(Player,  self).__init__(**kwargs)
        self.player = OMXPlayer('video.mp4','--loop')
        self.state='play'
        self.options={'eos': 'loop'}
        self.bind(on_touch_down = self.on_stop)

    def check(self):
        Logger.info("film position:" + str(self.position))

    def on_stop(self,  *args):
        print ('I have been clicked')
        #self.state='stop'  # stop the video
        self.player.quit()
        sm.current = 'menu'  # switch to the other Screen

class MenuScreen(Screen):


    #coffeeName = ObjectProperty(None)

    def __init__(self,  **kwargs):
        super(MenuScreen, self).__init__(**kwargs)
    def buttonEspresso(self):
        print ('Espresso Selected')
        global selectedDrink
        selectedDrink = self.coffeeName.text #<-------
        sm.current = 'settings'


    def buttonAmericano(self):
        print ('Americano Selected')
        sm.current = 'settings'
    def buttonCafeLatte(self):
        print ('Cafe Latte Selected')
        sm.current = 'settings'
    def buttonCappuccino(self):
        print ('Cappuccino Selected')
        sm.current = 'settings'
    def buttonCafeMocha(self):
        print ('Cafe Mocha Selected')
        sm.current = 'settings'
    def buttonMochaccino(self):
        print ('Mochaccino Selected')
        sm.current = 'settings'
class SettingsScreen(Screen):

    coffeeName = ObjectProperty(None)


    def __init__(self,  **kwargs):
        super(SettingsScreen, self).__init__(**kwargs)
        self.ids.coffeeName.text = selectedDrink #<-------

    def backToMenu(self):
        print('going back to menu')
        sm.current = 'menu'



Builder.load_file('screenManager.kv')

sm = ScreenManager()
screen1 = Screen(name='video')
screen1.add_widget(Player())
sm.add_widget(screen1)
sm.add_widget(MenuScreen(name='menu'))
sm.add_widget(SettingsScreen(name='settings'))


class VideoPlayerApp(App):
    def build(self):
        return sm

if __name__ == "__main__":
    video = VideoPlayerApp()
    try:
        video.run()
    except KeyboardInterrupt:
        video.stop()
        os.system('killall dbus-daemon')

Код Kivy

#:import FadeTransition kivy.uix.screenmanager.FadeTransition
#:import SlideTransition kivy.uix.screenmanager.SlideTransition
#:import GridLayout kivy.uix.gridlayout

<MenuScreen>:
    coffeeName: coffeeName
    GridLayout:
        cols:2

        GridLayout:
            cols:2
            Button:
                id: coffeeName
                text: 'Espresso'
                on_press: 
                    root.manager.transition = FadeTransition()
                    root.text = 'Espresso'
                    root.buttonEspresso()
            Button:
                text: 'Americano'
                on_press: 
                    root.manager.transition = FadeTransition()
                    root.buttonAmericano()
            Button:
                text: 'Cafe Latte'
                on_press: 
                    root.manager.transition = FadeTransition()      
                    root.buttonCafeLatte()
            Button:
                text: 'Cappuccino'
                on_press: 
                    root.manager.transition = FadeTransition()
                    root.buttonCappuccino()
            Button:
                text: 'Cafe Mocha'
                on_press: 
                    root.manager.transition = FadeTransition()
                    root.buttonCafeMocha()
            Button:
                text: 'Mochaccino'
                on_press: 
                    root.manager.transition = FadeTransition()
                    root.buttonMochaccino()


        GridLayout:
            cols:2
            Button:
                text: 'Hot Chocolate'
                on_press: 
                    root.manager.transition = FadeTransition()
                    root.manager.current = 'settings'
                    #fading transition for video
            Button:
                text: 'Creamy Chocolate'
                on_press: 
                    root.manager.transition = FadeTransition()
                    root.manager.current = 'settings'
                    #fading transition for video
            Button:
                text: 'Express Coffee'
                on_press: 
                    root.manager.transition = FadeTransition()
                    root.manager.current = 'settings'
                    #fading transition for video        
            Button:
                text: 'Green Tea'
                on_press: 
                    root.manager.transition = FadeTransition()
                    root.manager.current = 'settings'
                    #fading transition for video                
            Button:
                text: 'Milk Tea'
                on_press: 
                    root.manager.transition = FadeTransition()
                    root.manager.current = 'settings'
                    #fading transition for video        
            Button:
                text: 'Roibos Tea'
                on_press: 
                    root.manager.transition = FadeTransition()
                    root.manager.current = 'settings'
                    #fading transition for video

<SettingsScreen>:
    coffeeName: coffeeName
    GridLayout:
        cols:2

        GridLayout:
            cols:1
            Button:
                text: 'Back to menu'
                size_hint: None, None
                size: 200, 50
                on_press: 
                    root.manager.transition  = SlideTransition(direction="left")
                    root.backToMenu()

            Label:
                id: coffeeName #<-------
                text: 'coffeeName'
                font_size: 70
                size_hint: None, None
                size: 960, 50
            AnchorLayout:
                anchor_x: 'center'
                anchor_y: 'center'
                Image:
                    source: 'cappuccino.png'
                    size_hint: None, None
                    size: 1000, 1000
        GridLayout:
            cols:1

            Label:
                font_size: 70
                text: 'Select a Payment Option'
                size_hint: None, None
                size: 960, 200
            BoxLayout:
                size_hint: None, None
                size: 960, 50
                ToggleButton:
                    text: 'Cash'
                    font_size: 50
                    on_press: 

                        print('on_press')
                ToggleButton:
                    text: 'UniPay'
                    font_size: 50

                ToggleButton:
                    text: 'Bank Cards'
                    font_size: 50

            BoxLayout:      
                Button:
                    text: 'Back to menu'
                    on_press: 
                        root.manager.transition  = SlideTransition(direction="left")
                        root.manager.current = 'menu'
...