【问题标题】:Kivy: Positioning of textKivy:文本的定位
【发布时间】:2020-10-04 21:04:38
【问题描述】:

我是 GUI 开发的新手,我正在使用 Kivy 做同样的事情。我在屏幕顶部制作了一个rectangle,它随着窗口大小的变化而增加/减少其长度。我想在矩形内添加文本,这样当我更改窗口大小时,文本不仅会增加/减小其字体大小,而且还会留在矩形内,即在中间。我不知道如何设置fontposition 参数来实现我的目标。

这是 Myapp.py 文件代码:

class Dashboard(RelativeLayout): 
   l = NumericProperty(0.0)
   b = NumericProperty(0.0)


class MyApp(App):  
   def build(self):  
      return (Dashboard())  
MyApp().run() 

这是我的.kv 文件代码:

<Dashboard>:
l: root.width
b: root.height/7

# creating Canvas 
   canvas: 
       Color: 
          rgba: 216 / 255., 195 / 255., 88 / 255., 1
       Rectangle: 
          pos: (0,self.size[1]/1.15)
          size: (self.l,self.b)


   Label: 
      size: self.parent.size[0], self.parent.size[1]
      font_size: self.parent.size[0] * 0.05
      text_size: self.size
      pos_hint:  {'x':0.5,'y':0.9}
      text:'hello!'

提前致谢! :)

【问题讨论】:

    标签: python kivy


    【解决方案1】:

    确保文本在Rectangle 中居中的最简单方法是使Label 的大小和位置与Rectangle 相同,然后使用halignvalign。我在Dashboard 中添加了另一个NumericProperty,只是为了包含RectangleLabel 的y 位置,所以Dashboard 类现在看起来像:

    class Dashboard(RelativeLayout):
       l = NumericProperty(0.0)
       b = NumericProperty(0.0)
       ypos = NumericProperty(0)
    

    还有修改后的kv

    <Dashboard>:
        l: root.width
        b: root.height/7
        ypos: root.size[1]/1.15
    
        # creating Canvas 
        canvas: 
            Color: 
                rgba: 216 / 255., 195 / 255., 88 / 255., 1
            Rectangle: 
                pos: (0, root.ypos)
                size: (root.l,root.b)
    
    
        Label: 
            size_hint: None, None
            size: root.l, root.b
            font_size: min(root.size[0] * 0.05, root.size[1] * 0.05)
            text_size: self.size
            halign: 'center'
            valign: 'center'
            pos: 0, root.ypos
            text:'hello!'
    

    我还修改了font_size 的计算,使其同时考虑Rectangle 的高度和宽度。

    请注意,如果您只想要 Label 的彩色背景,您可以在 Label 本身内执行此操作。这是kv 的另一个版本:

    <Dashboard>:
        l: root.width
        b: root.height/7
        ypos: root.size[1]/1.15
    
        Label: 
            canvas.before: 
                Color: 
                    rgba: 216 / 255., 195 / 255., 88 / 255., 1
                Rectangle: 
                    pos: self.pos
                    size: self.size
    
            size_hint: None, None
            size: root.l, root.b
            font_size: min(root.size[0] * 0.05, root.size[1] * 0.05)
            text_size: self.size
            halign: 'center'
            valign: 'center'
            pos: 0, root.ypos
            text:'hello!'
    

    【讨论】:

      猜你喜欢
      • 2022-06-12
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多