hanjie-chen 2022-08-08 22:34 采纳率: 0%
浏览 14

如何获得单个字符的像素宽度

我在学习Python的时候,看到如下这段代码,来自《Python基础教程》第三版

sentence = input("Sentence: ")

screen_width = 80
text_width = len(sentence)
box_width = text_width + 6
left_margin = (screen_width - box_width) // 2

print()
print(' '*left_margin + '+' + '-'*(box_width - 2) + '+')
print(' '*left_margin + '| ' + ' '*text_width + '   |')
print(' '*left_margin + '| ' + sentence + '   |')
print(' '*left_margin + '| ' + ' '*text_width + '   |')
print(' '*left_margin + '+' + '-'*(box_width - 2) + '+')
print()

这段代码的运行结果类似于下列的情况:

img

我想把这段代码改造成在屏幕中央居中显示一个方框和句子,于是我就想计算screen_width的值,我的计算公式为:屏幕的像素宽度/单个字符的像素宽度
但是我不知道单个字符的像素应该如何获取,请问有什么方式能让我获取到单个的字符像宽度吗?
以下是我修改过的代码:

import tkinter

sentence = input("Sentence: ")

# 如何计算single_word_length?
# 其中tkinter.Tk().winfo_screenwidth()获得了屏幕的像素宽度
screen_width = tkinter.Tk().winfo_screenwidth() // single_word_length
text_width = len(sentence)
box_width = text_width + 6
left_margin = (screen_width - box_width) // 2

print()
print(' '*left_margin + '+' + '-'*(box_width - 2) + '+')
print(' '*left_margin + '| ' + ' '*text_width + '   |')
print(' '*left_margin + '| ' + sentence + '   |')
print(' '*left_margin + '| ' + ' '*text_width + '   |')
print(' '*left_margin + '+' + '-'*(box_width - 2) + '+')
print()
  • 写回答

1条回答 默认 最新

报告相同问题?

问题事件

  • 创建了问题 8月8日

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)