首页 > 解决方案 > 如何在 Python Tkinter 中绑定 ComboBox 的 ListBox

问题描述

我正在寻找一个绑定,允许我根据用户按下的键放置一个特定的值。这是我执行此操作的示例代码:

from tkinter import *
from tkinter import ttk

v=Tk()

combo = ttk.Combobox(values=['item1','item2','item3','item4'], state='readonly')
combo.current(0)
combo.pack()

def function(Event):
    if(Event.char in '1234'):
        combo.set(f'item{Event.char}')

combo.bind('<Key>', function)
v.mainloop()

他们会告诉我“如果这样有效,你问这个做什么?” 事实证明,如果部署了 Combobox,则绑定将停止工作。问题如何解决?


我知道这部分问题不应该问,因为它与所讨论的问题无关。但是我想问一下,如果这个问题有问题,或者拼写错误,或者其他什么,请告知。“如何提出一个好问题”的页面对我没有帮助,因为从我的角度来看,我按照他们所说的去做。我尽我最大的努力使这里写的内容尽可能详细和易于理解。希望您的理解,谢谢。

标签: pythontkintercombobox

解决方案


根据 Henry Yik 的建议并研究 Event.widget 返回的内容,我找到了问题的解决方案。

from tkinter import *
from tkinter import ttk

v=Tk()

# I create two test combobox
for _ in range(2):
    combo = ttk.Combobox(values=['item1','item2','item3','item4'], state='readonly')
    combo.current(0)
    combo.pack()

# I create a test entry to test if the function correctly recognizes when it should be executed
entrada = Entry()
entrada.pack()

def function(Event):
    """
    If Event.widget is a str and ends with ".popdown.f.l" I consider it to be the Listbox,
    I get the path of the Combobox it belongs to and convert it to a widget.
    Afterwards, I set the value of Event.widget to that of the supposed combobox.
    """
    if(isinstance(Event.widget, str) and Event.widget.endswith(".popdown.f.l")):
        Event.widget = v._nametowidget(Event.widget[:-len(".popdown.f.l")])

        
    # If Event.widget is not a Combobox, it stops the execution of the function.
    if(not isinstance(Event.widget, ttk.Combobox)):
        return

    if(Event.char in '1234'):
        Event.widget.set(f'item{Event.char}')

v.bind_all('<Key>', function)
v.mainloop()

推荐阅读