如何在Tkinter Python 3.7中为组合框退出菜单绑定按键事件 [英] How to bind keypress event for combobox drop-out menu in tkinter Python 3.7

查看:144
本文介绍了如何在Tkinter Python 3.7中为组合框退出菜单绑定按键事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要创建一个功能:单击tkinter中的组合框并打开下拉菜单时,当您按任意键(例如 s)时,它将选择组合框中的第一个元素,以 s字母开头。
但是我找不到如何将其直接绑定到由combobox创建的listBox的方法。如果我将keyPress事件绑定到combobox,则在打开下拉菜单时它不会接收事件。

I want to make a feature: when my combobox in tkinter clicked and drop-down menu is opened, when you press any key (for example 's'), it selects first element in combobox, starting with 's' letter. But I cannot find out, how to bind it straight to listBox, which is created by combobox. If I bind keyPress events to combobox, it does not receive events, when drop-down menu opened.

因此,我尝试了以下操作: self.combobox.bind(< KeyPress>,self.keyPressed)但没有成功。

So, I tried stuff like this: self.combobox.bind("<KeyPress>", self.keyPressed) but no success.

能否请你给我建议怎么做?还是完全有可能?

Can you please advice me the way how to do that? Or if it possible at all?

更新:小代码示例

import tkinter as tk
from tkinter import ttk

def pressed(evt):
    print ("key pressed")

f = tk.Frame();
f.grid()
c = ttk.Combobox(f,values = ["alfa","betta","gamma"])
c.grid(column = 0, row = 0)
c.bind("<KeyRelease>",pressed)
f.mainloop()


推荐答案

据我了解,目前尚无法在Python中获取弹出菜单。而且您必须通过TCL做到这一点。弱点是参考的 .f.l部分,因为它取决于内部小部件的实现。有一个组合框的示例,当您按下键盘按钮时,将按字母的顺序选择项目。

As far as I understood, there no way to get popdown menu in Python currently. And you have to do that through TCL. The weak point is ".f.l" part of reference as it depends on internal widgets implementation. There is an example of combobox, wich will select items by first their letter when you press a keyboard button.

from tkinter import ttk
import itertools as it

class mycombobox(ttk.Combobox):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        pd = self.tk.call('ttk::combobox::PopdownWindow', self) #get popdownWindow reference 
        lb = pd + '.f.l' #get popdown listbox
        self._bind(('bind', lb),"<KeyPress>",self.popup_key_pressed,None)

    def popup_key_pressed(self,evt):
        values = self.cget("values")
        for i in it.chain(range(self.current() + 1,len(values)),range(0,self.current())):
            if evt.char.lower() == values[i][0].lower():
                self.current(i)
                self.icursor(i)
                self.tk.eval(evt.widget + ' selection clear 0 end') #clear current selection
                self.tk.eval(evt.widget + ' selection set ' + str(i)) #select new element
                self.tk.eval(evt.widget + ' see ' + str(i)) #spin combobox popdown for selected element will be visible
                return

这篇关于如何在Tkinter Python 3.7中为组合框退出菜单绑定按键事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆