如何从对话框返回结果?

时间:2015-02-10 23:17:37

标签: python-3.x tkinter call tk

我创建了一个对话框,一切都很好,除非我以某种方式返回结果。从对话框中获取用户选择的问题是,我们不知道他/她何时会点击okcancel

我试图了解如何实现标准对话框,以便做类似的事情。我注意到所有打开对话框的功能,例如askdirectoryaskopenfile都会调用Dialog的方法show。所以我决定看看这个方法,但我并没有看到这个方法与能够等待用户的回答/动作返回某些值的事实之间的关系。

我们究竟如何从对话框中返回一些值?

1 个答案:

答案 0 :(得分:5)

基本机制是创建一个创建窗口的函数(或使其可见),等待它被销毁(使用wait_window),从窗口中获取值,然后返回值。您将要使用StringVar或与窗口一起销毁的类似内容。

这是一个要求您键入字符串的对话框示例。您可以通过按返回键,单击"确定"来关闭对话框。按钮,或使用窗口管理器按钮杀死窗口。当您关闭对话框时,该字符串将显示在主窗口中。

import Tkinter as tk

class CustomDialog(tk.Toplevel):
    def __init__(self, parent, prompt):
        tk.Toplevel.__init__(self, parent)

        self.var = tk.StringVar()

        self.label = tk.Label(self, text=prompt)
        self.entry = tk.Entry(self, textvariable=self.var)
        self.ok_button = tk.Button(self, text="OK", command=self.on_ok)

        self.label.pack(side="top", fill="x")
        self.entry.pack(side="top", fill="x")
        self.ok_button.pack(side="right")

        self.entry.bind("<Return>", self.on_ok)

    def on_ok(self, event=None):
        self.destroy()

    def show(self):
        self.wm_deiconify()
        self.entry.focus_force()
        self.wait_window()
        return self.var.get()

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.button = tk.Button(self, text="Get Input", command=self.on_button)
        self.label = tk.Label(self, text="", width=20)
        self.button.pack(padx=8, pady=8)
        self.label.pack(side="bottom", fill="both", expand=True)

    def on_button(self):
        string = CustomDialog(self, "Enter something:").show()
        self.label.configure(text="You entered:\n" + string)


if __name__ == "__main__":
    root = tk.Tk()
    root.wm_geometry("400x200")
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

截图:

Entering input

You entered: Hello, world!

相关问题