Kivy управление несколькими экранами - PullRequest
0 голосов
/ 14 мая 2019

Я довольно новичок в Kivy (изучал его два дня назад). Я работал над базовым калькулятором, но натолкнулся на препятствие, которое я не смог перепрыгнуть.
Я хотел бы создать несколько экранов, потому что я намерен добавить больше в свой калькулятор, поскольку я продолжаю изучать Kivy, и я не знаю, как настроить ScreenManager в моем коде.

Это мой .py файл

import kivy

kivy.require('1.11.0')
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.pagelayout import PageLayout
from kivy.core.window import Window

Window.clearcolor = .3,.3,.3,1

class RootWidget(GridLayout):   
    def calculate(self, calculation):
        if calculation:
            try:
                self.display.text = str(eval(calculation))
            except Exception:
            self.display.text = "Error"
class kutuApp(App):
    def build(self):
        return RootWidget()
if __name__== '__main__':
    kutuApp().run()

А это мой .kv файл

<CustButton@Button>:
    font_size: 35
    background_color: 0,0,0,0
    canvas.before:
        Color:
            rgba: (.4, .4, .4, 1) if self.state=='normal' else (0,.7,.7,1)
        RoundedRectangle:
            pos: self.pos
            size: self.size
            radius: [20, ]

<RawLayout@BoxLayout>:
     spacing: 8
     padding: 8
      size_hint: [1, .2]

<RootWidget>:
       id: calculator
      rows: 10
       display: entry
       spacing: 1

BoxLayout:
    size_hint: [1, .1]
    Label:
        text: 'Basic Calculator'
    Label:
        text: 'Made by Xrew'

BoxLayout:
    padding: 10
    TextInput:
        id: entry
        spacing: 1
        padding: 5
        font_size: 32
        multiline: True
        focus: False
#       background_color: 0, 0, 0, 1
#       foreground_color: [1, 0, 1, 1]

RawLayout:
    CustButton:
        text: '<'
        on_press: entry.text += self.text
    CustButton:
        text: '>'
        on_press: entry.text += self.text
    CustButton:
        text: '≈'
        on_press: entry.text += '=='                

RawLayout:
    orientation: 'horizontal'
    CustButton:
        text: '('
        on_press: entry.text += '('
    CustButton: 
        text: ')'
        on_press: entry.text += ')'
    CustButton:
        text: '√'
        on_press: entry.text += '**(.5)'
    CustButton:
        text: '¹/x' 
        on_press: entry.text += '1/'
RawLayout:
    orientation: 'horizontal'
    CustButton:
        text: 'Del'
        on_press: entry.text = entry.text[:-1]
    CustButton:
        text: 'x²'
        on_press: entry.text += '**2'
    CustButton:
        text: 'xⁿ'
        on_press: entry.text += '**'
    CustButton:
        text: 'π'
        on_press: entry.text += '3.14'

RawLayout:
    orientation: 'horizontal'       
    cols: 4    
    CustButton:
        text: 'Clr'
        font_color: [255,0,0,1]
 #       background_normal: ' '
    #    background_color: 1, .3, .4, .85
        on_press: entry.text = ""
    CustButton:
        text: '+'
        on_press: entry.text += self.text
        font_size: 32
    CustButton:
        text: '÷'
        on_press: entry.text += '/'
    CustButton:
        text: '×'
        on_press: entry.text += '*'

RawLayout:
    rows: 1   
    orientation: 'horizontal'
    CustButton:
        text: '7'
        on_press: entry.text += self.text
    CustButton:
        text: '8'
        on_press: entry.text += self.text
    CustButton:
        text: '9'
        on_press: entry.text += self.text
    CustButton:
        text: '-'
        on_press: entry.text += self.text

RawLayout:
    orientation: 'horizontal'
    rows: 1
    CustButton:
        text: '4'
        on_press: entry.text += self.text
    CustButton:
        text: '5'
        on_press: entry.text += self.text
    CustButton:
        text: '6'
        on_press: entry.text += self.text
    CustButton:
        text: '+'
        on_press: entry.text += self.text   

RawLayout:
    orientation: 'horizontal'
    cols: 3
    CustButton:
        text: '1'
        size_hint: [.5, 1]
        on_press: entry.text += self.text
    CustButton:
        text: '2'
        size_hint: [.5, 1]
        on_press: entry.text += self.text
    CustButton:
        text: '3'
        size_hint: [.5, 1]
        on_press: entry.text += self.text
    CustButton:
        text: ' '
        size_hint: [.5, 1]
        background_normal: ' '
        background_color: 0, 0, 0, 0

RawLayout:
    orientation: 'horizontal'
    size_hint: [1, .2]
    CustButton:
        text: '0'
        on_press: entry.text += self.text
        size_hint: [.34, 1]
    CustButton:
        text: '.'
        on_press: entry.text += self.text
        size_hint: [.17, 1]
        font_size: 32
    CustButton:
        text: '='
        on_press: calculator.calculate(entry.text)
        size_hint: [.17, 2.4]
#       background_normal: ' '
    #   background_color:  0, .5, 95, 1

1 Ответ

0 голосов
/ 14 мая 2019

Kivy ScreenManager

Следующие шаги иллюстрируют, как расширить приложение Kivy с помощью ScreenManager , Screen и Button виджетов и одного из событий Button ( on_release, on_press).

Py File

  1. Добавить оператор импорта, from kivy.uix.screenmanager import ScreenManager, Screen
  2. Объявление класса с наследованием ScreenManager, например class ScreenManagement(ScreenManager):
  3. Объявить два класса с наследованием Screen, например class MenuScreen(Screen): и class CalculatorScreen(Screen):
  4. Добавьте pass в качестве тела трех новых классов, потому что мы собираемся использовать язык kv для разработки их представлений / представлений.
  5. Замените return RootWidget() на return ScreenManagement(), потому что теперь корнем приложения является Kivy ScreenManager
  6. Переименовать class RootWidget в class Calculator

Snippets - py

from kivy.uix.screenmanager import ScreenManager, Screen

...

class Calculator(GridLayout):
    ...    


class MenuScreen(Screen):
    pass


class CalculatorScreen(Screen):
    pass


class ScreenManagement(ScreenManager):
    pass


class kutuApp(App):
    def build(self):
        return ScreenManagement()

Файл kv

  1. Объявить правила класса , <MenuScreen>:, <CalculatorScreen>: <ScreenManagement>:, что соответствует class MenuScreen(Screen):, class CalculatorScreen(Screen): и class ScreenManagement(ScreenManager): соответственно в скрипте Python
  2. Переименовать RootWidget в Calculator
  3. Instantiate Calculator: как потомок класса, <CalculatorScreen>:
  4. Создайте экземпляры MenuScreen: и CalculatorScreen: как дети класса, <ScreenManagement>:
  5. Дайте имя MenuScreen: и CalculatorScreen: как name: 'menu' и name: 'calculator' соответственно. Это позволит нам ссылаться на них при переключении экрана.

Отрывки - кв

<ScreenManagement>:
    MenuScreen:
        name: 'menu'
    CalculatorScreen:
        name: 'calculator'

<MenuScreen>:
    BoxLayout:
        Button:
            text: 'Goto Calculator'
            on_press: root.manager.current = 'calculator'
        Button:
            text: 'Quit'

<CalculatorScreen>:
    Calculator:

...
<Calculator>:
    id: calculator
* * Пример тысяча восемьдесят-одна * * тысяча восемьдесят-два

main.py

from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.core.window import Window
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen


Window.clearcolor = .3, .3, .3, 1


class Calculator(GridLayout):
    def calculate(self, calculation):
        if calculation:
            try:
                self.display.text = str(eval(calculation))
            except Exception:
                self.display.text = "Error"


class MenuScreen(Screen):
    pass


class CalculatorScreen(Screen):
    pass


class ScreenManagement(ScreenManager):
    pass


Builder.load_file("main.kv")


class kutuApp(App):
    def build(self):
        return ScreenManagement()


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

main.kv

<ScreenManagement>:
    MenuScreen:
        name: 'menu'
    CalculatorScreen:
        name: 'calculator'

<MenuScreen>:
    BoxLayout:
        Button:
            text: 'Goto Calculator'
            on_press: root.manager.current = 'calculator'
        Button:
            text: 'Quit'

<CalculatorScreen>:
    Calculator:

<CustButton@Button>:
    font_size: 35
    background_color: 0,0,0,0
    canvas.before:
        Color:
            rgba: (.4, .4, .4, 1) if self.state=='normal' else (0,.7,.7,1)
        RoundedRectangle:
            pos: self.pos
            size: self.size
            radius: [20, ]

<RawLayout@BoxLayout>:
    spacing: 8
    padding: 8
    size_hint: [1, .2]

<Calculator>:
    id: calculator
    rows: 10
    display: entry
    spacing: 1

    BoxLayout:
        size_hint: [1, .1]
        Label:
            text: 'Basic Calculator'
        Label:
            text: 'Made by Xrew'

    BoxLayout:
        padding: 10
        TextInput:
            id: entry
            spacing: 1
            padding: 5
            font_size: 32
            multiline: True
            focus: False
    #       background_color: 0, 0, 0, 1
    #       foreground_color: [1, 0, 1, 1]

    RawLayout:
        CustButton:
            text: '<'
            on_press: entry.text += self.text
        CustButton:
            text: '>'
            on_press: entry.text += self.text
        CustButton:
            text: '≈'
            on_press: entry.text += '=='

    RawLayout:
        orientation: 'horizontal'
        CustButton:
            text: '('
            on_press: entry.text += '('
        CustButton:
            text: ')'
            on_press: entry.text += ')'
        CustButton:
            text: '√'
            on_press: entry.text += '**(.5)'
        CustButton:
            text: '¹/x'
            on_press: entry.text += '1/'
    RawLayout:
        orientation: 'horizontal'
        CustButton:
            text: 'Del'
            on_press: entry.text = entry.text[:-1]
        CustButton:
            text: 'x²'
            on_press: entry.text += '**2'
        CustButton:
            text: 'xⁿ'
            on_press: entry.text += '**'
        CustButton:
            text: 'π'
            on_press: entry.text += '3.14'

    RawLayout:
        orientation: 'horizontal'
        cols: 4
        CustButton:
            text: 'Clr'
            font_color: [255,0,0,1]
     #       background_normal: ' '
        #    background_color: 1, .3, .4, .85
            on_press: entry.text = ""
        CustButton:
            text: '+'
            on_press: entry.text += self.text
            font_size: 32
        CustButton:
            text: '÷'
            on_press: entry.text += '/'
        CustButton:
            text: '×'
            on_press: entry.text += '*'

    RawLayout:
        rows: 1
        orientation: 'horizontal'
        CustButton:
            text: '7'
            on_press: entry.text += self.text
        CustButton:
            text: '8'
            on_press: entry.text += self.text
        CustButton:
            text: '9'
            on_press: entry.text += self.text
        CustButton:
            text: '-'
            on_press: entry.text += self.text

    RawLayout:
        orientation: 'horizontal'
        rows: 1
        CustButton:
            text: '4'
            on_press: entry.text += self.text
        CustButton:
            text: '5'
            on_press: entry.text += self.text
        CustButton:
            text: '6'
            on_press: entry.text += self.text
        CustButton:
            text: '+'
            on_press: entry.text += self.text

    RawLayout:
        orientation: 'horizontal'
        cols: 3
        CustButton:
            text: '1'
            size_hint: [.5, 1]
            on_press: entry.text += self.text
        CustButton:
            text: '2'
            size_hint: [.5, 1]
            on_press: entry.text += self.text
        CustButton:
            text: '3'
            size_hint: [.5, 1]
            on_press: entry.text += self.text
        CustButton:
            text: ' '
            size_hint: [.5, 1]
            background_normal: ' '
            background_color: 0, 0, 0, 0

    RawLayout:
        orientation: 'horizontal'
        size_hint: [1, .2]
        CustButton:
            text: '0'
            on_press: entry.text += self.text
            size_hint: [.34, 1]
        CustButton:
            text: '.'
            on_press: entry.text += self.text
            size_hint: [.17, 1]
            font_size: 32
        CustButton:
            text: '='
            on_press: calculator.calculate(entry.text)
            size_hint: [.17, 2.4]
    #       background_normal: ' '
        #   background_color:  0, .5, 95, 1

выход

MenuScreen CalculatorScreen

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