【WIT】ttkbootstrap全组件中文本地化解决方案

1-localezhcn.py 加载全中文语言包

python 复制代码
# 全中文语言包
# 包含所有ttkbootstrap默认消息
# 可以直接使用"zh_cn_all"作为语言标识
# Wiktok 2025-10-01 160540168
from ttkbootstrap.localization.msgs import *
MESSAGES.append(LocaleMsgs(
        "zh_cn_all",
        ("&Abort", "中止(&A)"),
        ("&About...", "关于(&A)......"),
        ("&Apply", "应用(&A)"),
        ("&Blue", "蓝色(&B)"),
        ("&Cancel", "取消(&C)"),
        ("&Clear Console", "清除终端(&C)"),
        ("&Copy", "复制(&C)"),
        ("&Delete", "删除(&D)"),
        ("&Directory:", "目录(&D):"),
        ("&Edit", "编辑(&E)"),
        ("&File", "文件(&F)"),
        ("&Filter", "过滤(&F)"),
        ("&Font:", "字体(&F):"),
        ("&Green", "绿色(&G)"),
        ("&Help", "帮助(&H)"),
        ("&Hide Console", "隐藏终端(&H)"),
        ("&Ignore", "忽略(&I)"),
        ("&No", "否(&N)"),
        ("&OK", "确定(&O)"),
        ("&Open", "打开(&O)"),
        ("&Quit", "退出(&Q)"),
        ("&Red", "红色(&R)"),
        ("&Retry", "重试(&R)"),
        ("&Save", "保存(&S)"),
        ("&Selection:", "选择(&S):"),
        ("&Size:", "大小(&S):"),
        ("&Source...", "来源(&S)......"),
        ("&Underline", "下划线(&U)"),
        ("&Yes", "确定(&Y)"),
        ("⎌", "↺"),
        ("A4", "A4"),
        ("abort", "中止"),
        ("Add", "新增"),
        ("Advanced", "高级"),
        ("Align", "对齐"),
        ("Align center", "居中"),
        ("Align left", "左对齐"),
        ("Align right", "右对齐"),
        ("All Files", "所有文件"),
        ("Application Error", "应用程序错误"),
        ("Blue", "蓝色"),
        ("Bold", "粗体"),
        ("Bold Italic", "加粗斜体"),
        ("Cancel", "取消"),
        ("cancel", "取消"),
        (r"Cannot change to the directory %1\$s.\nPermission denied.",
         r"无法更改目录 %1\$s。\n访问被拒绝。"),
        ("Choose Directory", "选择文件夹"),
        ("Cl&ear", "清除(&E)"),
        ("Clear filters", "Limpar filtros"),
        ("Close", "关闭"),
        ("Color", "颜色"),
        ("Color Chooser", "颜色选择器"),
        ("color dropper", "颜色选择器"),
        ("Columns", "列操作"),
        ("Console", "终端"),
        ("Continue", "继续"),
        ("Copies", "复制"),
        ("Cu&t", "剪&切"),
        ("Current", "当前"),
        ("Delete", "删除"),
        ("Delete column", "删除列"),
        ("Delete selected rows", "删除所选行"),
        ("Details >>", "详细信息 >>"),
        (r"Directory %1\$s does not exist.", r"目录 %1\$s 不存在。"),
        ("E&xit", "退出(&X)"),
        ("Effects", "效果"),
        (r"Error: %1\$s", r"错误: %1\$s"),
        ("Export", "导出"),
        ("Export all records", "导出所有内容"),
        ("Export current page", "导出当前页面"),
        ("Export current selection", "导出当前所选"),
        ("Export records in filter", "导出筛选内容"),
        ("extension", "扩展"),
        ("extensions", "扩展"),
        ("Family", "组"),
        ("Fi&les:", "文件(&L):"),
        ("Fil&ter:", "过滤(&T):"),
        (r"File %1\$s already exists.\n\n", r"文件 %1\$s 已经存在。\n\n"),
        (r"File %1\$s already exists.\nDo you want to overwrite it?",
         r"文件 %1\$s 已经存在。\n您想要覆盖它吗?"),
        (r"File %1\$s does not exist.", r"文件 %1\$s 不存在。"),
        ("File &name:", "文件名(&N):"),
        ("File &names:", "文件名(&N):"),
        ("Files of &type:", "文件类型(&T):"),
        ("Filter", "筛选"),
        ("Clear filters", "清除筛选"),
        ("Filter by cell's value", "使用单元格值筛选"),
        ("Font", "字体"),
        ("Font Selector", "字体选择器"),
        ("Font st&yle:", "字体样式(&Y):"),
        ("Fr", "五"),
        ("Grayscale", "灰度"),
        ("Green", "绿色"),
        ("Hex", "Hex"),
        ("Hi", "你好"),
        ("Hide column", "隐藏列"),
        ("Hide select rows", "隐藏所选行"),
        ("Hue", "色相"),
        ("ignore", "忽略"),
        ("Invalid data type", "无效数据类型"),
        (r"Invalid file name %1\$s.", r"无效的文件名 %1\$s。"),
        ("italic", "斜体"),
        ("Italic", "斜体"),
        ("Landscape", "横向"),
        ("Legal ", "合法的 "),
        ("Letter ", "Letter"),
        ("Log Files", "日志文件"),
        ("Mo", "一"),
        ("Move", "移动"),
        ("Move down", "下移"),
        ("Move to bottom", "移至底部"),
        ("Move to first", "移至第一"),
        ("Move to last", "移至最后"),
        ("Move to left", "移至左侧"),
        ("Move to right", "移至右侧"),
        ("Move to top", "移至顶部"),
        ("Move up", "上移"),
        ("New", "新增"),
        ("Next", "下一步"),
        ("No", "否"),
        ("normal", "正常"),
        ("Number cannot be greater than", "数字不能大于"),
        ("of", "of"),
        ("OK", "确定"),
        ("Ok", "确定"),
        ("ok", "确定"),
        ("Open", "打开"),
        ("Open Multiple Files", "打开多个文件"),
        ("Options", "设置"),
        ("Orientation", "方向"),
        ("Out of range", "超出范围"),
        ("Output", "输出"),
        ("overstrike", "overstrike"),
        ("P&aste", "粘贴(&A)"),
        ("Page", "页数"),
        ("Paper", "纸"),
        ("Portrait", "竖向"),
        ("Prev", "上一步"),
        ("Preview", "预览"),
        ("Previous", "以前的"),
        ("Print", "输出"),
        ("Printer", "打印机"),
        ("Red", "红色"),
        ("red", "红色"),
        ("Regular", "规则"),
        ("Remove", "移除"),
        ("Replace existing file?", "替换已有文件?"),
        ("Reset table", "重置表格"),
        ("retry", "重试"),
        ("Retry", "重试"),
        ("RGB", "RGB"),
        ("roman", ""),
        ("Sa", "六"),
        ("Sample", "范本"),
        ("Save As", "另存为"),
        ("Save To Log", "保存到日志"),
        ("Scale", "规模"),
        ("Search", "搜索"),
        ("Select a file to source", "选择一个来源文件"),
        ("Select Log File", "选择日志文件"),
        ("Should be of data type", "应为数据类型"),
        ("Show &Hidden Directories", "显示隐藏目录(&H)"),
        ("Show &Hidden Files and Directories", "显示隐藏文件和目录(&H)"),
        ("Show All", "显示全部"),
        ("Show only select rows", "只显示所选行"),
        ("Size", "大小"),
        ("Skip Messages", "跳过消息"),
        ("Slant", "倾斜"),
        ("Sort", "排序"),
        ("Sort Ascending", "顺序"),
        ("Sort Descending", "倒序"),
        ("Standard", "标准"),
        ("Stri&keout", "删除线(&K)"),
        ("Su", "日"),
        ("Submit", "上传"),
        ("Tcl for Windows", "适用于Windows的Tcl"),
        ("Tcl Scripts", "Tcl脚本"),
        ("Text Files", "文本文件"),
        ("Th", "四"),
        ("The quick brown fox jumps over the lazy dog.", "敏捷的棕色狐狸跳过懒惰的狗。"),
        ("Themed", "主题化"),
        ("Tu", "二"),
        ("underline", "下划线"),
        ("We", "三"),
        ("Weight", "重量"),
        ("yes", "确认"),
        ("Yes", "确认"),
    )
)

2-在程序中使用:

python 复制代码
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
from ttkbootstrap.tableview import Tableview
import tkinter as tk
# 导入语言设置
from ttkbootstrap.localization import MessageCatalog
# 导入全中文语言包
import localezhcn
导入本地化初始模块
from ttkbootstrap import localization



class YourApp:
    def __init__(self, root):
        """初始化材料价格表应用程序"""
        self.root = root
        self.root.title("程序名称")
        self.root.geometry("700x600")  # 增大窗口尺寸以适应新组件
        
        # 初始化UI
        self._create_widgets()
        self._load_data()
    
    def _create_widgets(self):
        """创建所有UI组件"""
        # 创建标题标签
        self.header_label = ttk.Label(
            self.root, 
            text="材料规格与价格表", 
            font=("SimHei", 16, "bold")
        )
        self.header_label.pack(pady=10)
        
        # 创建输入区域框架
        input_frame = ttk.LabelFrame(self.root, text="数据输入区", padding=10)
        input_frame.pack(fill=X, padx=10, pady=5)
        
        # 创建Text组件用于数据输入
        input_label = ttk.Label(input_frame, text="请输入数据(格式:规格\t材料\t单价,每行一条):")
        input_label.pack(anchor=W, pady=5)
        
        # 创建带有滚动条的Text组件
        text_frame = ttk.Frame(input_frame)
        text_frame.pack(fill=X)
        
        self.text_scrollbar = ttk.Scrollbar(text_frame)
        self.text_scrollbar.pack(side=RIGHT, fill=Y)
        
        self.data_text = tk.Text(
            text_frame, 
            height=10, 
            width=70, 
            wrap=WORD, 
            yscrollcommand=self.text_scrollbar.set, 
            font=("SimHei", 10)
        )
        self.data_text.pack(side=LEFT, fill=X, expand=YES)
        self.text_scrollbar.config(command=self.data_text.yview)
        
        # 创建更新按钮
        button_frame = ttk.Frame(input_frame)
        button_frame.pack(fill=X, pady=10)
        
        self.update_button = ttk.Button(
            button_frame, 
            text="更新表格数据", 
            command=self._update_table_from_text,
            bootstyle="primary"
        )
        self.update_button.pack(anchor=CENTER)
        
        # 创建框架来放置表格
        self.frame = ttk.Frame(self.root, padding=10)
        self.frame.pack(fill=BOTH, expand=YES)
        
        # 定义表格列,不设置固定宽度让表格自适应填充
        coldata = [
            {"text": "规格"},
            {"text": "材料"},
            {"text": "单价 (元)"}
        ]
        
        # 创建ttkbootstrap的Tableview表格
        self.table = Tableview(
            self.frame, 
            coldata=coldata,
            paginated=False,
            searchable=False,
            bootstyle="primary"
            # stripecolor=("#f0f0f0", "#e0e0e0")
        )
        
        # 手动设置表格操作按钮的中文文本(如果有)
        # Tableview组件可能会根据系统locale自动调整语言
        
        # 放置表格
        self.table.pack(fill=BOTH, expand=YES, padx=5, pady=5)
    
    def _update_table_from_text(self):
        """从文本框读取数据并更新表格"""
        try:
            # 清空现有表格数据
            self.table.delete_rows()
            
            # 获取文本框内容
            text_content = self.data_text.get("1.0", END)
            
            # 解析数据
            lines = text_content.strip().split('\n')
            
            # 跳过标题行(如果有)
            if lines and '规格' in lines[0] and '材料' in lines[0] and '单价' in lines[0]:
                lines = lines[1:]
            
            # 处理每一行数据
            for line in lines:
                line = line.strip()
                if line:
                    # 使用制表符或空格分割数据
                    parts = [part.strip() for part in line.split('\t') if part.strip()]
                    if len(parts) < 3:
                        # 如果制表符分割不够,尝试用空格分割
                        parts = [part.strip() for part in line.split() if part.strip()]
                    
                    if len(parts) >= 3:
                        # 尝试将价格转换为浮点数
                        try:
                            price = float(parts[2])
                            # 将数据插入表格
                            self.table.insert_row(values=(parts[0], parts[1], price))
                        except ValueError:
                            # 如果价格无法转换为浮点数,仍然插入(显示原始文本)
                            self.table.insert_row(values=(parts[0], parts[1], parts[2]))
        except Exception as e:
            # 简单的错误处理
            print(f"更新表格时出错: {e}")
    
    def _load_data(self):
        """加载材料数据到表格中,并填充到文本框"""
        material_data = [
            ("C12E", "螺纹钢", 3248.2037),
            ("C14E", "螺纹钢", 3215.4427),
            ("C16E", "螺纹钢", 3159.9783),
            ("C18E", "螺纹钢", 3141.5592),
            ("C20E", "螺纹钢", 3107.7218),
            ("C22E", "螺纹钢", 3130.7664),
            ("C25E", "螺纹钢", 3177.2595),
            ("C28E", "螺纹钢", 3216.6662),
            ("C32E", "螺纹钢", 3206.164),
            ("C8", "螺纹钢", 3462.1064),
            ("C10E", "螺纹钢", 3502.6609)
        ]
        
        # 填充到表格
        for item in material_data:
            self.table.insert_row(values=item)
        
        # 填充到文本框,添加标题行
        self.data_text.delete("1.0", END)
        self.data_text.insert(END, "规格\t材料\t单价\n")
        for item in material_data:
            self.data_text.insert(END, f"{item[0]}\t{item[1]}\t{item[2]}\n")

if __name__ == "__main__":
    # 先创建应用程序窗口
    root_window = ttk.Window(themename="cosmo")
    # 在应用程序窗口创建完成后再初始化语言包,否则会额外弹出一个tk窗口
    # 然后进行本地化设置,确保使用已创建的窗口
    localization.initialize_localities()
    MessageCatalog.locale("zh_cn_all")
    
    # 实例化应用程序类并传入root窗口
    app = YourApp(root_window)
    
    # 启动应用程序主循环
    root_window.mainloop()
相关推荐
2603_965148118 小时前
如何解析JSON数据?API返回的商品信息处理教程
开发语言·数据库·python·自动化·json·api
jufeng13079 小时前
【系列:手搓自主 AI Agent:Hermes 架构原理剖析 · 第 8 篇】
python·ai agent·配置系统
circuitsosk9 小时前
跨境电商智能化实战:AI如何赋能客服自动回复、广告智能投放与供应链预测
大数据·人工智能·python·langchain·智能客服
2601_9563198810 小时前
2026年零基础学量化:从看懂示例到写清条件和动作
人工智能·python
过期的秋刀鱼!11 小时前
LangChain-D1-模型的工作流程
人工智能·python·langchain
萤火工厂目视化设计11 小时前
智能制造与企业文化目视化浪潮下:中小工厂的机遇与挑战
python·制造
DeepVisionary12 小时前
从GPT-5.6 Sol的Ultrafast模式看推理速度竞赛:750 token/秒背后,Cerebras的晶圆级生意
python·自动化
leisoo809713 小时前
财报数据怎么排雷本地化Python构建财务异常预警系统
人工智能·python·算法
小柯南敲键盘13 小时前
跨马翻译:跨境电商批量图片翻译与视频字幕一站式工具
人工智能·python·音视频
卷无止境13 小时前
FastAPI Guard 全解析,从概念到工程落地的实战指南
后端·python