如何用python创建一个自定义Kivy标签类?

2024-04-25 07:06:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用kivy编写一个桌面应用程序,但是它没有我想要的那样快。我有很多标签和按钮,有很多格式,只是颜色和大小不同。我希望,如果我创建一个自定义kivy标签的格式已经在它上面,将提高性能。我已经有我所有的格式标签,我想把它们都改成我的自定义kivy标签。在

kivy文件中的原始代码。我所有的标签都是这样的

Label:  
    text: "some text"  
    color: (0, 0.2, .4, 1)  
    size_hint: 1, 0.04  
    text_size: self.size  
    halign: 'left'  
    valign: 'top'  
    bold: True  
    canvas.before:  
        Color:  
            rgba: 1, 1, 1, 1  
        Rectangle:  
            pos: self.pos  
            size: self.size  

所以我试图创建一个FormattedLabel类来添加我想要的所有格式,然后在kivy文件中更改FormattedLabel的标签。在

Python文件

^{pr2}$

Kivy文件

FormattedLabel:  
    text: "some text"  
    color: (0, 0.2, .4, 1)  
    size_hint: 1, 0.04  
    background_color: 0,0,0,1  

但它并没有产生与我最初代码相同的结果: 1矩形的大小变小(更窄和更高),因此字母不再适合直线。我不知道如何将矩形的大小绑定到kivy文件中的size_提示。 2标签的颜色不变。 我不知道是因为代码不应该在init下,还是因为我不知道如何正确地编写它。提前感谢您的帮助!在


Tags: 文件代码textposselfsize颜色格式
1条回答
网友
1楼 · 发布于 2024-04-25 07:06:33

问题

  1. The size of the rectangle is off (narrower and taller) so the letters do not longer fit in a straight line. I don't know how to bind the rectangle's size to the size_hint in the kivy file.
  2. The colour of the label doesn't change. I don't know if it is because the code should not be under init or because I'm just not getting how to write it properly.

根本原因

结果并不像预期的那样,因为Kivy还没有完成它的造型。例如,矩形的大小是关闭的,因为它使用小部件的默认大小,即(100,100)。在

The load_kv() function is called from run(), therefore, any widget whose styling is defined in this kv file and is created before run() is called (e.g. in __init__), won’t have its styling applied. Note that build() is called after load_kv has been called.

解决方案

  1. 实现方法initialize_widget()
  2. canvas.add替换为canvas.before.add,因为没有before关键字,文本将不可见。在
  3. 在Kivy完成样式设置之后,使用Kivy Clock^{}方法来调用initialize_widget()函数。在

片段

from kivy.clock import Clock

...

class FormattedLabel(Label):  
    background_color = ListProperty()  

    def __init__(self, *args, **kwargs):  
        Label.__init__(self, *args, **kwargs)  
        Clock.schedule_once(lambda dt: self.initialize_widget(), 0.002)

    def initialize_widget(self):
        self.canvas.before.add(Color(self.background_color))  
        self.canvas.before.add(Rectangle(pos=self.pos, size=self.size))  
        self.text_size = self.size  
        self.halign = 'left'  
        self.valign = 'top'  
        self.bold = True  

相关问题 更多 >