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

如何在Custom Tkinter中对齐比赛数据的数字?

问题:Custom Tkinter文本框中比赛数据对齐失效
  • 终端/VSCode中输出的比赛数据是对齐的:

Preview 1 2 3 4 5 6 7 8 9 R H E
Astros 0 0 0 0
Cubs 0 0 0 0

  • 但在Custom Tkinter(CTk)文本框中,得分(R)、安打(H)、失误(E)列的数字无法对齐:

Preview 1 2 3 4 5 6 7 8 9 R H E
Astros 0 0 0 0
Cubs 0 0 0 0

(注:从文本框复制粘贴后显示正常,上述为复现效果)

问题代码

import customtkinter
import statsapi
import datetime
import time
import os
    
date = datetime.datetime.now().strftime("%m/%d/%Y")
astros_schedule = statsapi.schedule(team=117,start_date=date,end_date=date)
gamepk = astros_schedule[0]['game_id']
astros_linescore = statsapi.linescore(gamePk=gamepk)

customtkinter.set_appearance_mode("Dark")
customtkinter.set_default_color_theme("dark-blue")


app = customtkinter.CTk()
app.title("Astros Score Manual")
app.grid_columnconfigure(0, weight=1)
app.geometry("650,325")
switch_var = customtkinter.StringVar(value="off")
def switch_event():
    onoff = switch_var.get()
    if onoff == "off":
        Textbox.delete("0.0","end")
    elif onoff == "on":
        Textbox.configure(state="normal")
        Textbox.insert("0.0", astros_linescore)
        Textbox.configure(state="disabled")


Switch = customtkinter.CTkSwitch(master=app, text="CTkSwitch", command=switch_event,
                                   variable=switch_var, onvalue="on", offvalue="off")
Switch.pack(padx=20, pady=10)

Textbox = customtkinter.CTkTextbox(master=app,width=675,height=325, corner_radius=20, border_width=5, activate_scrollbars = False, state="disabled",font=("sans-serif",14), wrap="none")
Textbox.pack(padx=20, pady=10)


app.mainloop()
解决方法

问题根源是当前使用的sans-serif是比例字体(不同字符宽度不同,比如空格和字母宽度不一致),而终端默认使用等宽字体(每个字符宽度相同),导致对齐失效。

具体修复步骤

将CTkTextbox的字体替换为系统自带的等宽字体,比如Consolas、Courier New、Monaco等,修改代码中Textbox的font参数即可:

Textbox = customtkinter.CTkTextbox(master=app,width=675,height=325, corner_radius=20, border_width=5, activate_scrollbars = False, state="disabled",font=("Consolas",14), wrap="none")

不同系统推荐的等宽字体:

  • Windows:Courier New、Lucida Console
  • macOS:Monaco、Menlo
  • Linux:Ubuntu Mono、DejaVu Sans Mono

替换后,文本框中的每个字符(包括空格)宽度完全一致,数据会和终端显示一样保持列对齐。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 03:12:34