[英]How do I bind the ListBox of a ComboBox in Python Tkinter
我正在尋找一個綁定,允許我根據用戶按下的鍵放置某個值。 這是我在其中執行的示例代碼:
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.