终端打印方块异常:Unicode █显示为矩形的解决求助
Problem Description
I'm trying to generate a QR code in the terminal using the Unicode character █ (U+2588, solid black square), but it's displaying as a rectangle instead of a square. I'm using the DejaVu Sans Mono font and working in a Python 3 environment. Here's my relevant code:
import sys def print_cmd_qr(qrText, white=u'/u2588', black=' ', enableCmdQR=True): blockCount = int(enableCmdQR) if abs(blockCount) == 0: blockCount = 1 white *= abs(blockCount) if blockCount < 0: white, black = black, white sys.stdout.write(' '*50 + '\r') sys.stdout.flush() qr = qrText.replace('0', white).replace('1', black) sys.stdout.write(qr) sys.stdout.flush()
Solution
Let's break down the fixes and adjustments you can make to get square blocks:
Fix the Unicode escape code first
You've got a small typo in your code:u'/u2588'uses a forward slash instead of a backslash. It should beu'\u2588'(or just'\u2588'in Python 3, since strings are Unicode by default). This mistake might be the root cause of your incorrect character display.Tweak your terminal font or settings
WhileDejaVu Sans Monosupports U+2588, some terminal environments or font versions render it with a non-square aspect ratio:- Try switching to a terminal-optimized monospaced font like
Fira Code,Consolas(Windows), orMenlo(macOS) — these are built to keep block characters strictly square for use cases like terminal QR codes or ASCII art. - If you want to stick with
DejaVu Sans Mono, make sure you have the full, updated version installed (stripped-down versions may lack proper Unicode rendering). - Check your terminal's display settings: most let you adjust line height and character width. Set the line height to match the character width (a 1:1 ratio) to stop the block from stretching vertically into a rectangle.
- Try switching to a terminal-optimized monospaced font like
Use a modern terminal emulator
Older terminals (like Windows' classic Command Prompt) have spotty Unicode support. Switch to a modern option like Windows Terminal (Windows), iTerm2 (macOS), or Konsole (Linux) — these handle Unicode block characters far more reliably.
内容的提问来源于stack exchange,提问作者notyeat

