Tk中有三个基本概念要了解:
- widgets(组件/控件/窗口)
- geometry management(位置管理)
- event handling(事件处理)
Widgets(组件/控件/窗口)
整个用户界面都是由 widgets构成的,widgets解决的是放什么的问题。常见的有Button
Entry
Label
Frame
等等
组件层级
组件是有层级的,上图是第一个示例对应的层级关系。生成组件是该组件的上一级为它的
master
, 它是上一级的slave
组件的配置选项
每个组件都有一些配置选项,来定义它们的外观和行为。
比如Label
有text
选项,Button
也有text
选项,但Button
还有command
选项。即功能相同的选项名字一般也是相同的,组件还有自己特有的选项。下面代码展示了如何查看组件的选项。例如button.configure('text')
button.configure()
>>> from tkinter import *
>>> from tkinter import ttk
>>> root = Tk()
# create a button, passing two options:
>>> button = ttk.Button(root, text="Hello", command="buttonpressed")
# check the current value of the text option:
>>> button['text']
'Hello'
# change the value of the text option:
>>> button['text'] = 'goodbye'
# another way to do the same thing:
>>> button.configure(text='goodbye')
# check the current value of the text option:
>>> button['text']
'goodbye'
# get all information about the text option:
>>> button.configure('text')
('text', 'text', 'Text', '', 'goodbye')
# get information on all options for this widget:
>>> button.configure()
{'cursor': ('cursor', 'cursor', 'Cursor', '', ''), 'style': ('style', 'style', 'Style', '', ''),
'default': ('default', 'default', 'Default', <index object at 0x00DFFD10>, <index object at 0x00DFFD10>),
'text': ('text', 'text', 'Text', '', 'goodbye'), 'image': ('image', 'image', 'Image', '', ''),
'class': ('class', '', '', '', ''), 'padding': ('padding', 'padding', 'Pad', '', ''),
'width': ('width', 'width', 'Width', '', ''),
'state': ('state', 'state', 'State', <index object at 0x0167FA20>, <index object at 0x0167FA20>),
'command': ('command', 'command' , 'Command', '', 'buttonpressed'),
'textvariable': ('textvariable', 'textVariable', 'Variable', '', ''),
'compound': ('compound', 'compound', 'Compound', <index object at 0x0167FA08>, <index object at 0x0167FA08>),
'underline': ('underline', 'underline', 'Underline', -1, -1),
'takefocus': ('takefocus', 'takeFocus', 'TakeFocus', '', 'ttk::takefocus')}
Geometry Management(位置管理)
Geometry Management解决的是组件怎么放置的问题。常用的三个方法:
- grid() 例如
feet_entry.grid(column=2, row=1, sticky=(W, E))
按网格放置,美观方便,优先使用 - pack() 按先后顺序,堆放。先跑起来再说
- put() 按绝对坐标放置。精调
Event Handling(事件处理)
- 事件分两种:
- 低级事件:鼠标点击、按键、窗口拖拽……
- 高级事件(虚拟事件):对低级事件的一种概括,比如从下拉列表里选中一项,无论是用鼠标还是用上下键选中的都会生成
ListboxSelect
事件
- 事件与处理函数绑定的方式也有两种:
- 组件实例化时,用
command
选项 - 组件实例化后,用组件的
bind()
方法