Tkinter Menubar And Checkbox Keep Open
I am making a menubar in tkinter in one of the menu in the menu bar, I have some check_button and when one of these check_button is clicked, the menu closes, but I want to keep thi
Solution 1:
Below example opens View back each time a checkbutton is selected:
import tkinter as tk
root = tk.Tk()
test1, test2 = tk.BooleanVar(), tk.BooleanVar()
def cb():
print(test1.get(), test2.get())
root.tk.call('::tk::TraverseToMenu', root, 'v')
menubar = tk.Menu(root)
viewMenu = tk.Menu(menubar, tearoff = 0)
viewMenu.add_checkbutton(label = "Obstacles", variable = test1, command=cb)
viewMenu.add_checkbutton(label = "Ground", variable = test2, command=cb)
menubar.add_cascade(menu = viewMenu, label = "View")
root.config(menu = menubar) # win = tk.Tk()
root.mainloop()
Based on the answer that accounts for windows' special case here a very similar code can be written as follows:
import tkinter as tk
root = tk.Tk()
if root._windowingsystem == 'win32':
import ctypes
keybd_event = ctypes.windll.user32.keybd_event
alt_key = 0x12
key_up = 0x0002deftraverse_to_menu(key=''):
if key:
ansi_key = ord(key.upper())
# press alt + key
keybd_event(alt_key, 0, 0, 0)
keybd_event(ansi_key, 0, 0, 0)
# release alt + key
keybd_event(ansi_key, 0, key_up, 0)
keybd_event(alt_key, 0, key_up, 0)
else:
# root._windowingsystem == 'x11'deftraverse_to_menu(key=''):
root.tk.call('tk::TraverseToMenu', root, key)
test1, test2 = tk.BooleanVar(), tk.BooleanVar()
menubar = tk.Menu(root)
viewMenu = tk.Menu(menubar, tearoff = 0)
viewMenu.add_checkbutton(label = "Obstacles", variable = test1,
command=lambda : traverse_to_menu('v'))
viewMenu.add_checkbutton(label = "Ground", variable = test2,
command=lambda : traverse_to_menu('v'))
menubar.add_cascade(menu = viewMenu, label = "View")
root.config(menu = menubar) # win = tk.Tk()
root.mainloop()
key
variable to the traverse_to_menu
is 'v'
as Alt - V opens the menu via keyboard. As in key
needs to be the non-modifying key that by default opens the menu using keyboard.
Solution 2:
In my case, I did as follows:
first creating primary things as
window=Tk()
mb = Menubutton (window, text="Test", relief=RAISED)
var = BooleanVar()
Then adding some checkbutton as below:
mb.menu.add_checkbutton(label='Test btn', variable=var,command = lambda: menu_click("some input"))
#adding some other checkbuttons
Finally creating menu_click function:
def menu_click(input):
if input == "some input":
mb.menu.post(mb.winfo_rootx(), mb.winfo_rooty())
In which mb.winfo_rootx(), mb.winfo_rooty()
are x and y coordinates of desired opennig location.
Post a Comment for "Tkinter Menubar And Checkbox Keep Open"