如何验证Tkinter中的窗口?

时间:2013-12-05 15:08:43

标签: python user-interface tkinter

def createWidgets(self):
        self.INSTRUCTIONS = Button(self) #creating button linked to instructions_window
        self.INSTRUCTIONS["text"] = "Instructions"
        self.INSTRUCTIONS["fg"]   = "green"
        self.INSTRUCTIONS["command"] =  self.instruction_window #command which opens instructions_window

        self.INSTRUCTIONS.pack({"side": "left"})

目前,如果我多次按下按钮,则说明窗口将多次打开。如何确保按下按钮时,如果窗口已打开,则它将闪烁以显示无法打开同一窗口。有命令吗?或者我是否需要使用某种验证?

2 个答案:

答案 0 :(得分:0)

Here's a great article dealing with more complicated examples of dialog boxes.

基本上你正在寻找的东西几乎就像一个modal dialog window,除了它似乎还能够在一定程度上与父窗口进行交互。在这一点上,它可能值得考虑使它完全模态,但我不知道你的用例。如果没有,您绝对可以调整教程网站上提供的脚本以满足您的需求。

答案 1 :(得分:0)

我这样做的方法是创建一个如果窗口不存在就会创建窗口的函数,然后显示窗口。我个人认为不需要闪存窗口,但如果你愿意,你可以这样做。 Tkinter不知道如何刷一个窗口,但你可以做一些简单的事情,比如简单地改变颜色。

以下是一个例子:

import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        self.instruction_window = None
        self.instructions = tk.Button(self, text="Instructions", foreground="green",
                                      command=self.show_instructions)
        self.instructions.pack(side="left")

    def show_instructions(self):
        '''show the instruction window; create it if it doesn't exist'''
        if self.instruction_window is None or not self.instruction_window.winfo_exists():
            self.instruction_window = InstructionWindow(self)
        else:
            self.instruction_window.flash()

class InstructionWindow(tk.Toplevel):
    '''A simple instruction window'''
    def __init__(self, parent):
        tk.Toplevel.__init__(self, parent)
        self.text = tk.Text(self, width=40, height=8)
        self.text.pack(side="top", fill="both", expand=True)
        self.text.insert("end", "these are the instructions")

    def flash(self):
        '''make the window visible, and make it flash temporarily'''

        # make sure the window is visible, in case it got hidden
        self.lift()
        self.deiconify()

        # blink the colors
        self.after(100, lambda: self.text.configure(bg="black", fg="white"))
        self.after(500, lambda: self.text.configure(bg="white", fg="black"))

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