Python的事件与Tkinter的结合 [英] Python event binding with tkinter

查看:160
本文介绍了Python的事件与Tkinter的结合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,球员我是新来的GUI Python和我一直在试图理解envents过程中,这是我的code,而且每当我preSS的'a'键就应该打印意向键pressed,但它不会为我工作。

 #!的/ usr / bin中/ env的python3
# - * - 编码:UTF-8 - *从Tkinter的进口*根= TK()高清回调(事件):
    打印(键pressed)帆布=帆布(根,宽度= 100,高度= 100,BG ='蓝')
canvas.bind(A,回调)
canvas.pack()root.mainloop()


解决方案

由于该计划的重点是塔卡元素它不执行回调函数。如果换成 root.bind(A,回调)那行,你希望它会工作。

问题是,canvas元素不接收焦点,当你点击它像其他小部件作为入门,因此它只会回应,如果你先打电话KEYDOWN事件 canvas.focus_set()

So guys I'm new to GUIs in Python and I've been trying to understand the envents process, here's my code, and the intention that whenever I press the 'a' key it should print "key pressed'. But it won't work for me.

#!/usr/bin/env python3
# -*-coding:UTF-8 -*

from tkinter import *

root = Tk()

def callback(event):
    print("key pressed")

canvas = Canvas(root, width=100, height=100, bg='blue')
canvas.bind("a", callback)
canvas.pack()

root.mainloop()

解决方案

It doesn't execute the callback function because the focus of the program is on the Tk element. If you replace that line with root.bind("a", callback), it will work as you expect.

The problem is that the canvas element doesn't receive the focus when you click on it like other widgets as Entry, so it will only respond to keydown events if you call first canvas.focus_set().

这篇关于Python的事件与Tkinter的结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆