我正在与Kivy for python合作,我想知道是否有一种方法可以访问我在.kv文件中声明的一些变量,如下所示:
#:set global_background_color_A (0.4,0.4,0.4, 1)
#:set global_background_color_B (0.2,0.2,0.2, 1)
#:set global_background_color_C (0.6,0.6,0.6, 1)
#:set global_seperator_color_Blue (0.26,.545,.65,1)现在,如果我可以在我的python代码中动态地更改一些按钮的背景颜色,那就太好了。为此,我必须访问这些变量。
最简单的方法是什么?
先谢谢你,芬恩
发布于 2018-01-23 20:21:19
我使用了以下代码作为示例应用程序:
controller.kv
#:kivy 1.0
#:set global_background_color_A (0.4,0.4,0.4, 1)
#:set global_background_color_B (0.2,0.2,0.2, 1)
#:set global_background_color_C (0.6,0.6,0.6, 1)
#:set global_seperator_color_Blue (0.26,.545,.65,1)
<Controller>:
label_wid: my_custom_label
button_wid: my_custom_button
BoxLayout:
orientation: 'vertical'
padding: 20
Button:
id: my_custom_button
text: 'My controller info is: ' + root.info
on_press: root.do_action()
Label:
id: my_custom_label
text: 'My label before button press'__main__.py
import kivy
kivy.require('1.0.5')
from kivy.uix.floatlayout import FloatLayout
from kivy.app import App
from kivy.properties import ObjectProperty, StringProperty
from kivy.lang.parser import global_idmap # <--
class Controller(FloatLayout):
'''Create a controller that receives a custom widget from the kv lang file.
Add an action to be called from the kv lang file.
'''
label_wid = ObjectProperty()
info = StringProperty()
def do_action(self):
kv_var = global_idmap['global_background_color_A'] # <--
self.label_wid.text = str(kv_var) # <--
self.info = 'New info text'
class ControllerApp(App):
def build(self):
return Controller(info='Hello world')
if __name__ == '__main__':
ControllerApp().run()我已经用箭头标记了__main__.py中的重要行。
如果您查看一下kv语言解析器here,就可以看到它对set命令做了什么。它执行一些错误检查,并对容器global_idmap中的值执行eval()s。
现在,我不认为这是值得推荐的。正如您可以看到的那样,kivy特别不公开global_idmap。我认为这是一个不应该依赖的实现细节。
如果你想在代码中改变东西的颜色,你可以这样做:
def do_action(self):
...
self.button_wid.background_color = (1, 0, 1, 1)https://stackoverflow.com/questions/48398104
复制相似问题