Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Connect two comboboxes via a dictionary (with the purpose to display male or female names in the combobox)

I have a combobox where I select the gender Male or Female. Then I have another combobox where now all the names of people are displayed (without distinction of gender).

I would like to select Male from the first combobox and automatically display (without button) the Male names in the second combobox. The same thing for Female names. Thank you

from tkinter import ttk
import tkinter as tk
from tkinter import *

window = tk.Tk()  
window.attributes('-zoomed', True)
window.configure(bg='#f3f2f2')

style = ttk.Style(window)
style.theme_use('clam')

John = {"Name": "John", "Years": 1980, "Gender": "Male"}
Linda = {"Name": "Linda", "Years": 1983, "Gender": "Female"}
Martin = {"Name": "Martin", "Years": 1981, "Gender": "Male"}


gender=ttk.Combobox(window, width = 12)
gender.place(x=5, y=60)
gender['value'] = ["Male", "Female"]
gender.set("Gender?")

all_name=ttk.Combobox(window, width = 12)
all_name.place(x=150, y=60)
all_name['value'] = [x["Name"] for x in [John, Linda, Martin]]
all_name.set("All Name")



window.mainloop()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can bind <<ComboboxSelected>> event on gender and update value option of all_name inside the event callback:

...
def on_gender_selected(event):
    selected = gender.get()
    # get the names for selected gender
    all_name['value'] = [x['Name'] for x in [John, Linda, Martin] if x['Gender'] == selected]
    all_name.set('') # clear current selection

gender.bind('<<ComboboxSelected>>', on_gender_selected)
...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading