python-3.x - 如何从对话框返回结果?

标签 python-3.x tkinter call tk-toolkit

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

我试图看看标准对话框是如何实现的,以便做类似的事情。我注意到所有打开对话框的函数,如 askdirectoryaskopenfile 调用 Dialog 的方法 show。所以我决定看看这个方法,但我并没有完全看到这个方法与能够等待用户的回答/ Action 返回一些值的事实之间的关系。

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

最佳答案

基 native 制是有一个函数来创建窗口(或使其可见),等待它被销毁(使用 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!

关于python-3.x - 如何从对话框返回结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28443749/

相关文章:

python - 在 Windows 10 上安装 Kivy 时出现问题

python - 使用 for 循环在列表中查找用户定义的项目

Python Tkinter 子窗口问题

python - 如何绘制具有可缩放半径的圆?

python - 如何获取特定时区的当前时间?

python - 如何在 python 3 中使用 cookie?

python - 如何使用 Tkinter 中的类创建新页面?

android - TabChange 上的调用方法

java - 如何在 Java 中的另一个类中使用一个类的变量?

blackberry - 黑莓手机如何录音?