首页 > 解决方案 > 悬停在其上时如何打开与 ttk.Menubutton 相关的菜单?

问题描述

我想在 中做一个自定义菜单栏Tkinter,但由于无法调整,我不得不制作拐杖。Frame我从和Button制作了一个自定义菜单Menubutton。但我遇到了一个小问题 - 悬停时无法打开菜单ttk.Menubutton。也就是说,我需要将鼠标悬停在 Menubutton 上时,附加到该按钮的菜单会打开(模拟单击Menubutton)。如何实施?

代码

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

root.option_add("*Menu.borderWidth", "0")
root.option_add("*Menu.activeBorderWidth", "0")
root.option_add("*Menu.background", "black")


style = ttk.Style(root)

fr = ttk.Frame(root)

btn_menu = ttk.Menubutton(fr, text='fegvd')
btn_menu.grid(row=0, column=0)

btn =ttk.Button(fr, text='grfbvgfev')
btn.grid(row=0, column=1)

btn_menu_st = ttk.Menubutton(fr, text='Gds')
btn_menu_st.grid(row=0, column=2)

fr.pack(fill='x')


file = tk.Menu(btn_menu, tearoff=0, foreground='white')
file.add_command(label='ГЫГ')

style = tk.Menu(btn_menu_st, tearoff=0, foreground='white')
style.add_command(label='Ugu')

btn_menu.configure(menu=file)
btn_menu_st.configure(menu=style)


root.mainloop()

标签: pythonpython-3.xtkintermenuttk

解决方案


也许有更好的想法来实现它。我的想法是发送鼠标事件。

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

root.option_add("*Menu.borderWidth", "0")
root.option_add("*Menu.activeBorderWidth", "0")
root.option_add("*Menu.background", "black")


style = ttk.Style(root)

fr = ttk.Frame(root)

btn_menu = ttk.Menubutton(fr, text='fegvd')
btn_menu.grid(row=0, column=0)

def func1(e):
    e.widget.event_generate("<Button-1>") # send a mouse press event

btn_menu.bind("<Enter>",func1) # when your mouse enter this widget
btn =ttk.Button(fr, text='grfbvgfev')
btn.grid(row=0, column=1)

btn_menu_st = ttk.Menubutton(fr, text='Gds')
btn_menu_st.grid(row=0, column=2)

fr.pack(fill='x')


file = tk.Menu(btn_menu, tearoff=0, foreground='white')
file.add_command(label='ГЫГ')

style = tk.Menu(btn_menu_st, tearoff=0, foreground='white')
style.add_command(label='Ugu')

btn_menu.configure(menu=file)
btn_menu_st.configure(menu=style)


root.mainloop()

我发现.post可以做一个很好的方法。

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

root.option_add("*Menu.borderWidth", "0")
root.option_add("*Menu.activeBorderWidth", "0")
root.option_add("*Menu.background", "black")


style = ttk.Style(root)

fr = ttk.Frame(root)

btn_menu = ttk.Menubutton(fr, text='fegvd')
btn_menu.grid(row=0, column=0)
def func1(e):
    file.post(e.widget.winfo_rootx(),e.widget.winfo_rooty()+e.widget.winfo_height())

btn_menu.bind("<Enter>",func1)
btn =ttk.Button(fr, text='grfbvgfev')
btn.grid(row=0, column=1)

btn_menu_st = ttk.Menubutton(fr, text='Gds')
btn_menu_st.grid(row=0, column=2)

fr.pack(fill='x')


file = tk.Menu(btn_menu, tearoff=0, foreground='white')
file.add_command(label='ГЫГ')

style = tk.Menu(btn_menu_st, tearoff=0, foreground='white')
style.add_command(label='Ugu')

btn_menu.configure(menu=file)
btn_menu_st.configure(menu=style)

root.mainloop()

.unpost不能在我的电脑上工作,我发现了这个问题


推荐阅读