我试图在tkinter中创建一个应用程序,该应用程序有一个下拉菜单,允许多次选择。问题是,当我选择一个选项,菜单撤回,我必须重新打开它手动选择下一个选项。有没有办法让下拉菜单保持打开状态直到,比如,点击应用内外的某个地方或者直到我再次点击下拉菜单的顶部?
import tkinter as tk
def update_selected_options(option, var, selected_options):
if var.get():
selected_options.append(option)
else:
selected_options.remove(option)
print(selected_options)
def select_option(option, var, selected_options):
update_selected_options(option, var, selected_options)
def create_dropdown(parent, options):
selected_options = []
# create menubutton
menubutton = tk.Menubutton(parent, text="Choose options", indicatoron=True, borderwidth=1, relief="raised")
menu = tk.Menu(menubutton, tearoff=True)
menubutton.configure(menu=menu)
menubutton.pack(padx=10, pady=10)
# add checkbuttons to menu
for option in options:
var = tk.BooleanVar(value=False)
menu.add_checkbutton(label=option, variable=var, onvalue=True, offvalue=False, command=lambda option=option, var=var: select_option(option, var, selected_options))
# keep menu open after an option is selected
menu.postcommand = lambda: menubutton.config(state="active")
return menubutton
if __name__ == "__main__":
root = tk.Tk()
options = ["Option 1", "Option 2", "Option 3"]
menubutton = create_dropdown(root, options)
root.mainloop()
我找到了这个menu.postcommand = lambda: menubutton.config(state="active")
,但它似乎不能正确地完成工作
我对你的代码做了一些小的改变,但是解决你的问题的主线是menu.post(menubutton.winfo_rootx(), menubutton.winfo_rooty() + menubutton.winfo_height())
。我从这个问题中得到的。基本上,每次调用select_option
函数时,它都会在menubutton
的位置重新打开drop-down menu
。当你将+100
添加到x或y坐标时,你就可以得到这个想法。
import tkinter as tk
def select_option(option, var):
global selected_options
if var.get():
selected_options.append(option)
else:
selected_options.remove(option)
print(selected_options)
menu.post(menubutton.winfo_rootx(), menubutton.winfo_rooty() + menubutton.winfo_height())
if __name__ == "__main__":
root = tk.Tk()
options = ["Option 1", "Option 2", "Option 3"]
selected_options = []
# create menubutton
menubutton = tk.Menubutton(root, text="Choose options", indicatoron=True, activeforeground='blue', highlightcolor='blue', borderwidth=1, relief="raised")
menu = tk.Menu(menubutton, tearoff=False, activeborderwidth=10, activeforeground='blue')
menubutton.configure(menu=menu)
menubutton.pack(padx=10, pady=10)
# add checkbuttons to menu
for option in options:
var = tk.BooleanVar(value=False)
menu.add_checkbutton(label=option, variable=var, onvalue=True, offvalue=False, command=lambda option=option, var=var: select_option(option, var))
root.mainloop()