一.tkinter.Event

tkinter的事件机制跟js是一样的,也是只有一个Event类,这个类包罗万象,集成了键盘事件,鼠标事件,包含各种参数。
不像java swing那种强类型事件,swing从Event派生出KeyEvent,MouseEvent等,层次分明,一切都是确定的。
这是两种哲学。
tkinter的事件机制也很好,简洁明了,知道一个就足够了。
tkinter.Event类包含以下属性

  • 'char'键盘事件,按键的字符
  • 'delta'鼠标滚动事件,鼠标滚动的距离
  • 'height','width'仅用于Configure事件,即当控件形状发生变化之后的宽度和高度.相当于SizeChanged事件
  • 'keycode'键盘事件,按键码
  • 'keysym', 'keysym_num', 按键事件
  • 'num'鼠标事件,鼠标按键码,1为左键,2为中建,3为右键
  • 'serial',An integer serail number that is incremented every time the server processes a client request
    也就是serial相当于Event的ID
  • 'state', A integer describing the state of all the modifier keys.用来表示修饰键的状态,即ctrl,shift,alt等修饰键的状态.
  • 'time',事件发生的时间
  • 'type', 事件的类型
  • 'widget',事件的源头
  • 'x', 'x_root', 'y', 'y_root'鼠标事件,鼠标的位置,x_root和y_root为绝对坐标系,x,y为相对坐标。

二.tkinter的bind函数

def bind(self, sequence=None, func=None, add=None)
函数包含三个可选参数,sequence描述事件类型,func描述回调函数,add感觉没卵用,就是确定即将绑定的事件会不会替代刚才绑定的事件(默认是不会,于是形成一个回调函数列表).
查看bind函数源代码,可以查看关于事件绑定函数如下doc string。
(1)一切事件都用字符串来表示,事件字符串格式为<MODIFIER-MODIFIER-TYPE-DETAIL>
(2)修饰符MODIFIER最多可以有两个,也可以有1个或者0个.修饰符MODIFIER取值必为以下之一:

  • Control,Shift,Alt,Lock
  • Meta, M
  • Mod1, M1,Mod2, M2,Mod3, M3,Mod4, M4,Mod5, M5
  • Button1,B1,Button2,B2,Button3,B3,Button4,B4,Button5,B5
  • Double,Triple.

(3)TYPE是事件类型,是字符串中最重要的部分,可取值包括:

  • Activate, Deactivate,
  • Enter,Leave,FocusIn,FocusOut,
  • Map, Unmap,
  • ButtonPress,ButtonRelease, Button, Motion,MouseWheel,
  • KeyRelease, KeyPress, Key
  • Expose, Circulate, Property,Colormap, Gravity, Reparent,Visibility, Destroy,
  • Configure

(4)详情DETAIL描述事件的具体内容,对于不同的事件类型,DETAIL的取值不一样.
DETAIL is the button number for ButtonPress,ButtonRelease
DETAIL is the Keysym for KeyPress and KeyRelease.
(5)举几个例子
<Control-Button-1> for pressing Control and mouse button 1.
<Alt-A> for pressing A and the Alt key (KeyPress can be omitted).
(6)An event pattern can also be a virtual event of the form <<AString>> where AString can be arbitrary. This event can be generated by event_generate.
(7)If events are concatenated they must appear shortly after each other.
(8)FUNC will be called if the event sequence occurs with an instance of Event as argument. If the return value of FUNC is "break" no further bound function is invoked.
(9)An additional boolean parameter ADD specifies whether FUNC will be called additionally to the other bound function or whether it will replace the previous function.
(10)Bind will return an identifier to allow deletion of the bound function with unbind without memory leak.
(11)If FUNC or SEQUENCE is omitted the bound function or list of bound events are returned.

三.事件举例

  • <Button-1>
    这个事件表示一个鼠标按键被按下。Button 1表示左键,button 2表示中键,Button 3表示右键。当在一个组件上按下一个鼠标键的时候Tkinter会自动的'grab'鼠标指针,当这个鼠标按键一直被持续按下,接下来的鼠标事件(比如移动和释放事件)将会被发送到组件上,甚至鼠标已经被移到了当前组件的外面。鼠标指针的当前位置(相对于组件)会在event对象中以成员x 和 y 的形式传递给callback。
    你可以使用ButtonPress来替代Button,甚至不写:<Button-1><ButtonPress-1><1>是一样的意思。为了表达清晰,我更喜欢使用<Button-1>语句。
  • <B1-Motion>
    The mouse is moved, with mouse button 1 being held down (use B2 for the middle button, B3 for the right button). The current position of the mouse pointer is provided in the x and y members of the event object passed to the callback.
    当Button 1被按下的时候移动鼠标(B2代表中键,B3代表右键),鼠标指针的当前位置将会以event对象的x y 成员的形式传递给callback。
  • <ButtonRelease-1>
    Button 1 was released. The current position of the mouse pointer is provided in the x and y members of the event object passed to the callback.
    Button 1被释放。鼠标指针的当前位置将会以event对象的x y 成员的形式传递给callback。
  • <Double-Button-1>
    Button 1 was double clicked. You can use Double or Triple as prefixes. Note that if you bind to both a single click () and a double click, both bindings will be called.
    Button 1被双击。可以使用Double 或者 Triple前缀。注意:如果你同时映射了一个单击和一个双击,两个映射都会被调用。
  • <Enter>
    The mouse pointer entered the widget (this event doesn’t mean that the user pressed the Enter key!).
    鼠标指针进入组件范围(这个事件不是用户按下了Enter键的意思)。
  • <Leave>
    The mouse pointer left the widget.
    鼠标指针离开组件范围。
  • <FocusIn>
    Keyboard focus was moved to this widget, or to a child of this widget.
    键盘焦点切换到这个组件或者子组件。
  • <FocusOut>
    Keyboard focus was moved from this widget to another widget.
    键盘焦点从一个组件切换到另外一个组件。
  • <Return>
    The user pressed the Enter key. You can bind to virtually all keys on the keyboard. For an ordinary 102-key PC-style keyboard, the special keys are Cancel (the Break key), BackSpace, Tab, Return(the Enter key), Shift_L (any Shift key), Control_L (any Control key),Alt_L (any Alt key), 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.
    用户按下Enter键。你可以映射键盘上所有的按键。对于一个普通的102键键盘,特殊按键有Cancel (the Break key), BackSpace, Tab, Return(the Enter key), Shift_L (any Shift key), Control_L (any Control key),Alt_L (any Alt key), 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.
  • <Key>
    The user pressed any key. The key is provided in the char member of the event object passed to the callback (this is an empty string for special keys).
    用户按下任何键。这个键会以event对象的char成员的形式传递给callback(对于特殊按键会是一个空字符串)
  • a
    The user typed an “a”. Most printable characters can be used as is. The exceptions are space (<space>) and less than (<less>). Note that 1 is a keyboard binding, while <1> is a button binding.
    用户输入‘a’。所有的可打印字符都可以这样使用。空格和少于例外。 注意 ‘1’表示映射键盘上的数字1,而<1>是一个鼠标映射
  • <Shift-Up>
    The user pressed the Up arrow, while holding the Shift key pressed. You can use prefixes like Alt, Shift, and Control.
    用户在按住Shift键的同时,按下Up箭头。你可以使用Alt + Shift + Control一样的各种组合。
  • <Configure>
    The widget changed size (or location, on some platforms). The new size is provided in the width and height attributes of the event object passed to the callback.
    改变组件的形状(在某些平台上表示的是位置)。新形状以event对象中width 和 height属性的形式传递给callback。

四.事件绑定

tkinter的事件绑定分为四个层次:

  • 本控件,the widget instance,use bind()
  • the top-level window,use bind()
  • the widget class,use bind_class()
  • 本应用程序,the whole application,use bind_all()

事件回调顺序:按照上述顺序从上到下依次执行,每层只执行一个最恰当的事件处理函数.由此可知,最多形成一个长度为4的回调函数列表.当不想继续让其它回调函数处理这个事件时,只需要return 'break',即可停止事件回调函数列表.

# 事件级别间”传递"
from Tkinter import *
root = Tk()
# Key事件处理函数
def printEvent(event):
    print '<instance>',event.keycode
# Return事件处理函数
def printToplevel(event):
    print '<toplevel>',event.keycode
def printClass(event):
    print '<bind_class>',event.keycode
def printAppAll(event):
    print '<bind_all>',event.keycode
# 在instance级别与printEvent绑定
bt1 = Button(root,text = 'instance event')
bt1.bind('<Return>',printEvent)
# 在bt1的Toplevel级别与printToplevel绑定
bt1.winfo_toplevel().bind('<Return>',printToplevel)
# 在class级别绑定事件printClass
root.bind_class('Button','<Return>',printClass)
# 在application all级别绑定printAppAll
bt1.bind_all('<Return>',printAppAll)
# 将焦点定位到bt1上,回车一下,结果有4个打印输出。
bt1.focus_set()
bt1.grid()
root.mainloop()
# 输出结果:
# <instance> 13
# <bind_class> 13
# <toplevel> 13
# <bind_all> 13
# Return向高级别进行了“传递",调用顺序为instance/class/toplevel/all

bind_class的作用

# 使用bind_class将影响所有这个类的instance
from Tkinter import *
root = Tk()
def printClass(event):
    print '<bind_class>',event.keycode
# 改变button类的事件绑定
root.bind_class('Button','<Return>',printClass)
# 创建两个Button
bt1 = Button(root,text = 'a button')
bt2 = Button(root,text = 'another button')
bt1.focus_set()
bt1.grid()
bt2.grid()
root.mainloop()
# 回车,bt1打印结果
# TAB切换到bt2,回车同样打印出结果,即所有的Button对Return事件进行响应

五.protocols

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", callback)  

root.mainloop()  

六.按钮事件直接绑定command参数

b=tkinter.Button(window,text='haha', command=haha)
这样一点击按钮就会调用haha()函数

tkinter事件机制的更多相关文章

  1. 【移动端兼容问题研究】javascript事件机制详解(涉及移动兼容)

    前言 这篇博客有点长,如果你是高手请您读一读,能对其中的一些误点提出来,以免我误人子弟,并且帮助我提高 如果你是javascript菜鸟,建议您好好读一读,真的理解下来会有不一样的收获 在下才疏学浅, ...

  2. [解惑]JavaScript事件机制

    群里童鞋问到关于事件传播的一个问题:“事件捕获的时候,阻止冒泡,事件到达目标之后,还会冒泡吗?”. 初学 JS 的童鞋经常会有诸多疑问,我在很多 QQ 群也混了好几年了,耳濡目染也也收获了不少,以后会 ...

  3. Atitit  数据库的事件机制--触发器与定时任务attilax总结

    Atitit  数据库的事件机制--触发器与定时任务attilax总结 1.1. 事件机制的图谱1 2. 触发器的类型2 3. 实现原理 After触发器 Vs Instead Of触发器2 3.1. ...

  4. 深入浅出iOS事件机制

    原文地址: http://zhoon.github.io/ios/2015/04/12/ios-event.html 本文章将讲解有关iOS事件的传递机制,如有错误或者不同的见解,欢迎留言指出. iO ...

  5. Java 事件机制

    java事件机制包括三个部分:事件.事件监听器.事件源. 1.事件.一般继承自java.util.EventObject类,封装了事件源对象及跟事件相关的信息,用于listener的相应的方法之中,作 ...

  6. Angular $scope和$rootScope事件机制之$emit、$broadcast和$on

    Angular按照发布/订阅模式设计了其事件系统,使用时需要“发布”事件,并在适当的位置“订阅”或“退订”事件,就像邮箱里面大量的订阅邮件一样,当我们不需要时就可以将其退订了.具体到开发中,对应着$s ...

  7. JavaScript 详说事件机制之冒泡、捕获、传播、委托

    DOM事件流(event  flow )存在三个阶段:事件捕获阶段.处于目标阶段.事件冒泡阶段. 事件捕获(event  capturing):通俗的理解就是,当鼠标点击或者触发dom事件时,浏览器会 ...

  8. DOM事件机制进一步理解

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name ...

  9. javascript 中的事件机制

    1.javascript中的事件. 事件流 javascript中的事件是以一种流的形式存在的. 一个事件会也有多个元素同时响应. 有时候这不是我们想要的效果, 我们只是需要某个特定的元素相应我们的绑 ...

随机推荐

  1. JAVA/GUI程序之记事本

    自上半年JAVA课程结束后,再也没有看过JAVA了,最近不是很忙,又简单的看了看,本博客纯属记录学习过程,请大神们别笑,其中错误是难免的,毕竟是新手写的博客.下面就进入我们的正题吧,复习GUI时,就想 ...

  2. 关于Java泛型的使用

    在目前我遇到的java项目中,泛型应用的最多的就属集合了.当要从数据库取出多个对象或者说是多条记录时,往往都要使用集合,那么为什么这么使用,或者使用时有什么要注意的地方,请关注以下内容. 感谢Wind ...

  3. 物联网框架SuperIO 2.2.9和ServerSuperIO 2.1同时更新,更适用于类似西门子s7-200发送多次数据,才能读取数据的情况

    一.解决方案 二.更新内容 1.修改IRunDevice接口,把void Send(io,bytes)改成int Send(io,bytes).2.修改网络控制器,发送数据不直接使用IO实例,改为使用 ...

  4. (转)解决 ORA-12514: TNS: 监听程序当前无法识别连接描述符中请求的服务

    下面操作默认在安装Oralce数据库的服务器上运行. 1)确保Oracle 基本服务都已启动 OracleDBConsoleorcl OracleOraDb11g_home1TNSListener O ...

  5. .Container与.container_fluid区别

    .Container与.container_fluid是bootstrap中的两种不同类型的外层容器,两者的区别是:.container 类用于固定宽度并支持响应式布局的容器..container-f ...

  6. 苹果手机不支持click文字 需要添加 cursor:pointer 才能 识别可以点击

    给一个div 绑定一个 click事件,  苹果手机会识别不了,必须添加一个 cursor:pointer 才能 识别可以点击.安卓正常识别.

  7. vue.js初级入门之最基础的双向绑定操作

    首先在页面引入vue.js以及其他需要用到的或者可能要用到的插件(这里我多引用了bootstrap和jquery) 引用的时候需要注意文件的路径,准备工作这样基本就完成了,下面正式开始入门. vue. ...

  8. UICollectionView布局cell的三种方式

    UICollectionViewFlowLayout里面: // 方法一 - (void)prepareLayout{} // 方法二 - (nullable NSArray<__kindof ...

  9. 正则表达式在iOS中的运用

    1.什么是正则表达式 正则表达式,又称正规表示法,是对字符串操作的一种逻辑公式.正则表达式可以检测给定的字符串是否符合我们定义的逻辑,也可以从字符串中获取我们想要的特定部分.它可以迅速地用极简单的方式 ...

  10. git-入门

    一.简介 Git是目前世界上最先进的分布式版本控制系统,Git中绝大部分操作都是访问本地资源,不需要网络,其中有三个概念比较重要:1. 工作目录 2. 暂存区域 3.本地仓库. 简单说明一下,工作目录 ...