python - 如何在 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,则绑定将停止工作。问题如何解决?
我知道这部分问题不应该问,因为它与所讨论的问题无关。但是我想问一下,如果这个问题有问题,或者拼写错误,或者其他什么,请告知。“如何提出一个好问题”的页面对我没有帮助,因为从我的角度来看,我按照他们所说的去做。我尽我最大的努力使这里写的内容尽可能详细和易于理解。希望您的理解,谢谢。
解决方案
根据 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()
推荐阅读
- html - 表单字段不适合 Bootstrap 模式
- python-3.x - Python Flask 图像处理库
- groovy - 在 Groovy 中读取 \u0001 分隔文件
- aes - 使用没有身份验证标签的 Python 解密 AES GCM
- c# - 在 C# 控制台应用程序中生成文件路径时获取错误的文件路径
- swift - 调整已显示的 ViewController 的大小
- ansible - SCM 提交 ID/SHA 的 Ansible Tower 变量
- python-3.x - Python3在findall中使用带有正则表达式的f-string
- css - HTML iframe 在动画期间显示滚动条然后消失。CSS 溢出属性设置为隐藏
- sql - 如何从每个月内多次出现的重复值中选择 MAX(VALUE)?