[Python] Updating dictionary values

Discussão em 'Python' iniciado por Stack, Junho 20, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to build a program that will display multiple teams with their status. An option menu is used to select a team and then change the corresponding value in a dictionary which would change the team's status label example: Team A shows "Inactive" when launching the program but then after team a is selected in the option menu, and the button is pressed, the corresponding label would change to "Active".

    import tkinter as tk
    from tkinter import StringVar

    # Sample dictionary to update
    team_data = {
    "Team A":"Active",
    "Team B":"Inactive",
    "Team C":"Inactive"}
    }

    def update_team_data():
    selected_team = team_var.get()
    if selected_team in team_data:
    # Increment the status for the selected team
    team_data[selected_team]["Inactive"] = ["Active"]
    result_label.config(text=f"{selected_team} status updated to {team_data[selected_team]['Active']}")
    else:
    result_label.config(text="Invalid team selected!")

    # Create the main Tkinter window
    root = tk.Tk()
    root.title("Update Team Data")

    # Create a StringVar for the OptionMenu
    team_var = StringVar()
    team_var.set("Select a Team") # Default value

    # Create an OptionMenu for team selection
    team_menu = tk.OptionMenu(root, team_var, *team_data.keys())
    team_menu.pack(pady=10)

    # Create a button to trigger the update
    update_button = tk.Button(root, text="Update Team", command=update_team_data)
    update_button.pack(pady=10)

    # Label to display the result
    result_label = tk.Label(root, text="")
    result_label.pack(pady=10)

    # Convert dictionary to a readable string
    options_text = "\n".join([f"{key}: {value}" for key, value in team_data.items()])

    # Create a label to display the dictionary options
    label = tk.Label(root, text=options_text, font=("Arial", 12), justify="left", padx=10, pady=10)
    label.pack()

    # Run the application
    root.mainloop()




    # Run the Tkinter event loop
    root.mainloop()

    Continue reading...

Compartilhe esta Página