如何验证tkinter中的按钮,以便只调用一次该函数?

时间:2013-12-10 15:38:49

标签: python button user-interface tkinter

当我多次按下“Enter”按钮时,文本字段将继续显示但是我想要它,这样一旦我输入了我的名字并按下按钮,该按钮将停用。我该怎么做?

class Enter_Name_Window(tk.Toplevel):
    '''A simple instruction window'''
    def __init__(self, parent):
        tk.Toplevel.__init__(self, parent)
        self.text = tk.Text(self, width=40, height=2)
        self.text.pack(side="top", fill="both", expand=True)
        self.text.insert("end", "Please enter your name and class. ")

        enter_name = Entry(self)
        enter_name.pack()

        enter_name.focus_set()

    def callback():
        self.display_name = tk.Text(self, width=40, height=2)
        self.display_name.pack(side="top", fill="both", expand=True)
        self.display_name.insert("end", "Now please enter your tutor group.")
        tutor = Entry(self)
        tutor.pack()

        tutor.focus_set()

        Enter_0_2 = Button(self, text="Enter", width=10, command=callback2)
        Enter_0_2.pack()

    def callback2():
        self.display_name = tk.Text(self, width=40, height=2)
        self.display_name.pack(side="top", fill="both", expand=True)
        self.display_name.insert("end", "Let's begin! Exit back to main screen.")


    Enter_0 = Button(self, text="Enter", width=10, command=callback)
    Enter_0.pack()

1 个答案:

答案 0 :(得分:1)

在Button的state="disabled"方法中使用config()来禁用窗口小部件。您可以使用state="normal"以类似方式启用已禁用的窗口小部件。

基于示例代码的示例:

import Tkinter as tk


class Application(tk.Frame):

    def __init__(self, master):
        tk.Frame.__init__(self, master)
        self.text = tk.Text(self, width=40, height=2)
        self.text.pack(side="top", fill="both", expand=True)
        self.text.insert("end", "Please enter your name and class. ")

        enter_name = tk.Entry(self)
        enter_name.pack()
        self.enter_0 = tk.Button(self, text="Enter", width=10, command=self.callback)
        self.enter_0.pack()

        enter_name.focus_set()
        self.pack()

    def callback(self):
        self.display_name = tk.Text(self, width=40, height=2)
        self.display_name.pack(side="top", fill="both", expand=True)
        self.display_name.insert("end", "Now please enter your tutor group.")
        tutor = tk.Entry(self)
        tutor.pack()
        tutor.focus_set()
        self.enter_0.config(state="disabled")

        Enter_0_2 = tk.Button(self, text="Enter", width=10, command=self.callback2)
        Enter_0_2.pack()

    def callback2(self):
        self.display_name = tk.Text(self, width=40, height=2)
        self.display_name.pack(side="top", fill="both", expand=True)
        self.display_name.insert("end", "Let's begin! Exit back to main screen.")

root = tk.Tk()
root.geometry("600x400")
app = Application(root)
app.mainloop()