将背景图像或颜色矩形设置为GridLayout中的小部件

时间:2014-04-21 10:14:25

标签: python kivy

手头的问题是我有一个屏幕,我在gridlayout下创建了4个小部件。小部件一是一个自定义小部件,它有一个boxlayout,有2个图像和一个按钮。 和其他3个小部件是简单的按钮 现在我希望第一个小部件有一个背景图像或彩色矩形,但是在0,0位置绘制了图像。我试图使用画布指令来创建一个矩形或边框图像但似乎gridlayout显示小部件位置为0,0因此它创建了0,0的矩形。请参阅以下代码:

如何修复此问题并在窗口小部件1的边框处创建矩形?

from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen,FallOutTransition
from kivy.uix.image import Image
from kivy.uix.gridlayout import GridLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.core.window import Window
from kivy.graphics import BorderImage
from kivy.graphics import Color, Rectangle ,Line

#################     Images   ######################
S = Image(source='images/Sti.png')
L = 'images/spinnin.gif'
#################     Images   ######################

class CButtonW(BoxLayout):
    def __init__(self, **kwargs):
        print "init --> CButton self.pos is ",self.pos
        super(CButtonW, self).__init__(**kwargs)
        self.orientation = 'vertical'
        with self.canvas.before:
            Color(1, 1, 0, 1, mode='rgba')
            Rectangle(pos=self.pos,size=self.size)
            BorderImage(
                     border=(10, 10, 10, 10),
                    source='images/tex.png')

        self.add_widget(S)
        self.add_widget(Button(text="Button 1"))
        self.add_widget(Image(source=L))


class LevelScreen(Screen,GridLayout):
    def __init__(self, **kwargs):
        super(LevelScreen, self).__init__(**kwargs)
        with self.canvas:
            Line(points=(10, 10, 20, 30, 40, 50))
            Color(1, 0, 1, 1, mode='rgba')
            Rectangle(pos=self.pos, size=Window.size)

        self.layout = GridLayout(cols=3,spacing=1,padding=10)
        self.Button1 = CButtonW(id='1',text='Level 1')
        self.Button2 = Button(id='2',text='Level 2')
        self.Button3 = Button(id='3',text='Level 3')
        self.Button4 = Button(id='4',text='Level 4')
        self.layout.add_widget(self.Button1)
        self.layout.add_widget(self.Button2)
        self.layout.add_widget(self.Button3)
        self.layout.add_widget(self.Button4)

        LevelScreen.cols=3
        LevelScreen.add_widget(self,self.layout)
        print "position of 1st button is ",self.Button1.pos
        print "position of 2 button is ",self.Button2.pos

# App Class
class MyJBApp(App):
    def build(self):
        sm = ScreenManager(transition= FallOutTransition())
        sm.add_widget(LevelScreen(name='level'))
        return sm

if __name__ == '__main__':
    MyJBApp().run()

1 个答案:

答案 0 :(得分:2)

您的画布说明是在CButtonW按其布局定位之前绘制的,因此此时它仍处于默认位置0,0。

您可以通过添加代码来修复它,以便在窗口小部件的位置或大小发生变化时重新定位指令。最简单的方法是首先使用kv语言,这将自动创建相关的绑定,但您也可以在python中绑定到pos或size,或者使用与其更改相关联的on_propertyname事件。