欢迎回来!
上一篇我们对Label组件进行了简单的认识,那么在这一篇我们将继续对Label组件进行进一步的熟悉。
1. 改变文字的前景色与后景色
最好使用Windows自带的颜色
原代码:
fg:前景色,字体颜色
bg:背景色
fg报错的,可以试试用十六进制的颜色,比如天依蓝 #66ccff
from tkinter import *
root = Tk()
Label(root,bg = 'black',fg = 'red',text = " i am a XUATer").pack()
'''直接输入对应颜色英文即可'''
Label(root,bg = 'yellow',fg = 'gray',text = " i am a XUATer").pack()
Label(root,bg = 'green',fg = 'white',text = " i am a XUATer").pack()
root.mainloop()
2.设置文字的位置,对齐方式
padx: 距离x轴的位置
pady: 距离y轴的位置
width: 宽度
height: 高度
wraplength: 指定多少单位后开始换行
justify: 指定多行的对齐方式
ahchor: 指定文本(text)或图像(bitmap/image)在Label中的显示位置
可用的值:
e
w
n
s
ne
se
sw
sn
center
布局如下图
nw n ne
w center e
sw s se
————————————————
from tkinter import *
root = Tk()
Label(root,
bg = 'black',
fg = 'red',
text = "XUATer",
width = 60,
height = 5,
'''文本左对齐,居中'''
justify = LEFT).pack()
Label(root,
bg = 'yellow',
fg = 'gray',
text = "XUATer",
width = 60,
height = 5,
'''文本居中对齐,位于左'''
anchor = 'w').pack()
Label(root,
bg = 'green',
fg = 'white',
text = "XUATer",
width = 60,
height = 5,
'''文本居中对齐,位于右'''
anchor = 'e').pack()
root.mainloop()
多行字符串对齐方式
from tkinter import *
root = Tk()
Label(root,
bg = 'yellow',
fg = 'gray',
text = "i\nXUATer",
width = 60,
height = 5,
'''文字左对齐,居中'''
justify = LEFT
).pack()
Label(root,
bg = 'yellow',
fg = 'gray',
text = "i\nXUATer",
width = 60,
height = 5,
'''文字右对齐,居中'''
justify = RIGHT
).pack()
Label(root,
bg = 'yellow',
fg = 'gray',
text = "i\nXUATer",
width = 60,
height = 5,
'''文字左对齐,居左'''
justify = LEFT,
anchor = 'w'
).pack()
Label(root,
bg = 'yellow',
fg = 'gray',
text = "i\nXUATer",
width = 60,
height = 5,
'''文字左对齐,居右'''
justify = LEFT,
anchor = 'e'
).pack()
root.mainloop()
输出如下:
3.引入图片
compound: 指定文本(text)与图像(bitmap/image)是如何在Label上显示。可以使用的值:
left: 图像居左
right: 图像居右
top: 图像居上
bottom:图像居下
center:文字覆盖在图像上
from tkinter import *
root = Tk()
photo = 'error'
#图像居下
Label(root,text = 'botton',compound = 'bottom',bitmap = photo).pack()
#图像居上
Label(root,text = 'top',compound = 'top',bitmap = photo).pack()
#图像居右
Label(root,text = 'right',compound = 'right',bitmap =photo).pack()
#图像居左
Label(root,text = 'left',compound = 'left',bitmap = photo).pack()
#文字覆盖在图像上
Label(root,text = 'center',compound = 'center',bitmap= photo).pack()
#消息循环
root.mainloop()
运行结果如下:
上面我们使用了电脑自带的位图,同样地我们也可以使用自己喜欢的图片
from tkinter import *
root = Tk()
textLabel = Label(root,
text = "听说你在偷看我?\n喵~~~",
justify = LEFT,
padx = 10)
textLabel.pack(side = LEFT)
photo = PhotoImage(file='wws.gif')
imgLabel = Label(root,image=photo)
imgLabel.pack()
mainloop()
运行结果如下;
————————————————————————
在我们使用Label组件引入图片时,可能会出现较多问题,我在这里罗列一些成功引入图片的要素:
1)图片格式是gif或者png,jpg图片需要进行转化
2)图片需要保存在python运行的文件夹内
3)当我们使用电脑自带位图时,要注意Label组件中参数为bitmap,见第三点第一个程序。当我们使用自己下载的图片时,相应参数名应为image,详见第二个程序。
找好方法不头凉,关注小王有人帮。
下一讲,我们说——Button
部分内容参考博主:翻滚吧挨踢男
原文链接:https://blog.csdn.net/a359680405/article/details/45062087