Reputation: 11
I am trying to learn how to use ttk Combo box and got as far as setting it up, populating, getting it to respond to selection of a listed item using a button control and alternatively binding to the ComboboxSelected event. The latter works for listed items coded in but I am missing something to make it work for an entry typed into the Combo box. I can type in an item and it will respond if I click a button but typing in an item and pressing enter does not work. I am trying to get the combo box fully functional without a button.
import tkinter as tk
from tkinter import ttk
window = tk.Tk()
window.minsize(600, 400)
window.title("ttk Combo box")
def chooseNumbers():
label.configure(text = "You Selected " + mynumber.get())
def callbackfn(event):
label.configure(text = "You Have Selected " + mynumber.get())
label = ttk.Label(window, text = "Choose A Number")
label.grid(column = 0, row = 0)
mynumber = tk.StringVar()
combobox = ttk.Combobox(window, width = 15 , textvariable = mynumber,state='normal')
combobox['values'] = (5,6,7,8,9,10,12,14,15)
combobox.grid(column = 0, row = 1)
button = ttk.Button(window, text = "Click Me", command = chooseNumbers) # don't want this
button.grid(column = 1, row = 1)
combobox.bind("<<ComboboxSelected>>",callbackfn) # how to get this to work with keyboard entry?
window.mainloop()
Upvotes: 1
Views: 1754
Reputation: 12672
Is this what you want?
import tkinter as tk
from tkinter import ttk
window = tk.Tk()
window.minsize(600, 400)
window.title("ttk Combo box")
def chooseNumbers(event):
label.configure(text = "You Selected " + mynumber.get())
def callbackfn(event):
label.configure(text = "You Have Selected " + mynumber.get())
label = ttk.Label(window, text = "Choose A Number")
label.grid(column = 0, row = 0)
mynumber = tk.StringVar()
combobox = ttk.Combobox(window, width = 15 , textvariable = mynumber,state='normal')
combobox['values'] = (5,6,7,8,9,10,12,14,15)
combobox.grid(column = 0, row = 1)
combobox.bind("<<ComboboxSelected>>",callbackfn) # how to get this to work with keyboard entry?
combobox.bind("<Return>",chooseNumbers)
window.mainloop()
When you press button Enter
,It will show "You Selected x".Just bind a event <Return>
and call a function.
Upvotes: 2