본문 바로가기

Programming/Python_Etc

파이썬 kivy 시작하기 2 - kv 파일 분리

반응형

1. main.py

from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty

class MyGridLayout(Widget):
    name = ObjectProperty(None) # 변수에 아무것도 할당하지 않도록 함
    pizza = ObjectProperty(None)
    color = ObjectProperty(None)

    def press(self):
        name = self.name.text
        pizza = self.pizza.text
        color = self.color.text

        #self.add_widget(Label(text=f'Hello {name} pizza {pizza} color {color}'))
        print(f'Hello {name} pizza {pizza} color {color}')
        self.name.text = ""
        self.pizza.text = ""
        self.color.text = ""

class MyApp(App):
    def build(self):
        return MyGridLayout()

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

 

2. my.kv

<MyGridLayout>

    name:name
    pizza:pizza
    color: color

    GridLayout:
        cols:1
        size: root.width, root.height
        GridLayout:
            cols:2

            Label:
                text: "Name"
            TextInput:
                id:name
                multiline:False
            Label:
                text: "Favorite Pizza"
            TextInput:
                id:pizza
                multiline:False
            Label:
                text: "Favorite Color"
            TextInput:
                id:color
                multiline:False

        Button:
            text: "Submit"
            font_size: 32
            on_press: root.press()

 

<결과>

반응형