有没有办法在 python 中的 2 个小部件上检测 FocusOut 事件

Is there a way to detect a FocusOut event on 2 widgets in python

我想要的是只要我在 dateEntry 小部件上就可以自由选择日期(即使我单击向下箭头也不会破坏这个小部件)并销毁最后一个(dateEntry)如果我点击其他地方。

问题是 tkcalender 是由多个小部件创建的,这就是 focusOut 事件仅在其中一个小部件上设置的原因。

from tkinter import *
from tkcalendar import DateEntry

def ok(e):
    print(cal.get_date())


root = Tk()
cal = DateEntry(root, year=2010)
cal.pack(padx=10, pady=10)
cal.bind('<FocusOut>', lambda e: cal.destroy())
cal.bind('<Return>', ok)  # validate with Enter
cal.focus_set()

root.mainloop()

如果你 运行 代码然后你点击 DateEntry 的箭头,这个被破坏了,我希望这个留在那儿,直到你点击 window 中的其他地方销毁。

如果我没理解错的话,您希望 DateEntry 在您单击打开日历时不被破坏。这可以通过检查您当前的焦点和 pass 如果当前焦点是 Calendar 对象来实现。

import tkinter as tk
from tkcalendar import DateEntry, Calendar

def check_focus(event):
    current = root.focus_get()
    if not isinstance(current,Calendar):
        cal.destroy()

root = tk.Tk()

cal = DateEntry(root, year=2010)
cal.pack(padx=10, pady=10)
cal.bind('<FocusOut>', check_focus)
tk.Button(root,text="Click").pack()

root.mainloop()

尝试按 Tab 键更改焦点并查看。