查了资料发现canvas绑定键盘需要调用focus_set

昨天查了资料,看到例子里面有画布绑定键盘wasd字母做方向控制的代码。

后面再调用canvas.focus_set(),试了例子发现可以canvas绑定键盘事件。

所以想到上次绑定不成功的原因了。

做了个测试程序,测试一下键盘的向左、向右、向上、向下绑定到canvas

测试结果成功!

F:\Temp\stk_dbg>cankey.py

do_Enter

do_Motion

。。。

do_Leave

do_Left

do_Right

do_Up

do_Down

代码如下:

#!/usr/bin/env python

# -*- coding:gb2312 -*-


from tkinter import *  


class App:

def __init__(self):

self.root = Tk()

self.root.title('Canvas绑定鼠标事件键盘事件测试...')

self.cvs = Canvas(self.root, width=800, height=600, bg='black', cursor='crosshair')

self.cvs.pack() #fill=BOTH, expand=1

#self.root.resizable(0,0)

# 鼠标进入退出移动

self.cvs.bind('<Enter>', self.do_Enter)

self.cvs.bind('<Leave>', self.do_Leave)

self.cvs.bind('<Motion>', self.do_Motion)

# 按键向左向右向上向下

self.cvs.bind('<Left>', self.do_Left)

self.cvs.bind('<Right>', self.do_Right)

self.cvs.bind('<Up>', self.do_Up)

self.cvs.bind('<Down>', self.do_Down)

self.cvs.focus_set() # 这个不设置的话按键会没反应!


def do_Enter(self, event):

print('do_Enter')


def do_Leave(self, event):

print('do_Leave')


def do_Motion(self, event):

print('do_Motion')


def do_Left(self, event):

print('do_Left')


def do_Right(self, event):

print('do_Right')


def do_Up(self, event):

print('do_Up')


def do_Down(self, event):

print('do_Down')


def Run(self):

self.root.mainloop()


app = App()

app.Run()


评论
©appall | Powered by LOFTER