杰瑞科技汇

Python label字体如何设置与调整?

Of course! In Python, changing the font of a label is a common task, but the exact method depends on the GUI library you are using. The two most popular libraries for this are Tkinter (which comes built-in with Python) and PyQt/PySide.

Python label字体如何设置与调整?-图1
(图片来源网络,侵删)

Here’s a detailed guide covering both, plus a quick look at other libraries like Kivy and Matplotlib.


Tkinter (Built-in, Standard Library)

Tkinter is the most straightforward option since it's included with Python. You can change the font of a Label widget using the font parameter.

Method 1: Using the font Parameter Directly

You can specify the font family, size, and weight as a tuple passed to the font option.

import tkinter as tk
from tkinter import font
# Create the main window
root = tk.Tk()"Tkinter Label Font")
root.geometry("400x200")
# --- Option A: Using a tuple ---
# The format is: (font_family, size, weight)
# weight can be 'normal', 'bold', 'roman', 'italic'
label1 = tk.Label(
    root,
    text="This is a bold, 16pt Arial label.",
    font=("Arial", 16, "bold")
)
# --- Option B: Using named font (more reusable) ---
# First, define a named font in the font manager
custom_font = font.Font(family="Helvetica", size=14, weight="normal")
# Then, use that font object by name
label2 = tk.Label(
    root,
    text="This uses a reusable 'CustomFont'.",
    font=custom_font # Pass the font object
)
# --- Option C: Modifying an existing font ---
# Create a font based on the default, but change some properties
default_font = font.nametofont("TkDefaultFont") # Get the default system font
modified_font = default_font.copy()
modified_font.configure(size=12, slant="italic")
label3 = tk.Label(
    root,
    text="This is the default font, but 12pt and italic.",
    font=modified_font
)
# Pack the labels to display them
label1.pack(pady=10)
label2.pack(pady=10)
label3.pack(pady=10)
# Start the Tkinter event loop
root.mainloop()

Common Font Properties in Tkinter:

  • family: The name of the font (e.g., "Times New Roman", "Courier", "Verdana").
  • size: The size of the font in points.
  • weight: "normal" or "bold".
  • slant: "roman" (default) or "italic".
  • underline: 0 (no underline) or 1 (underline).
  • overstrike: 0 (no overstrike) or 1 (overstrike).

PyQt / PySide (Qt for Python)

PyQt and PySide are powerful, modern GUI toolkits. They use a QFont object to define fonts.

Python label字体如何设置与调整?-图2
(图片来源网络,侵删)

Method: Creating a QFont Object

You create an instance of QFont, set its properties, and then assign it to the setFont method of the label.

# You need to install it first: pip install PySide6
# Or for PyQt: pip install PyQt6
from PySide6.QtWidgets import QApplication, QMainWindow, QLabel, QVBoxLayout, QWidget
from PySide6.QtGui import QFont
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("PyQt/PySide Label Font")
        self.setGeometry(100, 100, 400, 200)
        # Create a central widget and layout
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        layout = QVBoxLayout(central_widget)
        # --- Option A: Create a QFont object ---
        font1 = QFont()
        font1.setFamily("Arial") # Or "Times New Roman", "Verdana", etc.
        font1.setPointSize(16)
        font1.setBold(True)
        label1 = QLabel("This is a bold, 16pt Arial label.")
        label1.setFont(font1)
        # --- Option B: Use a system application font ---
        # This is good for consistency with the OS
        font2 = self.font() # Get the default application font
        font2.setPointSize(14)
        font2.setItalic(True)
        label2 = QLabel("This is the default app font, but 14pt and italic.")
        label2.setFont(font2)
        # --- Option C: Using a QFontDatabase for custom fonts ---
        # (Useful if you have .ttf or .otf files)
        # from PySide6.QtGui import QFontDatabase
        # id = QFontDatabase.addApplicationFont("path/to/your/font.ttf")
        # family = QFontDatabase.applicationFontFamilies(id)[0]
        # font3 = QFont(family, 12)
        # label3 = QLabel("This uses a custom font file.")
        # label3.setFont(font3)
        layout.addWidget(label1)
        layout.addWidget(label2)
        # layout.addWidget(label3) # Uncomment if using custom font
        layout.addStretch() # Pushes labels to the top
if __name__ == '__main__':
    app = QApplication([])
    window = MainWindow()
    window.show()
    app.exec()

Common QFont Methods:

  • setFamily(str): Sets the font family name.
  • setPointSize(int): Sets the font size.
  • setBold(bool): Sets bold on/off.
  • setItalic(bool): Sets italic on/off.
  • setUnderline(bool): Sets underline on/off.
  • setWeight(int): Sets the font weight (e.g., QFont.Bold, QFont.Light).

Other Libraries

Kivy

Kivy uses a declarative language in its KV files, which is often preferred for styling.

Python File (main.py):

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
class FontApp(App):
    def build(self):
        # The font properties are set in the KV file
        layout = BoxLayout(orientation='vertical', padding=20, spacing=20)
        # The 'font_name' in the Label must match the name in the KV file
        label1 = Label(text="This is a Roboto, 24pt, bold label.")
        label2 = Label(text="This is a Verdana, 18pt, italic label.")
        layout.add_widget(label1)
        layout.add_widget(label2)
        return layout
if __name__ == '__main__':
    FontApp().run()

KV File (font.kv):

#:kivy 1.11.1
# Register a font from a file (e.g., a .ttf file)
# <Roboto>:
#     font_name: 'Roboto-Regular.ttf'
# If you don't have a file, Kivy comes with some defaults like 'Roboto'
<Label>:
    font_size: '18sp' # Default size for all labels
# Style specific labels using ids or classes
# Note: We are using the 'Roboto' font that comes with Kivy
# For custom fonts, you would use the registered name from above.
# The 'bold' and 'italic' properties are on the Label widget itself.
# The font file itself must have the bold/italic versions.
Label:
    id: label1
    font_size: '24sp'
    bold: True
    # For Kivy's default Roboto, you can specify the style
    # text_size: self.size
    # halign: 'center'
Label:
    id: label2
    font_size: '18sp'
    italic: True
    font_name: 'Verdana' # Kivy will try to find this font on the system

Matplotlib (For Plotting Labels)

If you're talking about labels on a plot (e.g., axis titles, tick labels), you use the fontdict parameter or set_fontsize() method.

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.set_title("Plot Title with Custom Font", fontsize=16, fontweight='bold')
ax.set_xlabel("X-Axis Label", fontsize=12, style='italic')
ax.set_ylabel("Y-Axis Label", fontsize=12)
# You can also set properties for all text elements at once
plt.rcParams['font.family'] = 'serif'
plt.rcParams['font.size'] = 10
ax.text(0.5, 0.5, "A text annotation", ha='center', va='center')
plt.show()

Summary Table

Library Method Example Snippet
Tkinter font parameter with a tuple or Font obj font=("Arial", 14, "bold") or font=my_font_object
PyQt/PySide Create a QFont object and use setFont() font = QFont("Arial", 14); label.setFont(font)
Kivy Use KV file properties (font_size, bold) In KV: <Label>: font_size: '20sp'; bold: True
Matplotlib fontsize, fontweight etc. in plotting functions ax.set_title("Title", fontsize=16, fontweight='bold')
分享:
扫描分享到社交APP
上一篇
下一篇