我发现下面的代码应该是以编程方式改变控制台字体大小。我在Windows 10上。
然而,无论我调整什么值,我似乎都不能控制字体大小,而且由于某种原因,当我运行这个脚本时打开的控制台非常宽。
我不知道ctypes是如何工作的--我只想从Python内部修改控制台字体的大小。
有什么切实可行的解决办法吗?
import ctypes
LF_FACESIZE = 32
STD_OUTPUT_HANDLE = -11
class COORD(ctypes.Structure):
_fields_ = [("X", ctypes.c_short), ("Y", ctypes.c_short)]
class CONSOLE_FONT_INFOEX(ctypes.Structure):
_fields_ = [("cbSize", ctypes.c_ulong),
("nFont", ctypes.c_ulong),
("dwFontSize", COORD),
("FontFamily", ctypes.c_uint),
("FontWeight", ctypes.c_uint),
("FaceName", ctypes.c_wchar * LF_FACESIZE)]
font = CONSOLE_FONT_INFOEX()
font.cbSize = ctypes.sizeof(CONSOLE_FONT_INFOEX)
font.nFont = 12
font.dwFontSize.X = 11
font.dwFontSize.Y = 18
font.FontFamily = 54
font.FontWeight = 400
font.FaceName = "Lucida Console"
handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
ctypes.windll.kernel32.SetCurrentConsoleFontEx(
handle, ctypes.c_long(False), ctypes.pointer(font))
print("Foo")
3条答案
按热度按时间vcirk6k61#
首先,检查[SO]: C function called from Python via ctypes returns incorrect value (@CristiFati's answer),以了解使用 CTypes(调用函数)时的常见陷阱。
我把你的密码改了“一点点”。
备注:
*请注意,所有引用的 WinAPI 函数都已过时
COORD.Y // 2
的值-可能是为了保持纵横比)。(Win 10 pc 064 )与当前所选字体匹配时,默认值为16。您可能需要在最后将其设置回来,为了避免控制台处于“受挑战”状态(显然,Win 会调整 Cmd 窗口大小,使其(某种程度上)与字体大小 * 同步 *):vsmadaxz2#
这不是一个纯粹的python问题,但涵盖了Windows API。
请看CONSOLE_FONT_INFOEX结构的文档,其中有一个COORD成员,用于表示每个字符的宽度和高度。
要更改控制台字体大小,可以将这些属性作为适当的值:
参考:Change console font in Windows
xwbd5t1u3#
对于将来希望使用控制台作为显示方法的任何人(白色)图像或只是得到尽可能小的字体大小,这是我使用的修改答案代码。我发现高度和宽度为2px是最好的最小大小,但要谨慎,所有大小都会扭曲图片,有些比其他更多。作为字体,我使用唯一可用的“rasterfont”。(就我个人而言,我有很大的问题,让这个工作,不知道为什么...这是不一样的公认答案)