繁体   English   中英

在tkinter中为组合框对话框创建一个简单的函数

[英]Create a simple function for combobox dialog in tkinter

我有一个带有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并返回它

如果你想使用像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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM