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