当前位置:网站首页>Gui Gui programming (XIII) - event handling
Gui Gui programming (XIII) - event handling
2022-07-06 20:18:00 【Progress Xiaobai】
Thank you for opening Xiaobai's article
“ I hope you have made a little progress today , One step closer to a better life !”
Catalog
event Object common properties
Test keyboard and mouse events
Summary of various event binding methods
Summary of various event binding methods
Preface
One individual GUI The whole application life cycle is in a message cycle (event loop) in . It waits for the event to happen , And deal with it accordingly .Tkinter Provides a mechanism for handling related events . Handling functions can be bound to various events of various controls .
widget.bind(event, handler)
If relevant events occur raw , handler The function will be triggered , Event object event Will pass to handler function .
Mouse and keyboard events
Code | explain |
<Button-1> <ButtonPress-1> <1> | Press the left mouse button . 2 Right click ,3 Represents the middle key ; |
<ButtonRelease-1> | Release the left mouse button |
<B1-Motion> | Press and hold the left mouse button to move |
<Double-Button-1> | Double left click |
<Enter> | The mouse pointer enters a component area |
<Leave> | The mouse pointer leaves a component area |
<MouseWheel> | Scroll wheel ; |
<KeyPress-a> | Press down a key ,a You can use another key instead of |
<KeyRelease-a> | Release a key . |
<KeyPress-A> | Press down A key ( uppercase A) |
<Alt-KeyPress-a> | Press at the same time alt and a;alt You can use ctrl and shift replace |
<Double-KeyPress-a> | Two quick clicks a |
<Control-V> | CTRL and V The keys are pressed simultaneously ,V It can be changed to other key positions |
event Object common properties
name | explain |
char | Key characters , Valid only for keyboard events |
keycode | Key code , Valid only for keyboard events |
keysym | Key name , Only valid for keyboard events, such as pressing the spacebar : Keyed char: Keyed keycode:32 Keyed keysym:space For example, press a key : Keyed char:a Keyed keycode:65 Keyed keysym:a |
num | Mouse button , Valid only for mouse events |
type | The type of event triggered |
widget | The component that caused the event |
width,height | The size of the changed component , only Configure It works |
x,y | Current mouse position , Relative to the parent container |
x_root,y_root | Current mouse position , Relative to the whole screen |
Test keyboard and mouse events
# coding=utf-8
# Test keyboard and mouse events
from tkinter import *
root = Tk();root.geometry("530x300")
c1 = Canvas(root,width=300,height=300,bg="pink")
c1.pack()
def mouseTest(event):
print(" Left click position ( Relative to the parent container ):{0},{1}".format(event.x,event.y))
print(" Left click position ( Relative to the screen ):{0},{1}".format(event.x_root,event.y_root))
print(" Event bound components :{0}".format(event.widget))
def testDrag(event):
c1.create_oval(event.x,event.y,event.x+1,event.y+1)
def keyboardTest(event):
print(" Keyed keycode:{0}, Keyed char:{1}, Keyed keysym:{2}"
.format(event.keycode,event.char,event.keysym))
def press_a_test(event):
print("press a")
def release_a_test(event):
print("release a")
c1.bind("<Button-1>",mouseTest)
c1.bind("<B1-Motion>",testDrag)
root.bind("<KeyPress>",keyboardTest)
root.bind("<KeyPress-a>",press_a_test) # Only for lowercase a, uppercase A No use
root.bind("<KeyRelease-a>",release_a_test)
root.mainloop()
give the result as follows :
Casually write numbers , events , Mouse events and keyboard events .
lambda Expression details
lambda The expression defines an anonymous function , Only suitable for simple input parameters , Simple calculation returns results , Not suitable for complex functions .lambda The defined anonymous function also has input 、 There's also output , Just no name . The syntax is as follows :
lambda Parameter value list : expression The parameter value list is the input . The structure of expression evaluation is output .
Write One individual most Jane single Of case example : add3args = lambda x,y,z:x+y+z #print(add3args(10,20,30))
above lambda The expression is equivalent to the following function definition :
def add3args(x,y,z):
return x+y+z
lambda The parameter value list of the expression can be as follows :
lambda Format | explain |
lambda x, y: x*y | The function input is x and y, The output is their product x*y |
lambda:None | Function has no input parameters , The output is None |
lambda:aaa(3,4) | Function has no input parameters , The output is aaa(3,4) The knot of fruit |
lambda *args: sum(args) | The input is any number of parameters , The output is their sum |
lambda **kwargs: 1 | The input is any key value pair parameter , The output is |
️ test lambda usage
from tkinter import *
root = Tk();root.geometry("270x50")
def mouseTest1():
print("command The way , Simple case : It does not involve obtaining event object , have access to ")
def mouseTest2(a,b):
print("a={0},b={1}".format(a,b))
Button(root, text=" test command1",
command=mouseTest1).pack(side="left")
Button(root, text=" test command2",
command=lambda: mouseTest2(" Small ", " white ")).pack(side="left")
root.mainloop()
Select the event in the pop-up box .
Summary of various event binding methods
Binding of component objects
adopt command Attribute binding ( Suitable for simple without obtaining event object )
Button(root,text=” Sign in ”,command=login)
adopt bind() Method binding ( Suitable for the need to obtain event object )
c1 = Canvas(); c1.bind(“<Button-1>”,drawLine)
Binding of component classes
Call the object's bind_class function , Bind all components of this component class to events :
w.bind_class(“Widget”,”event”,eventhanler)
Summary of various event binding methods
from tkinter import *
root = Tk();root.geometry("270x30")
def mouseTest1(event):
print("bind() Methods the binding , Can get event object ")
print(event.widget)
def mouseTest2(a, b):
print("a={0},b={1}".format(a, b))
print("command Methods the binding , You can't get it directly event object ")
def mouseTest3(event):
print(" Right click on the event , Bound to all buttons !!")
print(event.widget)
b1 = Button(root, text=" test bind() binding ")
b1.pack(side="left")
# bind Bind events by
b1.bind("<Button-1>", mouseTest1)
# command Property is directly bound to the event
b2 = Button(root, text=" test command2",
command=lambda: mouseTest2(" The small white ", " come on. "))
b2.pack(side="left")
# To all Button Buttons are bound to right-click Events <Button-2>
b1.bind_class("Button", "<Button-2>", mouseTest3)
root.mainloop()
Looking back
GUI Graphical user interface programming ( One ): (278 Bar message ) GUI Graphical user interface programming ( One )_am_student The blog of -CSDN Blog
GUI Graphical user interface programming ( Two ):
GUI Graphical user interface programming ( 3、 ... and ):
GUI Graphical user interface programming ( Four ):
GUI Graphical user interface programming ( 5、 ... and ):
边栏推荐
- 【云原生与5G】微服务加持5G核心网
- Tencent byte Alibaba Xiaomi jd.com offer got a soft hand, and the teacher said it was great
- Error analysis ~csdn rebound shell error
- Cesium 两点之间的直线距离
- SQL injection 2
- Leetcode brush first_ Maximum Subarray
- 小微企业难做账?智能代账小工具快用起来
- AsyncHandler
- Enumeration gets values based on parameters
- 某东短信登录复活 安装部署教程
猜你喜欢
BeagleBoneBlack 上手记
beegfs高可用模式探讨
An East SMS login resurrection installation and deployment tutorial
Digital triangle model acwing 1018 Minimum toll
[Yann Lecun likes the red stone neural network made by minecraft]
BUUCTF---Reverse---easyre
B-杰哥的树(状压树形dp)
Oceanbase Community Edition OBD mode deployment mode stand-alone installation
报错分析~csdn反弹shell报错
Node. Js: express + MySQL realizes registration, login and identity authentication
随机推荐
Unity makes AB package
5. Nano - Net in wireless body: Top 10 "is it possible?" Questions
【GET-4】
使用ssh连接被拒
Linear distance between two points of cesium
String length limit?
JMeter server resource indicator monitoring (CPU, memory, etc.)
新一代垃圾回收器—ZGC
棋盘左上角到右下角方案数(2)
Tencent cloud database public cloud market ranks top 2!
语音识别(ASR)论文优选:全球最大的中英混合开源数据TALCS: An Open-Source Mandarin-English Code-Switching Corpus and a Speech
Standardized QCI characteristics
8086 instruction code summary (table)
Redisson bug analysis
数据的同步为每个站点创建触发器同步表
recyclerview gridlayout 平分中间空白区域
Crawler (14) - scrape redis distributed crawler (1) | detailed explanation
精彩编码 【进制转换】
方法关键字Deprecated,ExternalProcName,Final,ForceGenerate
Catch ball game 1