tkinter: 事件 & 绑定 (Events and Bindings)

目的

tkinter 获取 键盘输入鼠标输入

实现代码

# coding=utf-8
import tkinter as tk

root = tk.Tk()

def center_window(w, h):
    # 获取屏幕 宽、高
    ws = root.winfo_screenwidth()
    hs = root.winfo_screenheight()
    # 计算 x, y 位置
    x = (ws/2) - (w/2)
    y = (hs/2) - (h/2)
    root.geometry('%dx%d+%d+%d' % (w, h, x, y))

center_window(500, 500)

# 单击键盘
def key(event):
    print "pressed", repr(event.char)

# 单击左键
def callback_1(event):
    #当前框架被选中,意思是键盘触发,只对这个框架有效
    frame.focus_set()
    print "left clicked at : (window coordinate {}, {}), (screen coordinate {}, {}) ".format(event.x, event.y, event.x_root, event.y_root)

# 单击滚轮
def callback_2(event):
    #当前框架被选中,意思是键盘触发,只对这个框架有效
    frame.focus_set()
    print "middle clicked at : (window coordinate {}, {}), (screen coordinate {}, {}) ".format(event.x, event.y, event.x_root, event.y_root)

# 单击右键
def callback_3(event):
    #当前框架被选中,意思是键盘触发,只对这个框架有效
    frame.focus_set()
    print "right clicked at : (window coordinate {}, {}), (screen coordinate {}, {}) ".format(event.x, event.y, event.x_root, event.y_root)

frame = tk.Frame(root, width=500, height=500, bg='blue')
frame.bind("<Key>", key)
frame.bind("<Button-1>", callback_1)
frame.bind("<Button-2>", callback_2)
frame.bind("<Button-3>", callback_3)
frame.bind('<Control-q>', lambda event: frame.quit())
frame.pack()

root.mainloop()

打印结果

left clicked at : (window coordinate 123, 239), (screen coordinate 833, 557) 
middle clicked at : (window coordinate 161, 221), (screen coordinate 871, 539) 
right clicked at : (window coordinate 206, 228), (screen coordinate 916, 546) 
pressed 'r'
pressed 'g'
pressed ''

Process finished with exit code 0


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值