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

如何让CTkTextbox文本居中对齐?尝试anchor和justify无效

解决CTkTextbox文本居中显示的问题

CTkTextbox作为tkinter Text组件的封装,直接使用anchor或justify构造参数可能无法生效,需要直接操作其底层的tkinter Text控件来实现文本居中:

水平居中实现

创建CTkTextbox后,获取内部的原生Text组件,设置其justify属性为center,即可让所有新插入的文本水平居中:

self.tk_textbox = customtkinter.CTkTextbox(self.p1_show_score_frame, activate_scrollbars=False,
                                           width=100, height=150, font=("Arial", 20, "bold"), border_color="Darkblue")
# 获取底层tkinter Text组件
inner_textbox = self.tk_textbox._textbox
# 设置水平居中
inner_textbox.config(justify="center")
self.tk_textbox.grid(row=0, column=1, sticky="nsew")

垂直居中实现(可选)

如果需要让文本在组件内垂直居中,可以通过自定义tag设置上下间距,计算方式为组件高度减去文本的实际请求高度,平分后设置为上下间距:

self.tk_textbox = customtkinter.CTkTextbox(self.p1_show_score_frame, activate_scrollbars=False,
                                           width=100, height=150, font=("Arial", 20, "bold"), border_color="Darkblue")
inner_textbox = self.tk_textbox._textbox
# 水平居中
inner_textbox.config(justify="center")
# 计算垂直居中所需的上下间距
text_height = inner_textbox.winfo_reqheight()
pad_y = (150 - text_height) // 2
# 创建垂直居中tag并应用
inner_textbox.tag_configure("vcenter", spacing1=pad_y, spacing3=pad_y)
inner_textbox.tag_add("vcenter", "1.0", "end")
self.tk_textbox.grid(row=0, column=1, sticky="nsew")

注意事项

  • 若后续插入新文本,需要重新将tag应用到整个文本范围:inner_textbox.tag_add("vcenter", "1.0", "end")
  • 字体参数建议修正为标准格式:font=("字体名称", 字号, "bold"),比如("Arial",20,"bold"),避免解析错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 21:23:15