我在学习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()
这段代码的运行结果类似于下列的情况:
我想把这段代码改造成在屏幕中央居中显示一个方框和句子,于是我就想计算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()