'How to get value from dependent combobox tkinter python?
I'm able to select both the combo box successfully but to print the second dropdown box value, I got lost. Could somebody explain how to print the Table value from the 2nd drop down box.
Note: The two drop downs are dependabale.
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title("ETL")
Environment = ["UAT","ITEST","PROD"]
Tables = [["USER_UAT","IP_UAT"],
["USER_ITEST","IP_ITEST"],
["USER_PROD","IP_PROD"]]
envi= ttk.Combobox(root,width =37, value=(Environment))
envi.grid(row=3,column=1,columnspan=2, padx=10, pady=2, sticky='w')
def callback(eventObject):
abc = eventObject.widget.get()
en = envi.get()
index=Environment.index(en)
tab.config(values=Tables[index])
tab=ttk.Combobox(root, width=37)
tab.grid(row=4,column=1,columnspan=2, padx=10, pady=2, sticky='w')
tab.bind('<Button-1>', callback)
root.mainloop()
Solution 1:[1]
The most straightforward way is to add a separate event binding for each combobox. I changed the bindings from <Button-1> to <<ComboBoxSelect>> as this prevents the events from being fired every time a combobox is clicked - instead, events will only fire when a selection is actually made.
I also added some code to set the combobox default values as well as to update the value of the second combobobox whenever a selection is made in the first combobox.
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title('ETL')
environment = ['UAT', 'ITEST', 'PROD']
tables = [
['USER_UAT', 'IP_UAT'],
['USER_ITEST', 'IP_ITEST'],
['USER_PROD', 'IP_PROD'],
]
def populate_table_combobox(event):
index = environment.index(env_combo.get())
table_combo.config(values=tables[index])
table_combo.current(0) # update the 'table' selection when 'env' changes
def get_table_combo_value(event):
print(table_combo.get()) # YOUR CODE HERE!
env_combo = ttk.Combobox(root, width=37, value=environment)
env_combo.current(0) # set default value
env_combo.grid(row=3, column=1, columnspan=2, padx=10, pady=2, sticky='w')
table_combo = ttk.Combobox(root, width=37, values=tables[0])
table_combo.current(0) # set default value
table_combo.grid(row=4, column=1, columnspan=2, padx=10, pady=2, sticky='w')
env_combo.bind('<<ComboBoxSelected>>', populate_table_combobox)
table_combo.bind('<<ComboBoxSelected>>', get_table_combo_value)
root.mainloop()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | JRiggles |
