Search code examples
pythonwindowstkintercombobox

How to solve the problem that the dropdown list of ttk.Combobox remains visible after Alt+Tab in Win10


After clicking on the combobox, the dropdown list is shown. Press Alt+Tab (Win10) to switch to other application and find that the dropdown list remains visible while the test application itself is hidden.

Also there is no <FocusOut> event received for root or combo itself.

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.geometry("300x200")

combo = ttk.Combobox(root, state="readonly")
combo['values'] = ["Option 1", "Option 2", "Option 3"]
combo.bind('<Button-1>', lambda event: root.after(2000, lambda: webbrowser.open("https://stackoverflow.com")))
combo.pack()

root.mainloop()

With Python 3.12.4

Before Alt+Tab: dropdown is shown

After Alt+Tab: dropdown remains visible

I expect the dropdown disappears along with the test application itself. Also I'd like to receive <FocusOut> event for root


Solution

  • This may be a bit of brute force, but you could try redirecting focus to the root window when the Alt key is pressed. This way, the combobox menu closes as soon as the keypress is detected.

    bind_all is used here in order to bind to the children of combo as well (i.e., the menu window).

    combo.bind_all('<Alt_L>', lambda _: root.focus())
    

    Note that you'll probably also want to add a binding for '<Alt_R>'