【问题标题】:How do I display a dialog that asks the user multi-choice question using tkInter?如何使用 tkInter 显示一个询问用户多项选择问题的对话框?
【发布时间】:2017-03-03 14:07:40
【问题描述】:

无论如何,我一直在寻找一个 tkinter 函数,它询问用户一个多项选择问题,我发现最接近的是 messagebox.asknoyes,但它只提供 2 个选择,而且我无法编辑选择是固定的(是或否),是否有一个 tkinter 函数可以满足我的要求?

注意:这不可能与Taking input from the user in Tkinter 重复,因为该问题询问如何从用户那里获取输入,因此用户可以提交他们想要的任何输入,而我想给用户一些预定义的选择来选择一个

【问题讨论】:

  • 我认为没有内置功能。我认为您将不得不手动创建一个窗口,手动为其添加单选按钮和标签,等待用户响应,然后手动检查选择了哪个单选按钮。
  • @Kevin,谢谢,请将此作为答案,以便我接受
  • @Anil_M 不,不是。

标签: python python-3.x user-interface tkinter


【解决方案1】:

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

幸运的是,这很简单,所以我为你做了一个快速的实现。

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

【讨论】:

    猜你喜欢
    • 2011-04-20
    • 2014-07-25
    • 2015-04-09
    • 2020-03-20
    • 1970-01-01
    • 2018-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多