Tkinter:Label

来源:互联网 发布:输入法 linux 编辑:程序博客网 时间:2024/05/18 08:46

该代码是用Tkinter产生一个标签:

from Tkinter import *
root=Tk()
label=Label(root,text='Hello Tkinter !')
label.pack()
root.mainloop()

还有更简单的例子

from Tkinter import *
root = Tk()
root.title('hello Tkinter')
root.mainloop()

效果:

label使用内置位图

from Tkinter import *
root = Tk()
label=Label(root,bitmap='error')
label.pack()
root.mainloop()


效果:

label可用的位图有:

* error
* hourglass
* info
* questhead
* question
* warning
* gray12
* gray25
* gray50
* gray75

Label背景色与前景色设置

from Tkinter import *
root=Tk()
label=Label(root,fg='red',bg='blue',text='Hello Tkinter !')
label.pack()
root.mainloop()

效果:

Label高度与宽度设置:

from Tkinter import *
root=Tk()
label=Label(root,text='Hello Tkinter !',bg='blue')
label.pack()
label=Label(root,text='Hello Tkinter !',fg='yellow',width=15)
label.pack()
label=Label(root,text='Hello Tkinter !',bg='white',width=15,height=5)
label.pack()
root.mainloop()

效果:

Label图像和文本一起使用:

compound: 指定文本(text)与图像(bitmap/image)是如何在Label 上显示,缺省为None。

当指定 image/bitmap 时,compound指图像相对text的位置,可以使用的值:
left: 图像居左
right: 图像居右
top: 图像居上
bottom:图像居下
center:文字覆盖在图像上
bitmap/image:显示在Label 上的图像
text: 显示在Label 上的文本

from Tkinter import *
root=Tk()
label=Label(root,text='info',compound='left',bitmap='info')
label.pack()
label=Label(root,text='error',compound='right',bitmap='error')
label.pack()
label=Label(root,text='hourglass',compound='top',bitmap='hourglass')
label.pack()
label=Label(root,text='question',compound='bottom',bitmap='question')
label.pack()
label=Label(root,text='warning',compound='center',bitmap='warning')
label.pack()
root.mainloop()

效果:

Label控制多行显示:

如果使用width和height来指定控件的大小那么,如果文本过长的话,将是文本不能完全的显示,Tk不会自动换行,但Tk提供了一个属性来控制多行文本的显示:

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=Label(root,text='welcome to tkinter world !',bg='blue',width=20,wraplength=80,justify='left')
label.pack()

#居中对齐,文本居左
label=Label(root,text='welcome to tkinter world !',bg='red',width=20,wraplength=80,anchor='w')
label.pack()

#居中对齐,文本居右
label=Label(root,text='welcome to tkinter world !',bg='green',width=20,wraplength=80,justify='left',anchor='e')
label.pack()
root.mainloop()

效果:

justify 与anchor 的区别了:一个用于控制多行的对齐;另一个用于控制整个文本
块在Label 中的位置。

原创粉丝点击