文档地址:http://effbot.org/tkinterbook/
主界面
root = Tk()
root.mainloop()
框架
frame = Frame(root, width=100, height=100)
frame.pack()
按钮
button = Button(frame, text="te\nxt", justify="left", wraplength="50", fg="red", font="宋体", command=func)
button.pack(side=LEFT)
fg - 前景色
bg - 背景色
可用颜色:
Red, Green, Blue, Yellow, and LightBlue 等,还可接受 #ffff00 输入
font 指定字体,可同时指定大小,加粗,斜体
font = "Helvetica 10 bold italic"
font = ("Courier New", 10, "bold italic") 注意:如果字体名称中有空格,必须采用tuple形式
可以在text属性的字符串中加入'\n'来换行
justify 用来设置文本的对齐方式,可用值为 left,right,center,默认为center
wraplength 用来设置文本的自动换行宽度,宽度单位为像素
bd 设置边框宽度,宽度单位为像素
relief 设置浮雕效果,可用值:flat, groove, raised, ridge, solid, or sunken
.bind("
.focus_set() 将焦点设置在组件上。对于键盘按键事件,需要先设置焦点在组件上
"
callback(event)
event.x, event.y 鼠标点击x,y坐标
event.char 按键码
事件描述字符串
type - 是事件描述中最重要的部分,比如Button, Key, Enter, Configure等
如果仅仅为了匹配一个特定的按键,可以省略两边的尖括号,直接输入按键
常用事件:
Cancel (the Break key)
BackSpace
Tab
Control_L
Alt_L
Pause, Caps_Lock, Escape, Prior (Page Up), Next (Page Down), End, Home, Left, Up, Right, Down, Print, Insert, Delete, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, Num_Lock, and Scroll_Lock
bind的绑定层级
bind 绑定组件实例
bind 绑定顶级组件root
bind_class 绑定组件类
bind_all 绑定所有组件
绑定事件,后绑定覆盖先绑定
text.bind("
top.bind_class("Text", "
官方不建议这样修改,会影响程序的拓展性,更好的解决方案是使用自定义的类
class MyText(Text):
def __init__(self, master, **kw):
apply(Text.__init__, (self, master), kw)
self.bind("
除了绑定事件外,还有协议事件。以下例子为关闭窗口时弹出是否关闭的确认框
from tkinter import *
from tkinter import messagebox
def callback():
if messagebox.askokcancel("Quit", "Do you really wish to quit?"):
root.destroy()
root = Tk()
root.protocol("WM_DELETE_WINDOW", callback)
root.mainloop()
创建两个窗口,Toplevel不能使用pack等布局方法
root = Tk()
top = Toplevel()
root.mainloop()
创建菜单实例
from tkinter import *
def callback():
print "called the callback!"
root = Tk()
# create a menu
menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="New", command=callback)
filemenu.add_command(label="Open...", command=callback)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=callback)
helpmenu = Menu(menu)
menu.add_cascade(label="Help", menu=helpmenu)
helpmenu.add_command(label="About...", command=callback)
mainloop()
使用Frame做为工具栏,如果需要使用图标,使用PhotoImage载入图片,使用image属性指定图片
root = Tk()
toolbar = Frame(root)
b = Button(toolbar, text='new', width=6, command=callback)
b.pack(side=LEFT, padx=2,pady=2)
b = Button(toolbar, text='open', width=6, command=callback)
b.pack(side=LEFT, padx=2,pady=2)
# fill=X 为填满整个宽度
toolbar.pack(side=TOP, fill=X)
root.mainloop()
root.geometry("600x480") 设置主界面大小
状态栏
status = Label(root, text="状态栏", bd=1, relief=SUNKEN, anchor=W)
status.pack(side=BOTTOM, fill= X)
消息框,可用选项为showinfo, showwarning, showerror, askquestion, askokcancel, askyesno, or askretrycancel
if tkMessageBox.askyesno("Print", "Print this report?"):
report.print()
一个dialog的实例
class Dialog(Toplevel):
def __init__(self, parent, title = None):
Toplevel.__init__(self, parent)
self.transient(parent)
if title:
self.title(title)
self.parent = parent
self.result = None
body = Frame(self)
self.initial_focus = self.body(body)
body.pack(padx=5, pady=5)
self.buttonbox()
self.grab_set()
if not self.initial_focus:
self.initial_focus = self
self.protocol("WM_DELETE_WINDOW", self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,
parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
#
# construction hooks
def body(self, master):
# create dialog body. return widget that should have
# initial focus. this method should be overridden
pass
def buttonbox(self):
# add standard button box. override if you don't want the
# standard buttons
box = Frame(self)
w = Button(box, text="OK", width=10, command=self.ok, default=ACTIVE)
w.pack(side=LEFT, padx=5, pady=5)
w = Button(box, text="Cancel", width=10, command=self.cancel)
w.pack(side=LEFT, padx=5, pady=5)
self.bind("
self.bind("
box.pack()
#
# standard button semantics
def ok(self, event=None):
if not self.validate():
self.initial_focus.focus_set() # put focus back
return
self.withdraw()
self.update_idletasks()
self.apply()
self.cancel()
def cancel(self, event=None):
# put focus back to the parent window
self.parent.focus_set()
self.destroy()
#
# command hooks
def validate(self):
return 1 # override
def apply(self):
pass # override
class MyDialog(Dialog):
def body(self, master):
Label(master, text="First:").grid(row=0)
Label(master, text="Second").grid(row=1)
self.e1 = Entry(master)
self.e2 = Entry(master)
self.e1.grid(row=0, column=1)
self.e2.grid(row=1, column=1)
return self.e1
def apply(self):
first = int(self.e1.get())
second = int(self.e2.get())
print(first,second)
root = Tk()
MyDialog(root)
root.mainloop()
pack 可用属性
padx, pady 水平,垂直方向间隔
side 放置方向,LEFT TOP RIGHT BOTTOM
fill 延展方向 X-铺满
grid 可用属性
row, column 行列位置
sticky 对齐方向 W E N S