Python tkinter学习笔记(1)-Label

613 查看

Python是最好的语言

刚接触Python的GUI(其实Python也是刚接触的)。原本是想研究kivy,但是尝试了一上午,失败了,因为kivy需要Pygame,Pygame又需要XQuartz,前几天刚把它卸载了, 今天安装时卡死在验证程序。NND。
不过没关系,学习框架只是为了有趣的学习语言,况且tkinter是原生的。其他伟大的GUI框架,比如wxPython却不支持3.0以上。

开始了

from tkinter import *

# 初始化tk
root = Tk()
# 设置窗口的title
root.title('Hello')

# 指定master、标题
label = Label(root, text='Hello')
# 显示label
label.pack()

# 指定内置位图
# 其他位图:error hourglass info questhead question warning gray12 gray25 gray50 gray75
Label(root, bitmap='error').pack()

# 使用颜色,前景色、背景色(可写颜色名称(red,green,blue,yello,lightbule)与颜色值)
Label(root, fg='lightblue', bg='#FF00FF', text='Hello').pack()

# 指定宽高。如果没有指定,以文字的长度决定
# 宽高的单位到底是什么呢?
# 高度是行高
Label(root, bg='red', width=10, height=3).pack()

'''
使用图像与文本
compound:指定文本(text)与图像(bitmap/image)是如何在 Label 上显示,缺省为 None,当指定 image/bitmap 时,文本(text)将被覆盖,只显示图像了。可以使用的值:
    left: 图像居左
    right: 图像居右
    top: 图像居上
    bottom:图像居下
    center:文字覆盖在图像上
bitmap/image:显示在 Label 上的图像
text: 显示在 Label 上的文本
'''
Label(root, text='Error', compound='left', bitmap='error').pack()

'''
多行显示与自动对齐:自动换行功能
使用自动换行功能,及当文 本长度大于控件的宽度时,文本应该换到下一行显示,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
'''
# 先来一段Python之禅
ZenOfPython = '''
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
'''
# 左对齐,文本居中,不指定宽高就伸展到最长一行的宽度
Label(root, text=ZenOfPython, bg='yellow', justify='center').pack()

# 进入消息循环。其实就是显示
root.mainloop()

结果:


Labels