Tkinter 6 Label

本文详细介绍了如何在Tkinter中使用ttk.Label组件,包括设置文本、添加图片、定制字体、位置布局(如compound选项)以及调整其他样式属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Label可以显示文本,也可以用来展示图片,用法如下:

label = ttk.Label(master, **options)

Label可使用的option如下:

  • anchor:当label内容比width小时,anchor取tk.W,tk.CENTER,tk.E用于其对齐
  • background:背景色
  • class_:自定义一个class名字以定义label外观样式
  • compound:文本与图片共同展示时,文本与图片的排列方式
  • cursor:光标样式
  • font:字体
  • foreground:设置字体颜色
  • image:图片
  • justify:tk.LEFT,tk.CENTER,tk.RIGHT
  • padding:label组件的padding
  • relief:取raised\flat\sunken\groove\ridge,设置label框的样式
  • style:自定义样式
  • takefocus:默认为False,label不被take focus。
  • text:label之文本
  • textvariable:StringVar变量,text将被自动重载此值。
  • underline:指定某个字符添加下划线
  • width:
  • wraplength:长文本分割
import tkinter as tk
from tkinter.ttk import Label

root = tk.Tk()
root.geometry('300x200')
root.resizable(False, False)
root.title('Label Widget Demo')

# show a label
label = Label(root, text='This is a label')
label.pack(ipadx=10, ipady=10)

root.mainloop()

添加字体设置,如下:

import tkinter as tk
from tkinter import ttk


root = tk.Tk()
root.geometry('300x200')
root.resizable(False, False)
root.title('Label Widget Demo')

# label with a specific font
label = ttk.Label(
    root,
    text='A Label with the Helvetica font',
    font=("Helvetica", 14))

label.pack(ipadx=10, ipady=10)

root.mainloop()

label中展示图片

import tkinter as tk
from tkinter import ttk

# create the root window
root = tk.Tk()
root.geometry('300x200')
root.resizable(False, False)
root.title('Label Widget Image')

# display an image label
photo = tk.PhotoImage(file='./assets/python.png')
image_label = ttk.Label(
    root,
    image=photo,
    padding=5
)
image_label.pack()

root.mainloop()

文本和图片一起的话,使用compound来设置图片相对文本的位置。如top表明图片在文本之上,compound可以取如下值 :top、bottom、left、right、none(默认值:如果有图片则显示图片,否则显示文本)、text(显示文本)、image(显示图片而非文本)

import tkinter as tk
from tkinter import ttk

# create the root window
root = tk.Tk()
root.geometry('300x200')
root.resizable(False, False)
root.title('Label Widget Image')

# display an image label
photo = tk.PhotoImage(file='./assets/python.png')
image_label = ttk.Label(
    root,
    image=photo,
    text='Python',
    compound='top'
)
image_label.pack()

root.mainloop()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值