我想做一个简单的应用程序,使用按钮通过不同的字符串与标签循环,但是如何从。py文件到KV字符串的字符串?
例如,我希望它在屏幕中间显示'[x_string]'。当用户按下按钮(箭头朝右)时,它会转到'[y_string]'。当用户按下另一个按钮(箭头朝左)时,它会返回'[x_string]',等等。
这是我到目前为止的代码。
from PyDictionary import PyDictionary
from kivy.metrics import dp
from kivy.properties import StringProperty
from kivymd.uix.list import OneLineIconListItem
from kivymd.uix.menu import MDDropdownMenu
from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivymd.uix.toolbar import MDToolbar
from kivy.core.window import Window
from kivymd.uix.dialog import MDDialog
from kivymd.uix.button import MDFlatButton
from kivymd.uix.swiper import MDSwiper
from kivymd.uix.label import MDLabel
from pathlib import Path
KV = '''
ScreenManager:
Screen1:
<Screen1>:
name: 'screen'
MDScreen:
name: 'screen'
MDToolbar:
title: 'Test App'
elevation: 20
pos_hint: {'top': 1}
md_bg_color: (1, 1, 1, 1)
specific_text_color: (76/255, 76/255, 77/255, 1)
right_action_items: [["information"],["home"]]
FloatLayout:
# Left Arrow
Button:
background_normal: 'buttonsNormal/chevron_arrow_left.png'
background_down: 'buttonsDown/chevron_arrow_left_down.png'
size_hint: (0.06, 0.16)
pos_hint: {'center_x': 0.06, 'center_y': 0.445}
border: [0, 0, 0, 0]
# Right Arrow
Button:
background_normal: 'buttonsNormal/chevron_arrow_right.png'
background_down: 'buttonsDown/chevron_arrow_right_down.png'
size_hint: (0.06, 0.16)
pos_hint: {'center_x': 0.94, 'center_y': 0.445}
border: [0, 0, 0, 0]
'''
Window.size = (1280, 720)
class Screen1(Screen):
def build(self):
MDLabel(
text = 'Raise your arm.',
font_size = dp(56),
halign = 'center'
)
class MainApp(MDApp):
dialog = None
def build(self):
sm = ScreenManager()
sm.add_widget(Screen1(name = 'follow_screen'))
return Builder.load_string(KV)
MainApp().run()
我省略了大约800行完全不相关的代码,所以这就是为什么有这么多导入的模块作为顶部。
谢谢!
可以添加Label
到Screen1
kv
:
Label:
text: root.text
size_hint: 0.25, 0.25
color: 0,0,0,1
size: self.texture_size
pos_hint: {'center_x': 0.5, 'center_y': 0.5}
这个Label
的text
被设置为root.text
,它应该是Screen1
类中的StringProperty
:
class Screen1(Screen):
text = StringProperty('x_string')
然后,你可以像这样调整StringProperty
的值:
# Left Arrow
Button:
background_normal: 'buttonsNormal/chevron_arrow_left.png'
background_down: 'buttonsDown/chevron_arrow_left_down.png'
size_hint: (0.06, 0.16)
pos_hint: {'center_x': 0.06, 'center_y': 0.445}
border: [0, 0, 0, 0]
on_press:
root.text = 'x_string'
# Right Arrow
Button:
background_normal: 'buttonsNormal/chevron_arrow_right.png'
background_down: 'buttonsDown/chevron_arrow_right_down.png'
size_hint: (0.06, 0.16)
pos_hint: {'center_x': 0.94, 'center_y': 0.445}
border: [0, 0, 0, 0]
on_press:
root.text = 'y_string'