GUI英文全称是Graphical User Interface,中文为图形用户接口。git
tkinter是一个开放源码的图形接口开发工具,在安装Python时,就已经同时安装此模块了,在使用前只须要导入便可。express
import tkinter print(tkinter.TkVersion)
8.6
from tkinter import * root = Tk() root.mainloop()
一般将使用Tk()方法创建的窗口称为根窗口,默认名称是tk,以后能够在此根窗口中创建许多控件,也能够在此根窗口中创建上层窗口。mainloop()方法让程序继续执行,同时进入等待与处理窗口事件,单击窗口的"关闭"按钮,此程序才会结束。框架
与窗口相关的方法:ide
方法 | 说明 |
title() | 能够设置窗口的标题 |
geometry("widthxheight+x+y") | 设置窗口宽width与高height,单位是像素,设定窗口位置 |
maxsize(width,height) | 拖曳时窗口最大的宽和高 |
minsize(width,height) | 拖曳时窗口最小的宽和高 |
configure(bg="color") | 设置窗口的背景颜色 |
resizable(True,Ture) | 可设置是否可更改窗口大小,第一个参数是宽,第二个参数是高,若是要固定窗口宽与高,可使用resizable(0,0) |
state("zoomed") | 最大化窗口 |
iconify() | 最小化窗口 |
iconbitmap("xx.ico") | 更改默认窗口图标 |
root = Tk() root.title("MyWindow") root.geometry("300x160+400+200") root.configure(bg="#33ff33") root.iconbitmap("mystar.ico") root.mainloop()
geometry中width和height用x分隔,表示窗口的宽和高,+x是窗口左边距离屏幕左边的距离,若是是-x则是表示窗口右边距离屏幕右边的距离,同理,+y或-y表示窗口上边(下边)距离屏幕上边(下边)的距离。函数
在tkinter模块中可使用下列方法得到屏幕的宽度和高度:工具
下面的程序将窗口显示在屏幕中央。oop
root = Tk() screenWidth = root.winfo_screenwidth() screenHeight = root.winfo_screenheight() w = 300 h = 160 x = (screenWidth - w) / 2 y = (screenHeight -h) / 2 root.geometry("%dx%d+%d+%d" % (w,h,x,y)) root.mainloop()
Widget能够翻译为控件或组件或部件。窗口创建完成后,下一步就是在窗口内创建控件。学习
控件开发工具
增强版模块tkinter.ttk中新增的Widget:字体
Widget的共同属性:
Widget的共同方法:
Label()方法用于在窗口内创建文字或图像标签。
Label(父对象,options,…)
经常使用options参数:
Widget的共同属性。
bg、fg设置背景、前景色。
width、height的单位是字符。
root = Tk() root.title("Ex") root.geometry("200x80") label = Label(root, text = "I like tkinter", \ bg = "#EF72AA", fg = "white", \ height = 3, width = 20) label.pack() #包装与定位组件 root.mainloop()
Widget的共同属性。
Anchor是指标签文字在标签区域的输出位置。
好比nw效果以下:
anchor的参数设置也可使用NW、N、NE、W等大写常数,同时省略字符串的双引号。
wraplength = 35
效果以下:
Widget的共同属性。
用于设置文字字形。
root = Tk() root.title("Ex") label = Label(root, text = "I like tkinter", \ bg = "#EF72AA", fg = "white", \ height = 3, width = 20, \ font = "Helnetic 20 bold italic") # font = ("Helnetic", 20, "bold", "italic")) label.pack() #包装与定位组件 root.mainloop()
height和width都是字号联动的。
justify = "right"
Widget的共同属性。
在标签位置放置内建位图。
error、hourglass、info、questhead、question、warning、gray十二、gray2五、gray50、gray75
label = Label(root, bitmap = "question")
图像与文字共存时,使用此参数定义文字与图像的位置关系。
label = Label(root, bitmap = "question", text = "Question", \
compound = "left")
Widget的共同属性。
用于创建Widget的边框。
label = Label(root, text = "raised", \
relief = "raised")
padx用于设置标签文字左右边界与标签区间的x轴间距,pady用于设置文字上下边界与标签取件单y轴间距。
与width和height做用类似,能够互相替代。
root.geometry("300x100")
label = Label(root, text = "raised", \
bg = "lightyellow", relief = "raised", \
padx = 5, pady = 10)
图片能够应用在许多地方,例如标签、功能按钮、选项按钮文字区域等。在使用前可使用PhotoImage()方法创建图像对象,而后再将此对象应用在其余窗口组件上。
imageobj = PhotoImage(file = "xxx.gif")
png也可。
image_obj = PhotoImage(file = "mystar.png")
label = Label(root, image = image_obj)
jpg没法直接解析:
须要借助PIL模块。
from tkinter import * from PIL import Image, ImageTk root = Tk() root.title("Ex") image_obj = Image.open("scenery.jpg") jpg_obj = ImageTk.PhotoImage(image_obj) label = Label(root, image = jpg_obj) label.pack() #包装与定位组件 root.mainloop()
注意:bitmap和image不能共存。
Widget的共同属性。
表示光标形状,实际形状可能会因操做系统不一样而有所差别。
Widget的共同方法。
能够以列表的形式传回Widget的全部参数。
root = Tk() root.title("Ex") label = Label(root, text = "tkinter") label.pack() print(label.keys())
['activebackground', 'activeforeground', 'anchor', 'background', 'bd', 'bg', 'bitmap', 'borderwidth', 'compound', 'cursor', 'disabledforeground', 'fg', 'font', 'foreground', 'height', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'image', 'justify', 'padx', 'pady', 'relief', 'state', 'takefocus', 'text', 'textvariable', 'underline', 'width', 'wraplength']
Widget的共同方法。
Widget控件在创建时能够直接设置对象属性,如果部分属性未创建,将来在程序执行时可使用config()方法创建或更改属性。此方法内属性设置的参数用法与创建时相同。
计数器:
from tkinter import * counter = 0 def run_counter(digit): def counting(): global counter counter += 1 digit.config(text=str(counter)) digit.after(1000,counting) counting() root = Tk() root.title("Ex") digit = Label(root, bg = "yellow", \ height = 3, width = 10, \ font = "Helvetic 20 bold") digit.pack() run_counter(digit) root.mainloop()
用于添加分隔线。
Separator(父对象,options)
options为HORIZONTAL表示创建水平分隔线,VERTICAL表示创建垂直分隔线。
from tkinter import * from tkinter.ttk import Separator root = Tk() root.title("Ex") myTitle = "我喜欢Tkinter" myContent = """今天,我开始学习Tkinter。 Tkinter 是 Python 的标准 GUI 库, Python 使用 Tkinter 能够快速的建立 GUI 应用程序。""" label1 = Label(root, text = myTitle, font = "Helvetic 20 bold") label1.pack(padx = 10, pady = 10) sep = Separator(root, orient = HORIZONTAL) sep.pack(fill = X, padx = 5) label2 = Label(root, text = myContent) label2.pack(padx = 10, pady = 10) root.mainloop()
Widget Layout Manager用于将多个Widget控件配置到容器或窗口内,有3中方法:
最经常使用的控件配置管理员,使用相对位置类处理控件,至于控件的正确位置则是由pack方法自动完成的。
pack(options,…)
-after, -anchor, -before, -expand, -fill, -in, -ipadx, -ipady, -padx, -pady, -side
用于水平或垂直配置控件。
root = Tk() root.title("Ex") label1 = Label(root, text = "哈尔滨工业大学", \ bg = "lightyellow", width = 30) label2 = Label(root, text = "哈尔滨工程大学", \ bg = "lightgreen", width = 15) label3 = Label(root, text = "东北林业大学", \ bg = "lightblue", width = 15) label1.pack(side = BOTTOM) label2.pack(side = RIGHT) label3.pack(side = LEFT) root.mainloop()
列出全部的relief属性:
root = Tk() root.title("Ex") Reliefs = ["flat", "groove", "raised" ,"ridge", "solid", "sunken"] for Relief in Reliefs: Label(root, text = Relief, relief = Relief, \ fg="darkgreen", font = "Times 20 bold").pack(side = LEFT, padx = 5) root.mainloop()
列出全部的位图:
root = Tk() root.title("Ex") bitMaps = ["error", "hourglass", "info", "questhead", "question", \ "warning", "gray12", "gray25", "gray50", "gray75"] for bitMap in bitMaps: Label(root, bitmap = bitMap).pack(side = LEFT, padx = 5) root.mainloop()
设定控件边界与容器或其余控件边界之间的距离。默认为1。
控制文字与标签容器的x/y轴间距。
设定Widget控件在窗口中的位置
root = Tk() root.title("Ex") root.geometry("300x180") label1 = Label(root, text = "Next", \ font = "Times 15 bold", fg = "white", bg = "blue") label2 = Label(root, text = "Previous", \ font = "Times 15 bold", fg = "white", bg = "red") label1.pack(anchor = S, side = RIGHT, \ padx = 10, pady = 10) label2.pack(anchor = S, side = RIGHT, \ padx = 10, pady = 10) root.mainloop()
设置控件填满所分配容器的方式。
若是所分配容器区间已经满了,则使用fill参数不会有任何做用。
root = Tk() root.title("Ex") label1 = Label(root, text = "哈尔滨工业大学", \ bg = "lightyellow") label2 = Label(root, text = "哈尔滨工程大学", \ bg = "lightgreen") label3 = Label(root, text = "东北林业大学", \ bg = "lightblue") label1.pack(side = LEFT, fill = Y) label2.pack() label3.pack(fill = X) root.mainloop()
设定Widget控件是否填满额外的父容器界面,默认为False。
label2.pack(fill = BOTH, expand = True)
pack其实在tkinter中也是一个类别,有如下方法可供使用:
print(root.pack_slaves())
[<tkinter.Label object .!label>, <tkinter.Label object .!label2>, <tkinter.Label object .!label3>]
这是一种以格状或者相似Excel表格方式包装和定位窗口组件的方法。
grid(opions,…)
-column, -columnspan, -in, -ipadx, -ipady, -padx, -pady, -row, -rowspan, -sticky
label1.grid(row = 0, column = 0)
label2.grid(row = 1, column = 2)
label3.grid(row = 2, column = 1)
能够设定row或column方向的合并数量。
与pack方法中的参数相同。
相似于anchor,只能设定N/S/W/E,即上/下/左/右对齐,但能够组合使用。
用于设定某行或列在窗口缩放大小时的缩放比例。
rowconfigure(0, weight = 1) #row 0 的控件在窗口改变大小时缩放比是1
columnconfigure(0, weight = 1) #column 0 的控件在窗口改变大小时缩放比是1
root = Tk() root.title("Ex") root.rowconfigure(0,weight=1) root.columnconfigure(1,weight=1) label1 = Label(root, text = "哈尔滨工业大学", \ bg = "lightyellow") label2 = Label(root, text = "哈尔滨工程大学", \ bg = "lightgreen") label3 = Label(root, text = "东北林业大学", \ bg = "lightblue") label1.grid(row = 0, column = 0, sticky = N+S) label2.grid(row = 1, column = 0) label3.grid(row = 1, column = 1, sticky = W+E) root.mainloop()
创建色彩标签:
root = Tk() root.title("Ex") Colors = ["red", "orange", "yellow", "green","cyan", "blue", "purple"] r = 0 for color in Colors: Label(root, text = color, relief = "groove", width = 20).grid(row = r, column = 0) Label(root, bg = color, relief = "ridge", width = 20).grid(row = r,column = 1) r += 1 root.mainloop()
使用直接指定方式将Widget控件放在容器中的方法。
place(options,…)
直接设定控件左上角位置,单位是像素。
窗口区左上角是(x=0,y=0),x向右递增,y向下递增。
在插入图片的同时设定图片的大小。
from PIL import Image, ImageTk root = Tk() #root=Toplevel() root.title("Ex") root.geometry("520x520") flower = ImageTk.PhotoImage(Image.open("flower.jpg")) scenery = ImageTk.PhotoImage(Image.open("scenery.jpg")) p1 = Label(root, image = flower) p2 = Label(root, image = scenery) p1.place(x=20, y=20, width = 200, height = 200) p2.place(x=240, y=240, width = 260, height = 260) root.mainloop()
relx/rely用于设置相对于父容器的位置,relwidth/relheight用于设置相对于父容器的大小,取值为0~1.0。
在窗口组件中能够设计在单击功能按钮时,执行某一个特定的动做,这个动做也称为callback方法。
Button(父对象,options,…)
经常使用的options参数:
def msgShow(): label["text"] = "I love tkinter." label["bg"] = "lightyellow" label["fb"] = "blue" label.config(text = "I love tkinter.", bg = "lightyellow", fg = "blue") root = Tk() root.title("Ex") label = Label(root) btn1 = Button(root, text = "Show Message", width = 15, command = msgShow) btn2 = Button(root, text = "Exit", width = 15, command = root.destroy) label.pack() btn1.pack(side = LEFT) btn2.pack(side = LEFT) root.mainloop()
def bColor(bgColor): root.config(bg = bgColor) root = Tk() root.title("Ex") root.geometry("300x200") #创建3个按钮 bluebtn = Button(root, text = "Blue", command = lambda:bColor("blue")) yellowbtn = Button(root, text = "Yellow", command = lambda:bColor("yellow")) exitbtn = Button(root, text = "Exit", command = root.destroy) exitbtn.pack(anchor = S, side = RIGHT, padx = 5, pady = 5) yellowbtn.pack(anchor = S, side = RIGHT, padx = 5, pady = 5) bluebtn.pack(anchor = S, side = RIGHT, padx = 5, pady = 5) root.mainloop()
一般是指单行文本框,是GUI设计中用于输入的最基本的Widget控件,能够用来输入单行字符串。
若是输入的字符串长度大于文本框的宽度,输入的文字会自动隐藏形成部份内容没法显示出来,此时可使用箭头键移动鼠标光标到看不到的区域。
若是须要处理多行文字,则须要使用Text。
Entry(父对象,options,…)
经常使用的options参数:
root = Tk() root.title("Ex") accountL = Label(root, text = "Account:") accountL.grid(row = 0) passwordL = Label(root, text = "Password:") passwordL.grid(row = 1) accountE = Entry(root) accountE.grid(row = 0,column = 1) passwordE = Entry(root, show = '*') passwordE.grid(row = 1, column = 1) root.mainloop()
用于获取目前Entry的字符串内容。
def printInfo(): print("Account:%s\nPassword:%s" % \ (accountE.get(), passwordE.get())) ... loginbtn = Button(root, text = "Login", command = printInfo) loginbtn.grid(row = 3) quitbtn = Button(root, text = "Quit", command = root.destroy) quitbtn.grid(row = 3, column = 1) root.mainloop()
Account:叮叮当当sunny
Password:123456789abcdefg
用于创建默认文字。
insert(index,s) #将字符串s插入在index位置
accountE.insert(0, "Kevin")
passwordE.insert(0, "pwd123")
用于删除文字。
delete(first,last = None) #删除从第first到第last-1字符之间的字符串(last = None则仅删除第first个字符)
delete(0,END) #删除文本框内整个字符串
用于将字符串转换为Python语句执行,能够直接计算数学表达式。
result = eval(expression) #expression是字符串
数学表达式计算:
from tkinter import * import numpy as np def cal(): out.configure(text = "结果:" + str(eval(equ.get()))) root = Tk() root.title("Ex") label = Label(root, text = "请输入数学表达式:") label.pack() equ = Entry(root) equ.pack(padx = 20, pady = 5) out = Label(root) out.pack() btn = Button(root, text = "计算", command = cal) btn.pack(pady = 5) root.mainloop()
要将Widget控件的参数以变量方式处理时,须要借助tkinter模块内的变量类别,这个类别有4个子类别,每个类别实际上是一个数据类型的构造方法,咱们能够经过这4个子类别的数据类型将它们与Widget控件的相关参数结合。
使用get()方法取得变量内容,使用set()方法设置变量内容。
msg_on = False def btn_hit(): global msg_on if msg_on == False: msg_on = True x.set("I like tkinter") else: msg_on = False x.set("") root = Tk() root.title("Ex") x = StringVar() label = Label(root, textvariable = x, \ fg = "blue", bg = "lightyellow", \ font = "Verdana 15 bold", \ width = 25, height = 2) label.pack() btn = Button(root, text = "Show", command = btn_hit) btn.pack(pady = 5) root.mainloop()
def btn_hit():
if x.get() == "":
x.set("I like tkinter")
else:
x.set("")
利用变量追踪Widget控件,当其内容更改时,让程序执行callback函数。
def callback(*args): print("data changed:",xE.get()) root = Tk() root.title("Ex") xE = StringVar() entry = Entry(root, textvariable = xE) entry.pack() xE.trace('w', callback) root.mainloop()
data changed: t
data changed: tk
data changed: tki
data changed: tkin
data changed: tkint
data changed: tkinte
data changed: tkinter
w表示当写入时,自动执行callback函数,这个动做称为变更追踪。
r表示当控件内容被读取时,执行特定函数。
def callbackW(*args): xL.set(xE.get()) def callbackR(*args): print("Waring:数据被读取!") def hit(): print("读取数据:", xE.get()) root = Tk() root.title("Ex") xE = StringVar() entry = Entry(root, textvariable = xE) entry.pack(padx = 20, pady = 5) xE.trace('w', callbackW) xE.trace('r', callbackR) xL = StringVar() label = Label(root, textvariable = xL) xL.set("同步显示") label.pack(padx = 20, pady = 5) btn = Button(root, text = "读取", command = hit) btn.pack(padx = 20, pady = 5) root.mainloop()
Waring:数据被读取!
读取数据: tkinter
callback函数其实有3个参数:tk变量名称、index索引、mode模式。
def calculate(): r = re.findall(".+", equ.get()) result = eval(str(r[-1])) equ.set(equ.get() + "\n" + str(result)) def show(buttonString): content = equ.get() if content == "0": content = "" equ.set(content + buttonString) def backspace(): equ.set(str(equ.get()[:-1])) def clear(): equ.set("0") root = Tk() root.title("calculator") equ = StringVar() equ.set("0") #默认显示0 #显示区 label = Label(root, width = 25, height = 2, relief = "raised", \ anchor = SE, textvariable = equ) label.grid(row = 0, column = 0, columnspan = 4, padx = 5, pady = 5) #按钮设计 Button(root, text = "C", fg = "blue", width = 5, \ command = clear).grid(row = 1, column = 0) Button(root,text="DEL",width=5,command=backspace).grid(row=1,column=1) Button(root,text="%",width=5,command=lambda:show("%")).grid(row=1,column=2) Button(root,text="/",width=5,command=lambda:show("/")).grid(row=1,column=3) Button(root,text="7",width=5,command=lambda:show("7")).grid(row=2,column=0) Button(root,text="8",width=5,command=lambda:show("8")).grid(row=2,column=1) Button(root,text="9",width=5,command=lambda:show("9")).grid(row=2,column=2) Button(root,text="*",width=5,command=lambda:show("*")).grid(row=2,column=3) Button(root,text="4",width=5,command=lambda:show("4")).grid(row=3,column=0) Button(root,text="5",width=5,command=lambda:show("5")).grid(row=3,column=1) Button(root,text="6",width=5,command=lambda:show("6")).grid(row=3,column=2) Button(root,text="-",width=5,command=lambda:show("-")).grid(row=3,column=3) Button(root,text="1",width=5,command=lambda:show("1")).grid(row=4,column=0) Button(root,text="2",width=5,command=lambda:show("2")).grid(row=4,column=1) Button(root,text="3",width=5,command=lambda:show("3")).grid(row=4,column=2) Button(root,text="+",width=5,command=lambda:show("+")).grid(row=4,column=3) Button(root, text="0", width=12, \ command = lambda:show("0")).grid(row = 5, column = 0, columnspan = 2) Button(root, text=".", width=5, \ command = lambda:show(".")).grid(row = 5, column = 2) Button(root, text="=", bg = "lightyellow", width=5, \ command = calculate).grid(row = 5, column = 3) root.mainloop()