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

Tkinter(ttkbootstrap)跨屏幕字体大小不一致问题求助

解决ttkbootstrap文本框打包后缩放异常的问题

核心原因

这类问题大多是高DPI屏幕适配导致的:ttkbootstrap多数控件会自动跟随系统缩放,但文本框(Text/Entry)的字体未同步适配,加上PyInstaller打包时默认未开启高DPI感知,导致其他电脑上显示错位。


解决方案

1. 代码内开启高DPI感知

在程序最开头添加Windows系统DPI感知配置,让程序识别屏幕缩放比例:

import ctypes
# 设置为每显示器DPI感知(适配多屏不同缩放)
ctypes.windll.shcore.SetProcessDpiAwareness(2)
# 获取系统缩放比例(96为默认DPI)
dpi = ctypes.windll.user32.GetDpiForSystem()
scale_factor = dpi / 96

2. 强制文本框字体跟随缩放

手动计算缩放后的字体大小,给文本框指定适配后的字体:

import ttkbootstrap as ttkb

root = ttkb.Window(themename="darkly")
root.geometry("800x600")
root.resizable(False, False)

# 基于缩放比例设置字体大小(示例默认10号字体)
text_font = ("Segoe UI", int(10 * scale_factor))
# 给文本框绑定适配字体
text_box = ttkb.Text(root, font=text_font)
text_box.pack(fill="both", expand=True, padx=10, pady=10)

root.mainloop()

3. 全局统一控件样式

通过ttkbootstrap的Style对象,批量设置所有文本类控件的字体,避免逐个配置:

style = ttkb.Style()
# 统一设置Text和Entry的缩放字体
style.configure("TText", font=("Arial", int(10*scale_factor)))
style.configure("TEntry", font=("Arial", int(10*scale_factor)))

# 使用配置后的样式创建控件
text = ttkb.Text(root, style="TText")
entry = ttkb.Entry(root, style="TEntry")

4. 打包时添加高DPI清单文件

创建一个dpi_aware.manifest文件,内容如下:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  <application xmlns="urn:schemas-microsoft-com:asm.v3">
    <windowsSettings>
      <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/PM</dpiAware>
      <dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2, PerMonitor</dpiAwareness>
    </windowsSettings>
  </application>
</assembly>

打包时带上该清单:

pyinstaller --onefile --windowed --manifest=dpi_aware.manifest 你的脚本名.py

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 07:47:18