一、Tkinter介绍
Python中自带了这个,安装python后,就可以使用这个ui库,tkinter是python的标准GUI界面库,介绍这个库,主要有几点原因:一是这个库是python自带的,安装即可使用。二是这个库使用起来相对还是比较简单的(当然相对于开发复杂界面这个库有点吃力,因为要自己手写布局代码等)。
在工作中,python主要是用来写一下脚本,写一下后台应用程序,偶尔用来做一个小工具(当然用pyqt可以做很复杂的界面,但是做小工具,用qt就有点杀鸡用牛刀的感觉了)。
二、入门案例
废话不多说,直接上一个hello world(程序员学新东西都是从hello world开始的)。
# coding = utf-8
import tkinter as tk
if __name__ == '__main__':
widget = tk.Tk()
widget.title('hello world')
widget.geometry('300x200')
widget.mainloop()
这里第一句是初始化一个Tkinter的窗口对象,第二行是设置标题,第三行是设置窗口大小,注意这里比较反人类,因为做其他GUI习惯了,在写这个demo的时候,我直接写成了widget.geometry(‘300,200’),在意识到错误的时候,随手就改成了widget.geometry(‘300*200’),结果它中间是用的“x”。最后一行是开启这个窗口的主循环。
运行,结果如下所示:
这里窗口可以自由缩放,偶尔为了限制窗口大小,可以设置以下代码:
widget.resizable(width=False, height=False)
此时,窗口上的最大化框已经变得不可用了,如下所示:
三、布局介绍
Tkinter支持三种布局,分别是pack布局、grid布局和place布局,下面简单说明这三种布局:
①pack布局:
这个英文名字确实看不出什么意思,进入它的方法内部,看一下介绍,如下:
"""Pack a widget in the parent widget. Use as options:
after=widget - pack it after you have packed widget
anchor=NSEW (or subset) - position widget according to given direction
before=widget - pack it before you will pack widget
expand=bool - expand widget if parent size grows
fill=NONE or X or Y or BOTH - fill widget if widget grows
in=master - use master to contain this widget
in_=master - see 'in' option description
ipadx=amount - add internal padding in x direction
ipady=amount - add internal padding in y direction
padx=amount - add padding in x direction
pady=amount - add padding in y direction
side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget.
"""
简单介绍几个参数属性:其中after表示将组件放置于其他组件之后。before表示将组件放在其他组件之前。anchor表示组件的对齐方式,这里涉及到界面的锚点,下文中会有介绍,一般说来顶为n,底为s,左为w,右为e,可以组合。side表示组件在窗口中的位置,其值可以是top、bottom、left和right。fill表示填充方式。expand表示是否扩展。
②grid布局:
这个是网格布局,先看一下它的属性:
"""Position a widget in the parent widget in a grid. Use as options:
column=number - use cell identified with given column (starting with 0)
columnspan=number - this widget will span several columns
in=master - use master to contain this widget
in_=master - see 'in' option description
ipadx=amount - add internal padding in x direction
ipady=amount - add internal padding in y direction
padx=amount - add padding in x direction
pady=amount - add padding in y direction
row=number - use cell identified with given row (starting with 0)
rowspan=number - this widget will span several rows
sticky=NSEW - if cell is larger on which sides will this widget stick to the cell boundary
"""
简单介绍几个参数属性:co