Events and Bindings
一个Tkinter运用大部分时间都是运行在event loop-mainloop()中,events可以包括来自按键、鼠标,或者是window mangaer。Tkinter widget提高了一种很好的机制让用户处理事件,可以通过widget.bind(event,handler)来进行绑定。
root = Tk()
def callback(event):
print “clicked at”, event.x, event.y
frame = Frame(root, width = 100, height = 100)
frame.bind(“<Button-1>”, callback)
frame.pack()
root.mainloop()
- Events
Events以一个字符串的形式给出,其格式如下:
其中最重要的是type,可以是Buttton, Key,Enter,Configure等,modifier和detail用来指定一些附加的信息,常常可以忽略。下表为Event Formats.
- The Event Object
Attribute
|
Description
|
widget
|
表明该event是由拿一个widget产生的,例如event.frame == frame
|
x, y
|
当前鼠标的位置(以象素为单位)
|
x_root, y_root
|
当前鼠标位置相对于屏幕左上角而言的位置
|
char
|
Character code(keyboard events only)
|
keysym
|
Key symbol(keyboard events only)
|
keycode
|
The key code(keyboard events only),实际上就是该字母的ASCII(大写)
|
num
|
Buttom number(mouse button event only)
|
width, height
|
Configure event新指定的widget size
|
type
|
Event 类型
|
-
Instance and class bindings
widget.bind(…)都是为该widget绑定一个事件,没有继承性。但是,实际上继承可以从四个层次面来绑定。
the widget instance, using bind
the widget’s toplevel window(Toplevel or root), also using bind
the widget class, using bind_class
the whole application,using bind_all
-
Protocols
Tkinter也支持protocol handlers。即application和window manager之间的protocol。常用的由WM_DELETE_WINDOW。
from Tkinter import *
import tkMessageBox
def callback():
if tkMessageBox.askokcancel(“Quit”, “Do you really wish to quit?”):
root.destroy()
root = Tk()
root.protocol(“WM_DELETE_WINDOW”
Application Windows
-
Base Windows
调用Tk的构造函数生成一个root window,如果需要生成其它窗口则需要调用Toplevel()函数。
-
Menus
Tkinter为Menu提供了一系列widget。菜单的创建需要调用Menu类来完成,可以用add methods为其添加entries(菜单条)。
add_command(label=string, command=callback),添加菜单条
add_separator(),添加分割线
add_cascade(label=string, menu =menu instance),添加层次式菜单
from Tkinter import *
def callback():
print "called the callback!"
root = Tk()
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)
root.mainloop()
- Toolbars
工具条一般在菜单的下方,为菜单选择提供便捷方式。
from Tkinter import *
root = Tk()
def callback():
print "called the callback!"
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)
toolbar.pack(side = TOP, fill = X)
mainloop()
- Status Bars
大多数application window都可以指定状态栏,可用Label widget来实现它。
status = Label(master, text = “”, bd =1, relief = SUNKEN, anchor = W)
status.pack(side = BOTTOM, fill = X)