Python tkinter Combobox
27,905
You can use bind()
to execute function on_select
when you select element on list.
cb.bind('<<ComboboxSelected>>', on_select)
and in this function you can fill Entry
.
Old example from GitHub: combobox-get-selection
#!/usr/bin/env python3
import tkinter as tk
import tkinter.ttk as ttk
# --- functions ---
def on_select(event=None):
print('----------------------------')
if event: # <-- this works only with bind because `command=` doesn't send event
print("event.widget:", event.widget.get())
for i, x in enumerate(all_comboboxes):
print("all_comboboxes[%d]: %s" % (i, x.get()))
# --- main ---
root = tk.Tk()
all_comboboxes = []
cb = ttk.Combobox(root, values=("1", "2", "3", "4", "5"))
cb.set("1")
cb.pack()
cb.bind('<<ComboboxSelected>>', on_select)
all_comboboxes.append(cb)
cb = ttk.Combobox(root, values=("A", "B", "C", "D", "E"))
cb.set("A")
cb.pack()
cb.bind('<<ComboboxSelected>>', on_select)
all_comboboxes.append(cb)
b = tk.Button(root, text="Show all selections", command=on_select)
b.pack()
root.mainloop()
EDIT:
Line if event:
in on_select
works only when you use bind()
because it executes function with information about event. command=
executes function without arguments and then it sets even=None
and then if event:
is always False
.
Author by
Thomas Caio
Updated on July 09, 2022Comments
-
Thomas Caio almost 2 years
I want to fill my entries when I click in a name of my Combobox without buttons like 'check' to show the values. How can i do that?
import tkinter as tk from tkinter import ttk import csv root = tk.Tk() cb = ttk.Combobox(root,state='readonly') labName = ttk.Label(root,text='Names: ') labTel = ttk.Label(root,text='TelNum:') labCity = ttk.Label(root,text='City: ') entTel = ttk.Entry(root,state='readonly') entCity = ttk.Entry(root,state='readonly') with open('file.csv','r',newline='') as file: reader = csv.reader(file,delimiter='\t') cb.grid(row=0,column=1) labName.grid(row=0,column=0) labTel.grid(row=1,column=0) entTel.grid(row=1,column=1) labCity.grid(row=2,column=0) entCity.grid(row=2,column=1)
-
Thomas Caio over 6 yearsI tried the same in my code and this did not work. In the 'if event:' condition the program is skipping and I'm using its same code. def on_select(event=None): print('----------------------------') if event: print("event.widget:", event.widget.get()) printing only '---------------'
-
furas over 6 yearsdo you bind
<<ComboboxSelected>>
or usecommand=
inButton
?bind
executes function with information about event - andif event
works, butButton
execute it without arguments and then it setsevent=None
soif event
is false. -
Thomas Caio over 6 yearsMy bad, I was using bind('<<ComboboxSelected>>',self.on_select()) instead of self.on_select without () Thanks again!