python Judgement Example of Mouse and Button Binding Event
- 2021-07-22 10:00:22
- OfStack
When multiple events are bound to the same command, how to determine which event occurred when different events are processed within the command? Use the following to detect. After testing, tab keys and alt keys cannot be recognized, and other single ones can be recognized.
There is also an type attribute of the event. This tested keyboard event returns Character 2 and the mouse returns Character 2. You can judge whether it is a keyboard event or a mouse event according to this.
# <Button-1> Left mouse click event
# <Button-2> : Middle mouse click event
# <Button-3> Right-click event
# <Double-Button-1> : Double-click event
# <Triple-Button-1> : 3 Hit event
from tkinter import *
tk = Tk()
canvas = Canvas(width=500,height=500)
canvas.pack()
#canvas.create_polygon(0,0,250,250,fill = 'red')
def echo_event(evt):
# Print keyboard events
if evt.type == "2":
print(" Keyboard: %s" % evt.keysym)
# Print mouse operation
if evt.type == "4":
print(" Mouse: %s" % evt.num)
#
print(evt.type)
# Keyboard event
canvas.bind_all("<KeyPress>",echo_event)
# If the specified keyboard is bound, the "<Key>" Or "<KeyPress>" Can be specific to the words of the specified key followed by the underline and the specified key is good, such as: binding lowercase letters t And Left Key
canvas.bind_all("<KeyPress-t>",echo_event)
canvas.bind_all("<KeyPress-Left>",echo_event)
# Mouse event
canvas.bind_all("<Double-Button-1>",echo_event)
canvas.bind_all("<Button-1>",echo_event)
canvas.bind_all("<Button-2>",echo_event)
canvas.bind_all("<Button-3>",echo_event)