Day16 用python写UI-聊聊Binding events

绑定事件就是可以回传在执行时的动作位置,虽然说有很多的不同事件可以使用,但是要注意,当滑鼠与键盘同时绑定时会出现小陷阱,下面会有实例跟大家说明要怎麽解决这个问题喔~

语法:widget.bind(event,handler)

♠♣今天的文章大纲♥♦

  • 相关事件
  • 滑鼠绑定
  • 键盘与滑鼠绑定

相关事件

python tk 的事件有分成三种,滑鼠键盘跟控建

滑鼠事件:

<Button-1>

点选滑鼠一下,python shell印出当前点选的座标xy。1是点滑鼠左键,2是点滑鼠中间键,3是点右键,4是滑鼠滑轮向上滚动,5是滑鼠滑轮向下滚动。

<B1-Motion>

拖曳,按住滑鼠,python shell印出当前点选的座标xy。1是点滑鼠左键,2是点滑鼠中间键,3是点右键。

<ButtonRelease-1>

放开滑鼠,,python shell印出当前点选的座标xy。1是点滑鼠左键,2是点滑鼠中间键,3是点右键。

<Double-Button-1>

连按2下滑鼠,python shell印出当前点选的座标xy。1是点滑鼠左键,2是点滑鼠中间键,3是点右键。

<Motion>

滑鼠移动,python shell印出当前点选的座标xy。

<Enter>

滑鼠游标进入 Widget 控件。

<Leave>

滑鼠游标离开 Widget 控件。

键盘事件:

<Focusin>

键盘焦点进入 Widget 控件。

<FocusOut>

键盘焦点离开 Widget 控件。

<Return>

按下 Enter 键,键盘所有间接可以被绑定。

<Key>

按下某键盘键,键值会被储存在 event 物件中传递。

<Shift-Up>

按住 Shift 键时按下 Up 键。

<Alt-Up>

按住Alt 键时按下 Up 键。

<Ctrl-Up>

按住Ctrl 键时按下 Up 键。

控见事件:

<Configure>

新控件大小的 width 与 height 会存在event 物件内。


滑鼠绑定

import tkinter as tk

root = tk.Tk()


root.title('cuteluluWindow')
root.configure(bg="#7AFEC6")
root.iconbitmap('heart_green.ico')
root.geometry('300x180')

def cursors(event):
    print("Clicked at", event.x, event.y)

frame=tk.Frame (root, width = 300, height=180,bg="#7AFEC6")
frame.bind("<Button-1>", cursors)
frame.pack()


root.mainloop()

执行结果⬇⬇⬇
这边滑鼠形状是我电脑本身的,并不是程序码里面有改喔~如果想知道如何改滑鼠形状可以参考Day6~
https://ithelp.ithome.com.tw/upload/images/20211001/20140047lQVQE5QRKT.png
https://ithelp.ithome.com.tw/upload/images/20211001/20140047BWSVY1nkee.png


键盘与滑鼠绑定

import tkinter as tk

root = tk.Tk()
root.title('cuteluluWindow')
root.configure(bg="#7AFEC6")
root.iconbitmap('heart_green.ico')
root.geometry('300x150')

def key(event):
    print ("pressed",repr(event.char))

def cursors(event):
    frame.focus_set() #取得物件焦点
    print ("clicked at", event.x, event.y)

L=tk.Label(root,text="click your cursor first",
            font=("Algerian",15,"bold"),bg='#ADFEDC',fg='#00CACA')
L.pack()

frame = tk.Frame(root, width=300, height=150,bg="#7AFEC6")
frame.bind("<Key>", key)
frame.bind("<Button-1>", cursors)
frame.pack()

root.mainloop()

执行结果⬇⬇⬇
这边就是会出现小陷阱的地方,当执行这个程序码时,会发现按键盘没东西跑出来,所以就要在程序码里加入 frame.focus_set(),取得物件的焦点後,这样才可以正常执行喔~但还是要点滑鼠键在点键盘python shell才会出现位置资讯。
https://ithelp.ithome.com.tw/upload/images/20211001/20140047K7Vp0JwjDu.png
https://ithelp.ithome.com.tw/upload/images/20211001/201400477eA7sahG34.png


今天文章重点就是,当滑鼠与键盘同时绑定时,需要多加一行程序码frame.focus_set(),让两个都可以顺利地绑定~
/images/emoticon/emoticon12.gif


<<:  [Day17]What is Merkle tree? - 2

>>:  大共享时代系列_015_旅行进行式

xampp 多个网站 必须重启I-040GW 才可连上 浮动IP no-ip

各位前辈好 这个问题困扰我一年多了,真的找不到问题点所以提出 我的问题跟这位很像 我的原先设定是 使...

python入门学习day 2

#初学程序语言的你为什麽需要有GitHub? #Git & Github区别在哪里?? Gi...

手机节省行动数据的几个方法 4G 吃不饱

手机节省行动数据的几个方法 4G 吃不饱 没有学生方案 或者是低流量限速方案吃到饱方案 只能从关掉手...

[Day06] 用 .NET 实做简单的 RESTful API

HTTP request 上次我们建立了一个直接能跑的专案,但是它只有一个回传随机天气的 API 接...

【PHP Telegram Bot】Day15 - 基础(4):阵列处理、JSON

阵列就像是个大柜子,可以存放好多好多的东西 阵列赋值、取值 可以由两种格式产生(两者相等): $a...