python fontsize,Python Programmatically Change Console font size

原文:

I found the code below which is supposed to programmatically change the console font size. I'm on Windows 10.

However, whatever values I tweak, I can't seem to get any control over the font size, and also for some reason the console which gets opened when I run this script is very wide.

I have no idea how ctypes works - all I want is to modify the size of the console font from inside Python.

Any actual working solutions?

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")

# Answer 1

4d350fd91e33782268f371d7edaa8a76.png

I changed your code "a bit".

code.py:

#!/usr/bin/env python

import sys

from ctypes import POINTER, WinDLL, Structure, sizeof, byref

from ctypes.wintypes import BOOL, SHORT, WCHAR, UINT, ULONG, DWORD, HANDLE

LF_FACESIZE = 32

STD_OUTPUT_HANDLE = -11

class COORD(Structure):

_fields_ = [

("X", SHORT),

("Y", SHORT),

]

class CONSOLE_FONT_INFOEX(Structure):

_fields_ = [

("cbSize", ULONG),

("nFont", DWORD),

("dwFontSize", COORD),

("FontFamily", UINT),

("FontWeight", UINT),

("FaceName", WCHAR * LF_FACESIZE)

]

kernel32_dll = WinDLL("kernel32.dll")

get_last_error_func = kernel32_dll.GetLastError

get_last_error_func.argtypes = []

get_last_error_func.restype = DWORD

get_std_handle_func = kernel32_dll.GetStdHandle

get_std_handle_func.argtypes = [DWORD]

get_std_handle_func.restype = HANDLE

get_current_console_font_ex_func = kernel32_dll.GetCurrentConsoleFontEx

get_current_console_font_ex_func.argtypes = [HANDLE, BOOL, POINTER(CONSOLE_FONT_INFOEX)]

get_current_console_font_ex_func.restype = BOOL

set_current_console_font_ex_func = kernel32_dll.SetCurrentConsoleFontEx

set_current_console_font_ex_func.argtypes = [HANDLE, BOOL, POINTER(CONSOLE_FONT_INFOEX)]

set_current_console_font_ex_func.restype = BOOL

def main():

# Get stdout handle

stdout = get_std_handle_func(STD_OUTPUT_HANDLE)

if not stdout:

print("{:s} error: {:d}".format(get_std_handle_func.__name__, get_last_error_func()))

return

# Get current font characteristics

font = CONSOLE_FONT_INFOEX()

font.cbSize = sizeof(CONSOLE_FONT_INFOEX)

res = get_current_console_font_ex_func(stdout, False, byref(font))

if not res:

print("{:s} error: {:d}".format(get_current_console_font_ex_func.__name__, get_last_error_func()))

return

# Display font information

print("Console information for {:}".format(font))

for field_name, _ in font._fields_:

field_data = getattr(font, field_name)

if field_name == "dwFontSize":

print(" {:s}: {{X: {:d}, Y: {:d}}}".format(field_name, field_data.X, field_data.Y))

else:

print(" {:s}: {:}".format(field_name, field_data))

while 1:

try:

height = int(input("\nEnter font height (invalid to exit): "))

except:

break

# Alter font height

font.dwFontSize.X = 10 # Changing X has no effect (at least on my machine)

font.dwFontSize.Y = height

# Apply changes

res = set_current_console_font_ex_func(stdout, False, byref(font))

if not res:

print("{:s} error: {:d}".format(set_current_console_font_ex_func.__name__, get_last_error_func()))

return

print("OMG! The window changed :)")

# Get current font characteristics again and display font size

res = get_current_console_font_ex_func(stdout, False, byref(font))

if not res:

print("{:s} error: {:d}".format(get_current_console_font_ex_func.__name__, get_last_error_func()))

return

print("\nNew sizes X: {:d}, Y: {:d}".format(font.dwFontSize.X, font.dwFontSize.Y))

if __name__ == "__main__":

print("Python {:s} on {:s}\n".format(sys.version, sys.platform))

main()

Notes:

CTypes allows low level access similar to C (only the syntax is Python)

In order to avoid setting invalid values, it's used in conjunction with its counterpart: [MS.Docs]: GetCurrentConsoleFontEx function. Call that function in order to populate the CONSOLE_FONT_INFOEX structure, then modify only the desired values

There are "simpler" functions (e.g. [MS.Docs]: GetCurrentConsoleFont function or [MS.Docs]: GetConsoleFontSize function), but unfortunately there are no corresponding setters

The ctypes.wintypes constants (which reference the standard CTypes types) are used (to give the code a Win like flavor)

It is very (almost painfully) long (also because I've added proper error handling)

An alternative, as suggested in one of the answers of [SO]: Change console font in Windows (where you copied the code from), would be to install a 3rd-party module (e.g. [GitHub]: mhammond/pywin32 - Python for Windows (pywin32) Extensions which is a Python wrapper over WINAPIs) which would require less code to write because the bridging between Python and C would be already implemented, and probably the above functionality could be accomplished in just a few lines

As I commented in the code, setting COORD.X seems to be ignored. But it's automatically set when setting COORD.Y (to a value close to COORD.Y // 2 - probably to preserve the aspect ratio). On my machine (Win 10 pc064) the default value is 16. You might want to set it back at the end, to avoid leaving the console in a "challenged" state (apparently, Win adjusts cmd window size, to be (sort of) in sync with the font size):

H7VA6.jpg

# Answer 2

It's not a pure python problem, but covers Windows API.

Look at the documentation of CONSOLE_FONT_INFOEX structure. There is a COORD member on it for width and height of each character.

To change console font size, you can give these attributes as a proper value:

font.dwFontSize.X = 11

font.dwFontSize.Y = 18

# Answer 3

For anyone in the future who wants to use the console as a method of displaying (black and white) images or just getting the smallest possible font size, this is the modified answer code I used. I found a height and width of 2px was the best smallest size, but be cautious, all sizes distort the picture, some more than others. As the font, I use the only "rasterfont" that's available. (Personally I had massive problems getting this to work, not sure why tho... and this is NOT the same as the accepted answer)

def changeFontSize(size=2): #Changes the font size to *size* pixels (kind of, but not really. You'll have to try it to chack if it works for your purpose ;) )

from ctypes import POINTER, WinDLL, Structure, sizeof, byref

from ctypes.wintypes import BOOL, SHORT, WCHAR, UINT, ULONG, DWORD, HANDLE

LF_FACESIZE = 32

STD_OUTPUT_HANDLE = -11

class COORD(Structure):

_fields_ = [

("X", SHORT),

("Y", SHORT),

]

class CONSOLE_FONT_INFOEX(Structure):

_fields_ = [

("cbSize", ULONG),

("nFont", DWORD),

("dwFontSize", COORD),

("FontFamily", UINT),

("FontWeight", UINT),

("FaceName", WCHAR * LF_FACESIZE)

]

kernel32_dll = WinDLL("kernel32.dll")

get_last_error_func = kernel32_dll.GetLastError

get_last_error_func.argtypes = []

get_last_error_func.restype = DWORD

get_std_handle_func = kernel32_dll.GetStdHandle

get_std_handle_func.argtypes = [DWORD]

get_std_handle_func.restype = HANDLE

get_current_console_font_ex_func = kernel32_dll.GetCurrentConsoleFontEx

get_current_console_font_ex_func.argtypes = [HANDLE, BOOL, POINTER(CONSOLE_FONT_INFOEX)]

get_current_console_font_ex_func.restype = BOOL

set_current_console_font_ex_func = kernel32_dll.SetCurrentConsoleFontEx

set_current_console_font_ex_func.argtypes = [HANDLE, BOOL, POINTER(CONSOLE_FONT_INFOEX)]

set_current_console_font_ex_func.restype = BOOL

stdout = get_std_handle_func(STD_OUTPUT_HANDLE)

font = CONSOLE_FONT_INFOEX()

font.cbSize = sizeof(CONSOLE_FONT_INFOEX)

font.dwFontSize.X = size

font.dwFontSize.Y = size

set_current_console_font_ex_func(stdout, False, byref(font))

### 回答1: 你可以使用tkinter库来设置Python GUI中的字体大小。以下是一个简单的示例代码: ```python import tkinter as tk root = tk.Tk() # 设置字体 my_font = ("Helvetica", 16) # 创建标签并设置字体 label = tk.Label(root, text="Hello World!", font=my_font) label.pack() root.mainloop() ``` 在上面的代码中,我们使用`my_font`变量定义了一个字体,然后将其用于创建标签。你可以根据自己的需要更改字体名称和大小。 ### 回答2: Python中的fontsize是指字体的大小。在Python中,我们可以使用各种方法来设置和控制字体的大小。 在Python的图形用户界面(GUI)库中,例如Tkinter和PyQt,我们可以使用相关的函数和方法来设置文本的字体大小。可以使用类似于font.sizefont.configure函数来设置字体的大小。 在使用Python进行文本处理时,可以使用字符串的相关方法来设置字体大小。例如,我们可以使用字符串的format方法和HTML标签来设置HTML文档中的字体大小。 另外,Python还提供了各种绘图库,例如Matplotlib和Seaborn,可以用于在图表中设置字体的大小。这些库通常会提供相应的API或参数来设置图表中文本的字体大小。 总而言之,通过使用Python的相关库和函数,我们可以基于不同的应用场景和需求来设置和控制字体的大小。无论是在GUI应用程序中设置文本的字体大小,还是在文本处理中设置文本的字体大小,或者在绘图中设置图表的字体大小,Python提供了丰富的功能和选项。 ### 回答3: Python中可以使用matplotlib库来设置字体大小。可以通过设置figure对象和axes对象的属性来改变字体大小。具体的代码如下所示: ```python import matplotlib.pyplot as plt # 创建一个图形对象 fig = plt.figure() # 在图形对象上创建一个子图对象 ax = fig.add_subplot(111) # 在子图对象上绘制一个文本 ax.text(0.5, 0.5, 'Hello World!', fontsize=14) # 设置子图对象的字体大小 ax.set_title('Title', fontsize=16) ax.set_xlabel('X Label', fontsize=12) ax.set_ylabel('Y Label', fontsize=12) # 显示图形 plt.show() ``` 在上述代码中,我们通过调用`text`函数在子图对象上绘制了一个文本,并通过`fontsize`参数设置了字体大小为14。然后使用`set_title`、`set_xlabel`和`set_ylabel`方法设置了子图对象的标题、x轴和y轴的标签的字体大小。 除了使用matplotlib库之外,还可以使用其他的库来设置字体大小,比如tkinter库中的Label控件、pygame库中的font模块等。不同库的具体用法可能会有所差异,但都提供了相应的接口来改变字体大小。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值