[英]Apps in Kivy: get values in kv file
我是使用Kivy編程的新手,我正在嘗試開發一個程序來收集房間中的人數。
我的困難是在KV文件和主文件之間傳遞值。 我需要獲取KV文件中滑塊的值,並在main.py程序中使用它
怎么可能 我已經嘗試過在網站上針對不同主題發布的幾種方法,但是沒有。 也許是因為因為我對該領域一無所知,所以不知道正確地應用它。
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import NumericProperty, ObjectProperty
from kivy.lang import Builder
class ThemeBackground(Screen):
pass
class myApp(App):
def build(self):
root = ScreenManager()
root.add_widget(ThemeBackground(name='Screen'))
return root
if __name__ == '__main__':
myApp().run()
和KV文件
#:import random random.random
<ThemeBackground>:
orientation: 'vertical'
canvas:
Color:
rgb: 1, 1, 1
Rectangle:
source: 'data/images/background.jpg'
size: self.size
BoxLayout:
padding: 10
spacing: 10
size_hint: 1, None
pos_hint: {'top': 1}
height: 44
Image:
size_hint: None, None
size: 24, 24
source: 'data/logo/kivy-icon-24.png'
Label:
height: 24
text_size: self.size
color: (1, 1, 1, .8)
text: 'Kivy 1.9.0.'
valign: 'middle'
GridLayout:
cols: 2
Label:
text: 'Please enter \nthe number of occupants?'
bold: True
font_name: 'data/fonts/DejaVuSans.ttf'
font_size: 22
halign: 'center'
Slider:
id: slider
min: 0.0
max: 15.0
value: 1.0
step: 1.0
orientation: "horizontal"
width: "38dp"
Label
text: ''
Label
text: '{}'.format(slider.value)
halign: 'center'
valign: 'top'
bold: True
text_size: self.size
font_size: 18
Button:
text: 'Enter'
size_hint_y: None
height: '50sp'}
您應該在myApp
的build
中加載kv
文件:
class myApp(App):
def build(self):
self.load_kv("main.kv")
return ThemeBackground()
您無需在kv
文件底部的最后一個字符}
kv
其刪除。
height: '50sp'}
預習:
為了訪問滑塊的值,請將變量myslider
添加到python和kv文件中,如下所示:
千伏特 :
<ThemeBackground>:
orientation: 'vertical'
myslider: slider
蟒蛇 :
class ThemeBackground(Screen):
myslider = ObjectProperty(None)
現在,您可以通過以下方式訪問值,最小值或最大值:
class myApp(App):
def build(self):
self.load_kv("kivy.3.kv")
tb = ThemeBackground()
print "value =",tb.myslider.value # <---- value here
print "min =",tb.myslider.min # <--- min here
return tb
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.