如何在Kivy中实现文本居中?halign=center参数未生效问题
在Kivy中实现文本居中的解决方案
你遇到的问题根源在于:halign="center"仅控制文本在CoreLabel生成的纹理(texture)内部的对齐,而非让整个纹理相对于你设置的pos居中。你直接把纹理的左下角固定在(865,30),所以即使文本在纹理里居中了,整个纹理还是靠左显示,看起来文本没对齐到目标位置。
方案1:让文本围绕固定位置居中
调整Rectangle的pos,让纹理的中心与目标位置重合即可:
from kivy.app import App from kivy.uix.widget import Widget from kivy.uix.label import CoreLabel from kivy.graphics import Rectangle, Color from kivy.core.window import Window class MyWidget(Widget): def __init__(self, **kwargs): super().__init__(**kwargs) Window.clearcolor = (1, 1, 1, 1) self.canvas.clear() with self.canvas: Color(0, 0, 0, 1) label = CoreLabel(text="Text", font_size=50, halign="center") label.refresh() text = label.texture # 计算纹理中心对齐目标点的坐标:目标x减去纹理宽度的一半,y同理 pos_x = 865 - text.width / 2 pos_y = 30 - text.height / 2 Rectangle(size=text.size, pos=(pos_x, pos_y), texture=text) class MyApp(App): def build(self): return MyWidget() if __name__ == "__main__": MyApp().run()
方案2:让文本在窗口中自适应居中(适配窗口大小变化)
如果需要文本始终在窗口中间,可绑定Widget的size变化事件,动态计算居中位置:
from kivy.app import App from kivy.uix.widget import Widget from kivy.uix.label import CoreLabel from kivy.graphics import Rectangle, Color from kivy.core.window import Window class MyWidget(Widget): def __init__(self, **kwargs): super().__init__(**kwargs) Window.clearcolor = (1, 1, 1, 1) self.label = CoreLabel(text="Text", font_size=50, halign="center") # 绑定窗口尺寸变化事件,实时更新文本位置 self.bind(size=self.update_text_pos) # 初始化时先更新一次位置 self.update_text_pos() def update_text_pos(self, *args): self.canvas.clear() with self.canvas: Color(0, 0, 0, 1) self.label.refresh() text = self.label.texture # 基于当前Widget尺寸计算居中位置 pos_x = self.width / 2 - text.width / 2 pos_y = self.height / 2 - text.height / 2 Rectangle(size=text.size, pos=(pos_x, pos_y), texture=text) class MyApp(App): def build(self): return MyWidget() if __name__ == "__main__": MyApp().run()
关键总结
halign="center"负责文本在自身纹理区域内的居中,确保文本不会偏左/右溢出纹理- 要让纹理整体相对于某个点居中,必须手动调整
Rectangle的pos,用目标坐标减去纹理宽高的一半 - 适配窗口大小变化时,通过绑定
size事件动态计算位置即可
内容的提问来源于stack exchange,提问作者BarricadeX75
相关产品推荐
相关产品推荐

