tkinter窗口获得焦点时如何处理 [英] How to handle, when tkinter window gets focus

查看:596
本文介绍了tkinter窗口获得焦点时如何处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码:

from tkinter import *
w = Tk()
w.protocol('WM_TAKE_FOCUS', print('hello world'))
mainloop()

它只打印一次hello world,然后停止工作.不再有hello world基本上WM_TAKE_FOCUS不起作用.

解决方案

您可以将函数绑定到<FocusIn>事件.当您绑定到根窗口时,绑定将应用于根窗口中的每个窗口小部件,因此,如果您只想在整个窗口获得焦点时执行某些操作,则需要将event.widget与根窗口进行比较. /p>

例如:

import Tkinter as tk

def handle_focus(event):
    if event.widget == root:
        print("I have gained the focus")

root = tk.Tk()
entry1 = tk.Entry(root)
entry2 = tk.Entry(root)

entry1.pack()
entry2.pack()

root.bind("<FocusIn>", handle_focus)

root.mainloop()

I have this code:

from tkinter import *
w = Tk()
w.protocol('WM_TAKE_FOCUS', print('hello world'))
mainloop()

It prints hello world only once, and then it stops working. No more hello world Basically WM_TAKE_FOCUS does not work.

解决方案

You can bind a function to the <FocusIn> event. When you bind to the root window the binding is applied to every widget in the root window, so if you only want to do something when the window as a whole gets focus you'll need to compare event.widget to the root window.

For example:

import Tkinter as tk

def handle_focus(event):
    if event.widget == root:
        print("I have gained the focus")

root = tk.Tk()
entry1 = tk.Entry(root)
entry2 = tk.Entry(root)

entry1.pack()
entry2.pack()

root.bind("<FocusIn>", handle_focus)

root.mainloop()

这篇关于tkinter窗口获得焦点时如何处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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