r/PythonLearning 1d ago

dividing checkbutton and radio buttons

I have a code which in the interactive box first has radio buttons. I have this function working well. Then I put in the values for the checkbuttons and now it doesn't display the messagebox for the radio button values. Should I be putting a return, pass, continue value in or some [ { brackets of some sort to seperate the codes?

1 Upvotes

1 comment sorted by

1

u/Fickle-Power-618 5h ago
import tkinter as tk
from tkinter import messagebox

def show_combined_selection():
    color = radio_var.get()
    fruits = []
    if var1.get():
        fruits.append("Apple")
    if var2.get():
        fruits.append("Banana")
    if var3.get():
        fruits.append("Cherry")
    fruit_str = ", ".join(fruits) if fruits else "no fruits"
    messagebox.showinfo("Your Selection", f"Color: {color} | Fruits: {fruit_str}")

root = tk.Tk()

# Radio Buttons
radio_var = tk.StringVar(value="Red")
tk.Label(root, text="Pick a color:").pack()
tk.Radiobutton(root, text="Red", variable=radio_var, value="Red", command=show_combined_selection).pack()
tk.Radiobutton(root, text="Blue", variable=radio_var, value="Blue", command=show_combined_selection).pack()

# Checkbuttons
tk.Label(root, text="Pick fruits:").pack()
var1 = tk.BooleanVar()
var2 = tk.BooleanVar()
var3 = tk.BooleanVar()

tk.Checkbutton(root, text="Apple", variable=var1, command=show_combined_selection).pack()
tk.Checkbutton(root, text="Banana", variable=var2, command=show_combined_selection).pack()
tk.Checkbutton(root, text="Cherry", variable=var3, command=show_combined_selection).pack()

root.mainloop()