Menubutton 小部件中的菜单打开似乎阻止了除箭头键、回车键和转义键之外的任何键输入。
我正在尝试将那个场景中的回车键的功能分配给另一个键,但这似乎是不可能的。
我想知道是否有任何方法可以做到这一点,如果没有,你们中的任何人是否可以指出任何可以完全取代菜单按钮的“自制”类(除了那个缺陷)。
提前感谢您的关注。
[我已经尝试将这些键(箭头、输入和 scape)的明显功能绑定到其他键;我试图找出这些键的命令的根源,以便它们能够在那种情况下工作;我试图解除绑定这些键的功能,看看我是否能找出它们是如何工作的;我尝试制作自己的类似 Menubutton 类(带有 blackjack 和 hookers)。我在所有这些任务中都惨遭失败。]
这是问题的一个小例子:
import tkinter as tk
def option1():
print("You've chosen option 1")
def option2():
print("You've chosen option 2")
def option3():
print("You've chosen option 3")
def SomethingSomething(event):
event.widget.event_generate('<Return>')
root = tk.Tk()
root.geometry("200x200")
options = ["Option 1", "Option 2", "Option 3"]
var = tk.StringVar(root)
var.set(options[0])
mb = tk.Menubutton(root, text="Select an option", relief="raised", width=20)
mb.menu = tk.Menu(mb, tearoff=0)
mb["menu"] = mb.menu
for option in options:
mb.menu.add_radiobutton(label=option, variable=var, value=option, command=eval("option" + str(options.index(option) + 1)))
mb.pack()
mb.bind('<Control-Key-5>', SomethingSomething)
root.mainloop()
peputito,是我,你,来自不久的将来。
我可能已经找到解决您的问题的方法,可以帮助世界各地处于完全相同情况的人们。
首先,我想澄清一下,我还没有找到问题发生的原因(在我看来,一旦发布了一个menubutton,键盘上除了方向键、return和escape之外,没有其他键可以工作)。
但是,我想出了一个非常不优雅的解决方案,可以实现您想要实现的目标:
def F_MenuButtonSelector(event):
widget = root.focus_get()
if isinstance(widget, tk.Menubutton):
radiobuttons = []
PossibleDict = []
CurrentDict = {}
for i in range(widget.menu.index("end")+1):
if widget.menu.type(i) == "radiobutton":
radiobuttons.append(widget.menu.entrycget(i, "label"))
for i in range(len(AllDicts)):
PossibleDict = list(eval(AllDicts[i]).keys())
if PossibleDict == radiobuttons:
CurrentDict = eval(AllDicts[i])
break
CurrentText = widget.cget("text")
index = PossibleDict.index([key for key, value in CurrentDict.items() if value == CurrentText][0])
maxindex = len(radiobuttons)-1
if event.keysym == "Down":
if index == maxindex:
index = 0
elif index != maxindex:
index = index + 1
elif event.keysym == "Up":
if index == 0:
index = maxindex
elif index != maxindex:
index = index - 1
widget.menu.invoke(index)
Ventana.bind("<Up>", F_MenuButtonSelector)
Ventana.bind("<Down>", F_MenuButtonSelector)
我在这里所做的是一种选择菜单按钮选项(使用您想要的任何键)而无需发布级联的方法。在我的特殊情况下,这是通过从菜单按钮中的单选按钮标签中列出一个列表,搜索起源它们的字典,查看当前显示在菜单按钮中的选项,将其转换为索引引用,然后调用我想要选择的下一个/上一个索引。
如前所述,它不是很优雅(如果我认为这意味着我认为那意味着什么),但它对我们俩都有用。
干杯,过去的peputito.
编辑:此外,由于我的很多菜单按钮选项在选择时显示为首字母缩写词(出于空间原因),我创建了一种方法来在每次选择选项时显示工具提示而不发布完整的级联(在级联中你可以看到完整的选项而不是首字母缩略词)。
我刚刚找到了我自己问题的答案(真正的答案)
如果其他人遇到同样的问题,在发布菜单按钮级联时使用您自己定义的键的唯一方法是将它们绑定到菜单按钮的菜单。
根据我上面的代码(问题中的代码),绑定应该是这样的:
mb.menu.bind('<Control-Key-5>', SomethingSomething)
我刚刚将我的操作系统更改为 linux,但我只能假设这在 Windows 上同样有效。
干杯。