ArandomUserNameEG
ArandomUserNameEG

Reputation: 108

How do I display a dialog that asks the user multi-choice question using tkInter?

Anyway, I've been searching around for a tkinter function that asks the user a multi-choice question, the closest thing I've found is messagebox.asknoyes, but it only offers 2 choice, furthermore I can't edit the choices as they are fixed (Yes or No), is there's a tkinter function that does what i'm looking for?

Note: this is not a possible duplicate of Taking input from the user in Tkinter as that question asks how to take input from the user, so the user can submit any input they want, while I want to give the user some predefined choice to choose one

Upvotes: 5

Views: 6008

Answers (1)

Kevin
Kevin

Reputation: 76194

I don't think there's a built-in function for that. I think you're going to have to manually create a window, manually add radio buttons and labels to it, wait for the user to respond, and then manually check which radio button was selected.

Fortunately this is pretty straightforward, so I made a quick implementation for you.

from tkinter import Tk, Label, Button, Radiobutton, IntVar
#    ^ Use capital T here if using Python 2.7

def ask_multiple_choice_question(prompt, options):
    root = Tk()
    if prompt:
        Label(root, text=prompt).pack()
    v = IntVar()
    for i, option in enumerate(options):
        Radiobutton(root, text=option, variable=v, value=i).pack(anchor="w")
    Button(text="Submit", command=root.destroy).pack()
    root.mainloop()
    if v.get() == 0: return None
    return options[v.get()]

result = ask_multiple_choice_question(
    "What is your favorite color?",
    [
        "Blue!",
        "No -- Yellow!",
        "Aaaaargh!"
    ]
)

print("User's response was: {}".format(repr(result)))

Upvotes: 12

Related Questions