我创建了一个Combobox GUI,允许用户通过在键盘上输入字母来搜索Combobox。
例如,如果用户输入字母“L”,它将在Combobox下拉列表中搜索以字母“L”开头的单词的第一次出现。
我只能在下拉列表关闭时搜索Combobox。下拉列表打开时是否可以搜索Combobox?这是我的代码。
import tkinter as tk
from tkinter import StringVar, Label, Button
from tkinter import font
from tkinter.ttk import Combobox
from string import ascii_uppercase
class Parking_Gui(tk.Frame):
PARKING_LOTS = ('ARTX', 'BURG', 'CLAY_HALL', 'GLAB', 'HAMH_HUTC',
'HHPA', 'JVIC', 'LIBR', 'PLSU', 'POST', 'PROF',
'STEC', 'STRO_NORTH', 'STRO_WEST', 'TROP')
def __init__(self):
"""Sets up the window and widgets"""
tk.Frame.__init__(self)
self.myfont = font.Font(family="Calibri", size=11, weight="normal")
self.master.geometry("315x125")
self.master.title("MSU PARKING APP")
self.master.rowconfigure(0, weight = 1)
self.master.columnconfigure(0, weight = 1)
self.grid(sticky = 'NW')
# Label for the parking lots
self.LotLabel = tk.Label(self, text = "MSU Parking", font=self.myfont)
self.LotLabel.grid(row = 0, column = 0)
# Combobox for parking lots
self._ComboValue = tk.StringVar()
self._LotCombo = Combobox(self, textvariable=self._ComboValue,
state='readonly', height = '6',
justify = 'center', font=self.myfont)
# List of parking lots loaded into Combobox
self._LotCombo['values']= Parking_Gui.PARKING_LOTS
self._LotCombo.grid(row = 0, column = 1)
# Button to open parking diagram
self._button = tk.Button(self, text = "Open", font=self.myfont)
self._button.bind('<Button-1>', self._runParkingLot)
self._button.grid(row = 0, column = 2)
# Press enter to open selected parking diagram
self._LotCombo.bind("<Return>", self._runParkingLot)
# Search Combobox values with keyboard
self._LotCombo.bind("<Key>", self.findInBox)
self._LotCombo.focus()
def _runParkingLot(self, event):
"""Event handler for the button. Will run the
functinon associated with selected item"""
parkingLot = self._LotCombo.get()
"""The 'globals' keyword, will return a dictionary of every function,
variable, etc. currently defined within the global scope."""
if parkingLot in globals():
func = globals()[parkingLot]
func()
def findInBox(self, event):
"""findInBox method allows user to search through PARKING_LOTS
list values by keyboard press"""
keypress = event.char.upper()
# If user key press is in the alphabet
if keypress in ascii_uppercase:
for index, lot_name in enumerate(Parking_Gui.PARKING_LOTS):
if lot_name.startswith(keypress):
self._LotCombo.current(index)
break
def main():
Parking_Gui().mainloop()
main()