我想显示一个弹出消息框的方式,但不显示两个选项(是,否),我想个性化两个以上的选项,例如,我想问问他最好的颜色(蓝色,红色) ,绿色):
import tkinter.messagebox
from tkinter import Button, Tk
def ask_multiple_choice_question():
answer = tkinter.messagebox.askquestion(
"colors", "whats your favorite color"
) # red, blue, green
print(answer) # print the color chosen
window = Tk()
Button(text="Submit", command=ask_multiple_choice_question).pack()
window.mainloop()
答案 0 :(得分:1)
没有内置选项,但可以构造一个。
from tkinter import *
from tkinter import messagebox
class OptionDialog(Toplevel):
"""
This dialog accepts a list of options.
If an option is selected, the results property is to that option value
If the box is closed, the results property is set to zero
"""
def __init__(self,parent,title,question,options):
Toplevel.__init__(self,parent)
self.title(title)
self.question = question
self.transient(parent)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.options = options
self.result = '_'
self.createWidgets()
self.grab_set()
## wait.window ensures that calling function waits for the window to
## close before the result is returned.
self.wait_window()
def createWidgets(self):
frmQuestion = Frame(self)
Label(frmQuestion,text=self.question).grid()
frmQuestion.grid(row=1)
frmButtons = Frame(self)
frmButtons.grid(row=2)
column = 0
for option in self.options:
btn = Button(frmButtons,text=option,command=lambda x=option:self.setOption(x))
btn.grid(column=column,row=0)
column += 1
def setOption(self,optionSelected):
self.result = optionSelected
self.destroy()
def cancel(self):
self.result = None
self.destroy()
if __name__ == '__main__':
#test the dialog
root=Tk()
def run():
values = ['Red','Green','Blue','Yellow']
dlg = OptionDialog(root,'TestDialog',"Select a color",values)
print(dlg.result)
Button(root,text='Dialog',command=run).pack()
root.mainloop()
答案 1 :(得分:0)
评论:我需要更优雅的方式
您正在寻找这样的东西:
class App(Application):
def __init__(self):
super().__init__()
for question in questions:
question.choice = Dialog.ask_multiple_choice(self, question)
if __name__ == "__main__":
App().mainloop()