What I am trying to do is continuously generate new cloud images onto the kivy window -which I have done successfully-, but now I want them to continuously move to the left and off the screen to give the "sky" environment a moving effect. Though I haven't been able to change the images' positions. Any suggestions as to how I could make it work?
from kivy.app import App
from kivy.properties import Clock
from kivy.uix.widget import Widget
from kivy.graphics.context_instructions import Color
from kivy.uix.image import Image
from kivy.core.window import Window
import random
class MainWidget(Widget):
state_game_ongoing = True
clouds = []
def __init__(self, **kwargs):
super().__init__(**kwargs)
Clock.schedule_interval(self.init_clouds, 1 / 10)
def init_clouds(self, dt):
x = random.randint(-100, self.width)
y = random.randint(-100, self.height)
cloud = Image(source="images/cloudbig.png",
pos=(x, y))
self.add_widget(cloud)
class BalloonGameApp(App):
def build(self):
Window.clearcolor = (.2, .6, .8, 1)
xd = MainWidget()
return xd
BalloonGameApp().run()
I tried adding the clouds into a list using .append(), and calling each cloud and changing its position in a for loop via
clouds = []
def init_clouds(self, dt):
x = random.randint(-100, self.width)
y = random.randint(-100, self.height)
cloud = Image(source="images/cloudbig.png",
pos=(x, y))
self.add_widget(cloud)
clouds.append(cloud)
x += 100
y += 100
for cloud in self.clouds:
cloud.pos(x, y)
I also tried the same method but in an "update" function that was on loop via Clock.schedule_interval() kivy function, which also didn't work the error I usually get is
TypeError: 'ObservableReferenceList' object is not callable
Any help would be appreciated, thanks in advance!
You need to check all Image's Parent. For more soft move lets create another Clock:
Clock.schedule_interval(self.move_clouds,1/100)
Now lets edit this function:
def move_clouds(self,*args):
out_cloud_list = [] #If cloud not in screen remove:
for child in self.children:
if child.pos[0] >= self.width:
out_cloud_list.append(child)
else:
child.pos[0] += 5
for cloud in out_cloud_list:
self.remove_widget(cloud)
Related
So i'm making this arcade game and i have a state machine that takes an object(the enemy class) as a constructor parameter, and i have 1 folder for the enemy sprite.
So when i instantiate 1 state machine the game works fine, but when i instantiate 2 state machines(2 enemies) things get weird, when 1 enemy gets to the end of the screen and turn around with kivy's "flip_horizontal" the other enemy turns around too, and its because both state machines are controlling the same enemy folder(same images).
Now if i create an enemy folder for each state machine then it works fine but this is not good. so i thought about manipulating the images in memory, this way the effects of a state machine on the images wont be shared to other state machines.
I tried to do this using CoreImage but the furthest i got was to get a static on the screen and move the "x position", no animation, nothing.
So would anyone help me with this? or if you have a better solution i will be grateful.
heres a sample code:
statemachine.py:
from kivy.app import App
from kivy.properties import Clock, StringProperty, NumericProperty
from kivy.atlas import Atlas
from kivy.uix.image import Image
from itertools import cycle
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.widget import Widget
from kivy.core.window import Window
class EnemyFSM(FloatLayout):
def __init__(self, enemy_object, **kwargs):
super().__init__(**kwargs)
self.enemy = enemy_object
self.states = {'ROAM': 'ROAM',
'CHASE': 'CHASE',
'ATTACK': 'ATTACK',
'DEAD': 'DEAD',
'IDLE': 'IDLE'}
self.state = self.states['ROAM']
self.init_state = True
def update(self, dt):
if self.state == 'ROAM':
self.roam_state()
def idle_state(self):
self.enemy.methods_caller("walk")
def roam_state(self):
self.enemy.methods_caller("walk")
main.py:
from kivymd.app import MDApp
from kivymd.uix.screen import MDScreen
from kivymd.uix.floatlayout import MDFloatLayout
from kivy.properties import Clock
from kivy.uix.image import Image
from kivy.properties import NumericProperty
from random import uniform as rdm
from random import randint as rdi
from random import choice
enemy_list = []
from baseenemy import Enemy
from statemachine import EnemyFSM
class LevelOne(MDScreen):
def __init__(self, **kwargs):
super().__init__(**kwargs)
Clock.schedule_once(self.setup, 1/60)
def setup(self, dt):
self.left_side_spawn = rdi(-500, -100)
self.right_side_spawn = rdi(500, 600)
self.spawn_side = [self.left_side_spawn, self.right_side_spawn]
self.speed = rdi(1, 5)
"""here we instatiate the enemies, 1 works fine, 2 or more then hell breaks loose unless we give each state machine its own image folder"""
for _ in range(1):
self.base_enemy = Enemy(choice(self.spawn_side), rdm(1, 5))
self.add_widget(self.base_enemy)
self.enemy_ai = EnemyFSM(self.base_enemy)
self.add_widget(self.enemy_ai)
enemy_list.append(self.enemy_ai)
Clock.schedule_interval(self.init_game, 1/60)
def init_game(self, dt):
for i in range(len(enemy_list)):
enemy_list[i].update(dt)
class MainApp(MDApp):
def build(self):
self.theme_cls.theme_style = "Dark"
self.theme_cls.primary_palette = "Red"
return None
def on_start(self):
self.fps_monitor_start()
main.kv:
LevelOne:
<EnemyFSM>:
<Enemy>:
source: root.frame_path #the frame_path variable in the enenmy class
size_hint: None, None
size: "150dp", "150dp"
x: root.xpos
y: root.ypos
baseenemy.py:
from kivy.app import App
from kivy.atlas import Atlas
from kivy.properties import Clock, StringProperty, NumericProperty
from kivy.uix.image import Image
from kivy.core.image import Image as CoreImage
import itertools
"""Method to set up the frame names"""
def frame_setup(src):
return [f"1_enemies_1_{src}_{i}" for i in range(20)]
"""Path to the image folder with the atlas"""
def create_frame_path(frame_name):
return {'my_source':
f"atlas://{frame_name}/{frame_name}_atlas/1_enemies_1_{frame_name}_0",
'my_atlas': f"atlas://{frame_name}/{frame_name}_atlas/"}
class Enemy(Image):
xpos = NumericProperty(10)
ypos = NumericProperty(50)
init_frame = create_frame_path('walk')#default frame state 'walk'
frame_path = StringProperty(init_frame['my_source'])#path to the image, this var is also the images source in the .kv file
frame_atlas_path = None
updated_frames = []
previous_frame = None
frame_cycle_called = False
updated_frames_cycle = None
fliped = 0
def __init__(self, spawn_pos, speed, *args, **kwargs):
super().__init__(**kwargs)
self.goal = 0
self.methods_dict = {'walk': self.walk}
self.methods_call = None
self.step = 3
self.xpos = spawn_pos
"""this method, takes a param, and sets up everything
the new frame if the frame is diferent than the current frames'walk'
creates the frame list..."""
def methods_caller(self, new_src):
#The src param is the state of the enemy
#which will tell which frames to set up
#now its just "walk"
self.src = new_src
self.updated_frames = frame_setup(self.src)
#if a state change has occured these lines will run and set up
# a new set of frames according to the new state but for now its just the 'walk' state
if self.previous_frame is not new_src:
self.previous_frame = new_src
self.methods_call = self.methods_dict[new_src]#this get the dict element which is a function and assign to the var
self.frame_path = str(create_frame_path(new_src))
self.frame_atlas_path = create_frame_path(new_src)
self.frame_cycle_called = False
if not self.frame_cycle_called:
self.updated_frames_cycle = itertools.cycle(self.updated_frames)
self.frame_cycle_called = True
self.methods_call()#calling the method we got from the dict element which call the walk method
def walk(self):
#this is where the walking animation happen
if self.xpos >= 700:
self.goal = 1
if self.xpos <= -300:
self.goal = 0
self.frame_path =
self.frame_atlas_path['my_atlas']+next(self.updated_frames_cycle)
image_side = Image(source=self.frame_path).texture
if self.goal == 0 and int(round(image_side.tex_coords[0])) != 0:
image_side.flip_horizontal()
self.fliped = 0
if self.goal == 1 and int(round(image_side.tex_coords[0])) != 1:
image_side.flip_horizontal()
self.fliped = 1
if self.fliped == 0:
self.xpos += self.step
if self.fliped == 1:
self.xpos -= self.step
And finally heres the link to a zip file with the image folder:
https://drive.google.com/file/d/11eGTS_pI690eI5EhxAAoRmT05uNW3VOM/view?usp=sharing
and sorry for the long text.
import kivy
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.clock import Clock
from kivy.graphics import Rectangle
from kivy.core.image import Image as CoreImage
from kivy.core.window import Window
class Background(Widget):
def __init__(self, **kw):
super(Background, self).__init__(**kw)
with self.canvas:
texture = CoreImage('space.png').texture
texture.wrap = 'repeat'
self.rect_1 = Rectangle(texture=texture, size=self.size, pos=self.pos)
Clock.schedule_interval(self.txupdate, 0)
def txupdate(self, *l):
t = Clock.get_boottime()
self.rect_1.tex_coords = -(t * 0.001), 0, -(t * 0.001 + 10), 0, -(t * 0.001 + 10), -10, -(t * 0.001), -10
class CosmicPolygons(App):
def build(self):
return Background(size=Window.size)
if __name__ == "__main__":
CosmicPolygons().run()
I've tried many different ways and attempts in order to create a scrolling background in Kivy. This was the best method I could find as it was the only one that didn't crash. But I'm pretty sure it's still outdated as it did not work as intended, in addition to distorting my png greatly.
If anyone has any ideas on how to achieve this, let me know. Thanks in advance.
Image of current app:
Space.png:
Here is another approach that just creates a list of Images and moves them across the screen:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.image import Image
from kivy.clock import Clock
from kivy.core.window import Window
class BgImage(Image):
pass
Builder.load_string('''
<BgImage>:
source: 'stars.png'
allow_stretch: True
size_hint: None, 1
width: self.image_ratio * self.height
''')
class Background(FloatLayout):
def __init__(self, **kwargs):
super(Background, self).__init__(**kwargs)
self.deltax = 3 # sets speed of background movement
self.bg_images = [] # list of Images that form the background
Clock.schedule_once(self.set_up_bg)
def set_up_bg(self, dt):
# create BgImages and position them to fill the Background
self.start_x = None
pos_x = -1
while pos_x < self.width:
img = BgImage()
if self.start_x is None:
# starting position of first Image is just off screen
self.start_x = -self.height * img.image_ratio
pos_x = self.start_x
img.pos = (pos_x, 0)
self.bg_images.append(img)
self.add_widget(img)
# calculate starting position of next Image by adding its width
pos_x += self.height * img.image_ratio
# start moving the background
Clock.schedule_interval(self.update, 1.0/30.0)
def update(self, dt):
for img in self.bg_images:
img.x += self.deltax
if img.x > self.width:
# this Image is off screen, move it back to starting position
img.x = self.start_x
class CosmicPolygons(App):
def build(self):
return Background(size=Window.size)
if __name__ == "__main__":
CosmicPolygons().run()
all right? i hope so, I will be very grateful if you try to solve this problem that I'm facing about programming.
I'm trying to make a quadratic function plotter, however I can only display one side of the function.
If you uncomment that part of the code you will see that kivy only displays the other side, but the first side of the graphic is still hidden.
What I want to do and if you can help me here is to display both sides of the quadratic function in the same graph and code.
My code is bellow:
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.lang import Builder
from kivy.properties import ListProperty
from kivy.graphics import Rectangle, Color
Builder.load_string(
'''
<QuadraticApp>:
my_size: [root.size[0]*4, root.size[1]*0.5]
canvas:
Color:
rgba: 1, 1, 1, 0
Rectangle:
pos: (root.pos[0], root.pos[1])
size:(500, 500)
'''
)
class QuadraticApp(Widget):
my_size = ListProperty([0, 0])
def __init__(self):
super(QuadraticApp, self).__init__()
new_y = self.my_size
new_x = self.my_size
#'''
for x in range(100):
with self.canvas:
Color(0.1, 0.75, 0.1, 1, mode='rgba') # GREEN
rectx = Rectangle(pos=(new_x), size=(10, 10))
new_x[0] += (x*0.25-50)/2
new_x[1] += eval('(x)**2')
#'''
# Comment the for loop above to hide the another showing graphic
# And Uncoment this code bellow to show the another part of graphic
'''
for y in range(100):
with self.canvas:
Color(0.75, 0.1, 0.1, 1, mode='rgba') # RED
recty = Rectangle(pos=(new_y), size=(10, 10))
new_y[0] += -(y*0.25-50)/2
new_y[1] += eval('(y)**2')
'''
class MathApp(App):
def build(self):
return QuadraticApp()
if __name__ == '__main__':
MathApp().run()
This image bellow show the graphic at the left simetric side
https://i.stack.imgur.com/i1WTy.jpg
This image bellow show the graphic at the right simetric side
https://i.stack.imgur.com/HVhAz.jpg
Now i can say thank you for u support.
The problem is that the code:
new_y = self.my_size
new_x = self.my_size
is just creating references to self.my_size, so when you change new_x, or new_y, or self.my_size, you are changing all three. At the start of your second loop, new_y starts out with the values from new_x from the end of the first loop. Try changing those two lines to:
new_y = self.my_size.copy()
new_x = self.my_size.copy()
I am learning Kivy, and to make it more fun I am creating a small 2D game. For now its just a tank that can be controlled with WASD and shot projectiles with o.
The problem is that the FPS degrades over time. This happens even if I do nothing in the game. I don´t have an FPS counter, but its something like half the FPS after a minute of gametime.
My feeling is that the problem lies somewhere in the updating of canvas in widgets. Since the slowdowns occour even if the player does nothing for the whole game, its seems like there is data somewhere that is just added and added. I don´t know how to better explain it, other than its weird ...
A quick overview of how the game is programmed so far:
The main widget is the class Game. It detects keypresses and runs "Clock.schedule_interval-function".
The Tank widget is a child of Game. It holds some data and loads the hull and turret sprites via Kivys Image widget, which becomes its child. It has its own update function that updates everything tank-related, including setting the position of its canvas and rotating the hull and turret image canvas. The update-function in the Tank widget class is inwoked by "Clock.schedule_interval" in Game class.
The Shots widget does the same as the Tank widget, only it holds data for each shot fired instead
"Clock schedule_interval"-function holds a list of each shot widget, and deletes them when they get off screen. However, the slowdown problems persist even if no shots are fired.
I have attached the complete code. This might be excessive, but I don´t know wich part of it that provokes slowdowns. If you want to run the game, just put those four python-files in the same folder, and the images in a sub-folder called "images tank".
I hope someone can take a look at it :)
main.py:
#Import my own modules:
import tank
import shot
from stats import Stats
#Import kivy:
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.clock import Clock
#Set window size properties:
from kivy.config import Config
Config.set('graphics','resizable',0)
from kivy.core.window import Window
class Game(Widget):
def __init__(self):
#General settings:
super(Game, self).__init__()
Clock.schedule_interval(self.update, 1.0/60.0)
#Add keyboard:
self._keyboard = Window.request_keyboard (callback=None, target=self, input_type="text")
#Bind the keyboard to a function:
self._keyboard.bind(on_key_down=self.keypress)
self._keyboard.bind(on_key_up=self.keyUp)
#P1 tank starting values:
self.keypress_p1 = {"forward":False, "backward":False, "left":False, "right":False, "turret_left":False, "turret_right":False, "fire":False}
#P1 tank widget:
self.tank_p1 = tank.Tank()
self.add_widget(self.tank_p1)
#P1 shots list:
self.shotsList_p1 = []
#Keyboard press detection:
def keypress(self, *args):
key = args[2]
if key == "w":
self.keypress_p1["forward"]=True
if key == "s":
self.keypress_p1["backward"]=True
if key == "a":
self.keypress_p1["left"]=True
if key == "d":
self.keypress_p1["right"]=True
if key == "q":
self.keypress_p1["turret_left"]=True
if key == "e":
self.keypress_p1["turret_right"]=True
if key == "o":
self.keypress_p1["fire"]=True
#Keyboard button up detection:
def keyUp(self, *args):
key = args[1][1]
if key == "w":
self.keypress_p1["forward"]=False
if key == "s":
self.keypress_p1["backward"]=False
if key == "a":
self.keypress_p1["left"]=False
if key == "d":
self.keypress_p1["right"]=False
if key == "q":
self.keypress_p1["turret_left"]=False
if key == "e":
self.keypress_p1["turret_right"]=False
if key == "o":
self.keypress_p1["fire"]=False
#Parent update function that the clock runs:
def update(self, dt):
#Add new shots:
if self.keypress_p1["fire"]:
self.shot = shot.Shots(self.tank_p1.my_pos, self.tank_p1.my_angle+self.tank_p1.my_turretAngle)
self.shotsList_p1.append(self.shot)
self.add_widget(self.shot)
self.keypress_p1["fire"] = False
#P1 tank update:
self.tank_p1.update(self.keypress_p1)
#P1 shot update:
for i in range(len(self.shotsList_p1)-1,-1,-1):
self.shotsList_p1[i].update()
#Remove widgets that are outside the screen:
if ( 0<=self.shotsList_p1[i].my_pos[0]<Stats.winSize[0] and 0<=self.shotsList_p1[i].my_pos[1]<Stats.winSize[1] )==False:
self.remove_widget(self.shotsList_p1[i])
del self.shotsList_p1[i]
class MyApp(App):
def build(self):
game = Game()
Window.size = Stats.winSize
return game
MyApp().run()
tank.py:
#Import own modules:
from stats import Stats
#import python:
import math
#Import Kivy:
from kivy.uix.widget import Widget
from kivy.uix.image import Image
from kivy.graphics.context_instructions import PushMatrix, PopMatrix, Rotate, Translate, MatrixInstruction
from kivy.graphics.fbo import Fbo
class Tank(Widget):
def __init__(self):
super(Tank, self).__init__()
#Position and rotation values for the tank:
self.my_pos = [0,0]
self.posChange = [0,0]
self.my_angle = 0
self.angleChange = 0
self.my_turretAngle = 0
self.turretAngleChange = 0
#Hull widget:
self.hull = Hull()
self.add_widget(self.hull)
self.hull.center_x = self.my_pos[0]
self.hull.center_y = self.my_pos[1]
#Turret widget:
self.turret = Turret()
self.add_widget(self.turret)
self.turret.center_x = self.my_pos[0]
self.turret.center_y = self.my_pos[1]
def update(self, keypress):
if keypress["forward"]:
self.my_pos[0] -= Stats.hull_t1["forward"]*math.sin(math.radians(self.my_angle))
self.my_pos[1] += Stats.hull_t1["forward"]*math.cos(math.radians(self.my_angle))
self.posChange[0] = -Stats.hull_t1["forward"]*math.sin(math.radians(self.my_angle))
self.posChange[1] = Stats.hull_t1["forward"]*math.cos(math.radians(self.my_angle))
if keypress["backward"]:
self.my_pos[0] -= Stats.hull_t1["backward"]*math.sin(math.radians(self.my_angle))
self.my_pos[1] += Stats.hull_t1["backward"]*math.cos(math.radians(self.my_angle))
self.posChange[0] = -Stats.hull_t1["backward"]*math.sin(math.radians(self.my_angle))
self.posChange[1] = Stats.hull_t1["backward"]*math.cos(math.radians(self.my_angle))
if keypress["left"]:
self.my_angle += Stats.hull_t1["left"]
self.angleChange = Stats.hull_t1["left"]
if keypress["right"]:
self.my_angle += Stats.hull_t1["right"]
self.angleChange = Stats.hull_t1["right"]
if keypress["turret_left"]:
self.my_turretAngle += Stats.turret_t1["left"]
self.turretAngleChange = Stats.turret_t1["left"]
if keypress["turret_right"]:
self.my_turretAngle += Stats.turret_t1["right"]
self.turretAngleChange = Stats.turret_t1["right"]
#Tank Position:
with self.canvas.before:
PushMatrix()
Translate(self.posChange[0], self.posChange[1])
with self.canvas.after:
PopMatrix()
#Rotate hull image:
with self.hull.canvas.before:
PushMatrix()
self.rot = Rotate()
self.rot.axis = (0,0,1)
self.rot.origin = self.hull.center
self.rot.angle = self.angleChange
with self.hull.canvas.after:
PopMatrix()
#Rotate turret image:
with self.turret.canvas.before:
PushMatrix()
self.rot = Rotate()
self.rot.axis = (0,0,1)
self.rot.origin = self.turret.center
self.rot.angle = self.turretAngleChange + self.angleChange
with self.turret.canvas.after:
PopMatrix()
#Reset pos, angle and turretAngle change values:
self.posChange = [0,0]
self.angleChange = 0
self.turretAngleChange = 0
#--------------------------------------------------------------------------------------------------
class Hull(Image):
def __init__(self):
super(Hull, self).__init__(source="images tank/Tank.png")
self.size = self.texture_size
class Turret(Image):
def __init__(self):
super(Turret, self).__init__(source="images tank/GunTurret.png")
self.size = self.texture_size
shot.py:
#Import own modules:
from stats import Stats
#import python:
import math
from copy import copy
#Import Kivy:
from kivy.uix.widget import Widget
from kivy.uix.image import Image
from kivy.graphics.context_instructions import PushMatrix, PopMatrix, Rotate, Translate, MatrixInstruction
from kivy.graphics.fbo import Fbo
class Shots(Widget):
def __init__(self, tankPos, turretAngle):
super(Shots, self).__init__()
#Shot data:
self.my_pos = copy(tankPos)
self.my_angle = turretAngle
self.angleChange = self.my_angle
self.posChange = [ -Stats.shot_t1["speed"]*math.sin(math.radians(self.my_angle)), Stats.shot_t1["speed"]*math.cos(math.radians(self.my_angle)) ]
#Add image:
self.shotImg = ShotImg()
self.add_widget(self.shotImg)
self.shotImg.pos = self.my_pos
self.shotImg.center_x = self.my_pos[0]
self.shotImg.center_y = self.my_pos[1]
def update(self):
self.my_pos[0] += self.posChange[0]
self.my_pos[1] += self.posChange[1]
#Shot Position:
with self.canvas.before:
PushMatrix()
Translate(self.posChange[0], self.posChange[1])
with self.canvas.after:
PopMatrix()
#Rotate shot image:
if self.angleChange != 0:
with self.shotImg.canvas.before:
PushMatrix()
self.rot = Rotate()
self.rot.axis = (0,0,1)
self.rot.origin = self.shotImg.center
self.rot.angle = self.angleChange
with self.shotImg.canvas.after:
PopMatrix()
self.angleChange = 0
class ShotImg(Image):
def __init__(self):
super(ShotImg, self).__init__(source="images tank/Bullet.png")
self.size = self.texture_size
stats.py:
class Stats:
winSize = (800,800)
hull_t1 = {"forward":2, "backward":-2, "left":2, "right": -2}
turret_t1 = {"left":5, "right":-5}
shot_t1 = {"speed":3}
images should go in a subfolder called "images tank":
Bullet
GunTurret
Tank
The way you manage your position will create 8 new instructions per tank, and 6 per shot, every frame, which, at 60fps, will quickly create thousands of instructions, and for kivy will be slower and slower to process them.
#Tank Position:
with self.canvas.before:
PushMatrix()
Translate(self.posChange[0], self.posChange[1])
with self.canvas.after:
PopMatrix()
you don't want to do that, you want to create one Translate insruction (and same for Rotate) in your widget, and update it, move this block to __init__ and save Translate to self.translate for example, then in update, instead of using posChange, simply do self.translate.x, self.translate.y = self.my_pos
apply the same logic for rotation, and for shots, and the performances should be much more stable over time.
I had the same issue, I'm working on a space invaders game and it happened to be the way I treated my logic, I used "with self.canvas"
to draw my widgets, which appeared to be on the long term exhaustive as widgets that get generated on canvas are not being cleared, which is an important thing to be concerned about.
I Fixed it with creating a class for my objects (enemy, bullet, player) and when I need lets say 6 enemies to be created, I create a list of enemy widgets to keep track of them, and them add them to my on my main game widget by using self.add_widget(YourWidgetItem)
and simply when the widget has ended its purpose, like an enemy dying, I set my dead variable for this widget to be true, then scan for dead widgets and remove them from my main game widget by using self.remove_widget(YourWidgetItem)
this is one of many other possible solutions, you just need to take into consideration killing the widget that get off your screen to no overload your game on higher levels
You can check my project if it would help:
https://github.com/steveroseik/Invaders_Game
I am trying to dynamically change the background color of a Label in Kivy with this simple program. it is intended to produce a grid of red and black cells. However, all I get is a red cell in position (7,0) (I am printing the positions).
import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.graphics import Color, Rectangle
class LabelX(Label):
def set_bgcolor(self,r,b,g,o,*args):
self.canvas.after.clear()
with self.canvas.after:
Color(r,g,b,o)
Rectangle(pos=self.pos,size=self.size)
class MyGrid(GridLayout):
def __init__(self,cols,rows,**kwargs):
super(MyGrid,self).__init__(**kwargs)
self.cols = cols
for i in range(rows):
for j in range(cols):
l = LabelX(text=str(i)+","+str(j))
if (i*rows+j)%2:
l.set_bgcolor(1,0,0,1)
else:
l.set_bgcolor(0,0,0,1)
self.add_widget(l)
class GridApp(App):
def build(self):
g = MyGrid(8,8)
return g
if __name__=="__main__":
GridApp().run()
Any ideas on how to get a red/black checker board?
If you print self.pos using the following:
with self.canvas.after:
[...]
print(self.pos)
[...]
only the values [0, 0] are obtained, and that leads to the conclusion that all the rectangles are drawn in that position, so they are superimposed, and that is what you observe.
For example, to verify this we pass a parameter more to the function set_bgcolor () that will be the index of the loop and we will use it as a parameter to locate the position:
def set_bgcolor(self, r, b, g, o, i):
[..]
Rectangle(pos=[100*i, 100*i],size=self.size)
class MyGrid(GridLayout):
def __init__(self,cols,rows,**kwargs):
[...]
if (i*rows+j)%2:
l.set_bgcolor(1,0,0,1, i)
else:
l.set_bgcolor(0,0,0,1, i)
self.add_widget(l)
We get the following:
also if we change the size of the window the rectangle does not change either:
So if you want the Rectangle to be the bottom of the Label, the position and size of the Rectangle should be the same as the Label, so you have to make a binding with both properties between the Label and Rectangle. You must also use canvas.before instead of canvas.after otherwise the Rectangle will be drawn on top of the Label.
class LabelX(Label):
def set_bgcolor(self,r,b,g,o):
self.canvas.before.clear()
with self.canvas.before:
Color(r,g,b,o)
self.rect = Rectangle(pos=self.pos,size=self.size)
self.bind(pos=self.update_rect,
size=self.update_rect)
def update_rect(self, *args):
self.rect.pos = self.pos
self.rect.size = self.size
The advantage of my solution is that it is independent of the external widget or layout since the position and size of the Rectangle only depends on the Label.
The problem is that each labels position is (0,0) and size is (100,100) until the app is actually built. so all your canvas drawing is done at those positions and sizes. You can get the checkerboard effect by waiting until after the positions and sizes are assigned, then doing the checkerboard effect. I do this with a Clock.schedule_once:
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.graphics import Color, Rectangle
from kivy.clock import Clock
from kivy.core.window import Window
class LabelX(Label):
def set_bgcolor(self,r,b,g,o,*args):
self.canvas.after.clear()
with self.canvas.after:
Color(r,g,b,o)
Rectangle(pos=self.pos,size=self.size)
class MyGrid(GridLayout):
def __init__(self,cols,rows,**kwargs):
super(MyGrid,self).__init__(**kwargs)
self.cols = cols
for i in range(rows):
for j in range(cols):
l = LabelX(text=str(i)+","+str(j))
l.rowcol = (i,j)
self.add_widget(l)
class GridApp(App):
def build(self):
self.g = MyGrid(8,8)
Window.bind(size=self.checkerboard)
return self.g
def checkerboard(self, *args):
for l in self.g.children:
count = l.rowcol[0] + l.rowcol[1]
if count % 2:
l.set_bgcolor(1, 0, 0, 1)
else:
l.set_bgcolor(0, 0, 0, 1 )
if __name__=="__main__":
app = GridApp()
Clock.schedule_once(app.checkerboard, 1)
app.run()