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

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

问题描述

我想做一个功能:当我在 tkinter 中的组合框被点击并打开下拉菜单时,当你按下任意键(例如s")时,它会选择组合框中的第一个元素,以s"字母开头.但是我不知道如何将它直接绑定到由组合框创建的列表框.如果我将 keyPress 事件绑定到组合框,当下拉菜单打开时它不会接收事件.

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天全站免登陆