我有一个带tkinter的Python3程序,在代码的某些部分中,我想从选项列表中“询问”。我看到simplebox或messagebox都没有此选项,仅适用于文本。我该如何像result = simplechoicebox("title","Text",["Choices"],parent)
那样调用并返回结果?
我试图通过tkinter的功能来做到这一点,但是我没有找到。.
from tkinter import *
from tkinter import Menu, messagebox,simpledialog,ttk
def c_funcbutton():
res = simpledialog.askstring('Ask','Title',parent=main_window)
return res #Or do anything..
main_window = Tk()
main_window.title("My Window")
menu = Menu(main_window)
menu_com = Menu(menu)
menu_com = Menu(menu, tearoff=0)
menu_com.add_command(label='Here',command=c_funcbutton)
menu_com.add_command(label='Another')
menu.add_cascade(label='Equipos', menu=menu_com)
main_window.config(menu=menu)
main_window.mainloop()
我希望能够在c_funcbutton()
中询问Choicebox / Combobox并将其退回
答案 0 :(得分:0)
如果您想使用类似result = simplechoicebox("title","Text",["Choices"],parent)
的名称,则可以为其创建自己的类。
class SimpleChoiceBox:
def __init__(self,title,text,choices):
self.t = Toplevel()
self.t.title(title if title else "")
self.selection = None
Label(self.t, text=text if text else "").grid(row=0, column=0)
self.c = ttk.Combobox(self.t, value=choices if choices else [], state="readonly")
self.c.grid(row=0, column=1)
self.c.bind("<<ComboboxSelected>>", self.combobox_select)
def combobox_select(self,event):
self.selection = self.c.get()
self.t.destroy()
现在,您可以如下定义c_funcbutton
:
def c_funcbutton():
global res
res = SimpleChoiceBox("Ask","What is your favourite fruit?",["Apple","Orange","Watermelon"])
但是,它不会返回值-普通类的工作方式不同于simpledialog
。但是您可以通过res.selection
直接访问选择,如下所示:
menu_com.add_command(label='Another',command=lambda: print (res.selection))