You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python FMX GUI应用中为Label组件添加边框?

为DelphiFMX for Python的Label组件添加边框

可以给Label组件添加边框,你之前的代码未生效是因为FMX的Label默认样式不会渲染Stroke属性,需要通过以下两种方式实现:

方法1:使用内置边框样式

直接为Label指定内置的带边框样式,再配合Stroke属性调整边框的颜色、粗细等:

修改你的Label初始化代码,添加以下内容:

self.myLabel.StyleLookup = "borderedlabel"  # 启用带边框的内置样式
self.myLabel.Stroke.Kind = "Solid"
self.myLabel.Stroke.Color = "Black"
self.myLabel.Stroke.Thickness = 2
# 可选:设置边框圆角
self.myLabel.CornerRadius = 6

完整的示例代码:

from delphifmx import *

class frmMain(Form):
    def __init__(self, owner):
        self.Caption = 'Hello World'
        self.Width = 1000
        self.Height = 500
        self.Position = "ScreenCenter"

        self.myLabel = Label(self)
        self.myLabel.Parent = self
        self.myLabel.Text = "Hello World!"
        self.myLabel.Align = "Client"
        self.myLabel.StyledSettings = ""
        self.myLabel.TextSettings.Font.Size = 85
        self.myLabel.TextSettings.HorzAlign = "Center"
        
        # 添加边框相关设置
        self.myLabel.StyleLookup = "borderedlabel"
        self.myLabel.Stroke.Kind = "Solid"
        self.myLabel.Stroke.Color = "Black"
        self.myLabel.Stroke.Thickness = 2
        self.myLabel.CornerRadius = 6

Application.Initialize()
Application.Title = "My Application"
Application.MainForm = frmMain(Application)
Application.MainForm.Show()
Application.Run()
Application.MainForm.Destroy()

方法2:自定义绘制边框(灵活控制样式)

如果内置样式无法满足需求,可以通过绑定OnPaint事件手动绘制边框:

from delphifmx import *

class frmMain(Form):
    def __init__(self, owner):
        self.Caption = 'Hello World'
        self.Width = 1000
        self.Height = 500
        self.Position = "ScreenCenter"

        self.myLabel = Label(self)
        self.myLabel.Parent = self
        self.myLabel.Text = "Hello World!"
        self.myLabel.Align = "Client"
        self.myLabel.StyledSettings = ""
        self.myLabel.TextSettings.Font.Size = 85
        self.myLabel.TextSettings.HorzAlign = "Center"
        
        # 绑定自定义绘制事件
        self.myLabel.OnPaint = self.on_label_paint

    def on_label_paint(self, sender, canvas):
        # 获取Label的客户端区域
        rect = sender.ClientRect
        # 调整边框位置,避免覆盖文字
        rect.Inflate(-10, -10)
        # 设置边框样式
        canvas.Stroke.Color = "DarkBlue"
        canvas.Stroke.Thickness = 4
        # 绘制带圆角的矩形边框
        canvas.DrawRect(rect, 8, 8, True, True)

Application.Initialize()
Application.Title = "My Application"
Application.MainForm = frmMain(Application)
Application.MainForm.Show()
Application.Run()
Application.MainForm.Destroy()

关键说明

  • FMX Label组件默认的样式不包含边框渲染逻辑,因此直接设置Stroke属性不会生效,必须指定StyleLookup为支持边框的样式,或者通过OnPaint事件手动绘制。
  • 自定义绘制方式可以更灵活地控制边框的位置、形状、颜色等细节,比如调整rect.Inflate的值来改变边框与文字的间距。

内容的提问来源于stack exchange,提问作者Shaun Roselt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 01:14:55