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)
frame.bind("", callback_1)
frame.bind("", callback_2)
frame.bind("", callback_3)
frame.bind('', 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


你可能感兴趣的:(Python,编程,tkinter)