.kv file global variable both work and not work
Software Versions
- Python: 3.9
- OS: macOS Big Sur
- Kivy: 2.1.0
- Kivy installation method: pip
Describe the bug When declaring a global variable in .kv file, it works under some conditions and does not work under others.
Expected behavior Expect the declared global variable to work throughout the .kv file.
To Reproduce
Below is an example code showing both instances:
ColorConstants.kv showing both working and non-working conditions:
#:kivy 2.0.0
#:set BLUE (0, 0, 1, 1)
#:set WHITE (1, 1, 1, 1)
<Header@BoxLayout>:
# color constants don't work here: NoneType errors
# font_color: WHITE
# header_color: BLUE
font_color: (1, 1, 1, 1)
header_color: (0, 0, 1, 1)
header_text: ""
size_hint: 1, None
height: dp(50)
canvas.before:
Color:
rgba: self.header_color
Rectangle:
size: self.size
pos: self.pos
Label:
color: root.font_color
text: root.header_text
bold: True
BoxLayout:
orientation: "vertical"
Header:
header_text: "My Header"
Label:
# color constants work here
color: BLUE
text: "This is blue text on white"
canvas.before:
Color:
rgba: WHITE
Rectangle:
size: self.size
pos: self.pos
ColorConstants.py file to run the above:
from kivy.app import App
class ColorConstantsApp(App):
pass
ColorConstantsApp().run()
As can be seen, BLUE and WHITE are global variables that work in Label but for some strange reason they don't work in Header. When BLUE and WHITE are used for header_color and font_color, a TypeError: 'NoneType' object is not iterable error is encountered. The workaround is to use (0,0,1,1) and (1,1,1,1) in place of BLUE and WHITE, which defeats the purpose of defining the global variables in the first place.
You need to set the color with constant directly on the kv side:
canvas.before:
Color:
rgba: BLUE
Rectangle:
size: self.size
pos: self.pos
The other way is to instantiate the header_color variable on the python side as ColorProperty().
The documentation for [:set] says:
Set a key that will be available anywhere in the kv.
So, saying it is only available in some parts means the documentation is wrong or there is a bug with the code not meeting the spec.