Tracking whether a menu is closed or open is easily accomplished with a command and click binding. The hard part makes the menu close. Either a mouse click, or a mouse click, or pressing Escape will do this. But the generation of events does not occur. The following #commented_out bits represent failed experiments.
import tkinter as tk
root = tk.Tk()
n = 2
after_id = None
menu_open = False
omvar = tk.StringVar(root)
def timeout():
print('timeout called')
omvar.set('')
root.update()
def open(event):
print('open called')
global after_id, menu_open
after_id = root.after(n*1000, timeout)
menu_open = True
def close(val):
print('closed by', val)
global after_id, menu_open
root.after_cancel(after_id)
after_id = None
menu_open = False
om = tk.OptionMenu(root, omvar, 'a', 'b', 'c', command=close)
om.bind('<Button-1>', open)
om.pack()
root.mainloop()
The MenuButton + menu will look almost the same and could be simpler. Do you think that?
source
share