如何使用 tkInter 显示询问用户多项选择问题的对话框? [英] How do I display a dialog that asks the user multi-choice question using tkInter?

查看:34
本文介绍了如何使用 tkInter 显示询问用户多项选择问题的对话框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无论如何,我一直在寻找一个 tkinter 函数,它会向用户询问一个多选问题,我找到的最接近的是 messagebox.asknoyes,但它只提供 2 个选择,而且我无法编辑选择是固定的(是或否),是否有一个 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?

注意:这不是 在 Tkinter 中从用户那里获取输入 的可能重复,因为该问题询问如何从用户,所以用户可以提交他们想要的任何输入,而我想给用户一些预定义的选择

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

推荐答案

我认为没有内置函数可以解决这个问题.我认为您将不得不手动创建一个窗口,手动为其添加单选按钮和标签,等待用户响应,然后手动检查选择了哪个单选按钮.

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)))

这篇关于如何使用 tkInter 显示询问用户多项选择问题的对话框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆