简体   繁体   English

Tkinter Combobox 动态设置值

[英]Tkinter Combobox dynamically set values

I'm attempting to set the options of a Tkinter Combobox dynamically.我正在尝试动态设置 Tkinter Combobox 的选项。 My code almost works, and I'm not sure why.我的代码几乎可以工作,我不确定为什么。

The code is designed to allow typing a string into an Entry box.该代码旨在允许在输入框中键入字符串。 It then searches through a list for any items that contain that string.然后在列表中搜索包含该字符串的任何项目。 So for example, if you type例如,如果您键入

Mi

into the entry box the list becomes进入输入框,列表变为

['Mickey', 'Minnie'] ['米奇','米妮']

All this works as expected.所有这些都按预期工作。

The Combobox [values] attribute is supposed to update whenever <FocusIn> is triggered using a function. Combobox [values]属性应该在使用函数触发<FocusIn>时更新。 This does indeed happen, but only after I click on the Combobox twice.这确实发生了,但只有在我单击组合框两次之后。 I'm not sure why clicking on it the first time doesn't trigger the <FocusIn> binding.我不确定为什么第一次点击它不会触发<FocusIn>绑定。 Is this the wrong binding?这是错误的绑定吗? Is there something about my lambda function that isn't quite right?我的 lambda 函数有什么地方不太正确吗? Would love some help!希望得到一些帮助!

Code:代码:

from tkinter import *
from tkinter import ttk

init_list = ['Mickey', 'Minnie', 'Donald', 'Pluto', 'Goofy']

def db_values():
    i = inp_var.get()
    db_list = [x for x in init_list if i in x]
    print(db_list)
    return db_list

def db_refresh(event):
    db['values'] = db_values()

root = Tk()
title_label = Label(root, text="Partial string example")
title_label.grid(column=0, row=0)

inp_var = StringVar()
input_box = Entry(root, textvariable=inp_var)
input_box.grid(column=0, row=1)

name_selected = StringVar()
db = ttk.Combobox(root, textvariable=name_selected)
db['values'] = db_values()
db.bind('<FocusIn>', lambda event: db_refresh(event))
db.grid(column=0, row=2, sticky=EW, columnspan=3, padx=5, pady=2)

root.mainloop()
def db_values():
    i = inp_var.get()
    db_list = [x for x in init_list if i in x]
    print(db_list)
    db['values'] = db_values()

Only this small Change is requires.只有这个小改动是需要的。 list value must be assigned in the function itself.必须在函数本身中分配列表值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM