前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >tkinter: 事件 & 绑定 (Events and Bindings)

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

作者头像
JNingWei
发布2018-09-28 14:48:04
7080
发布2018-09-28 14:48:04
举报
文章被收录于专栏:JNing的专栏JNing的专栏

目的

tkinter 获取 键盘输入鼠标输入

实现代码

代码语言:javascript
复制
# 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()

打印结果

代码语言:javascript
复制
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


本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年10月20日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 目的
  • 实现代码
    • 打印结果
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档