验证tkinter用户输入,状态检查

时间:2014-03-18 13:20:01

标签: python tkinter

我需要在tkinter GUI上验证用户输入。我需要进行状态检查,格式检查(日期),其中一个输入只能是3个选项之一,我不知道如何做。我查看了其他示例,但很难理解,因为我没有使用过类。有人知道怎么做吗?

以下是一些示例代码

Entry1= Entry(window, bg="Blue", fg="white",font="40")
Entry2= Entry(window, bg="Blue", fg="white",font="40")
Entry3= Entry(winodw, bg="Blue", fg="white",font="40")


#Assigning the input boxes to area on the screen
Entry1.grid(row=1, column=1)
Entry2.grid(row=2, column=1)
Entry3.grid(row=3, column=1)

forename=Entry1.get()
surname=Entry2.get()
dateofbirth=Entry3.get()

2 个答案:

答案 0 :(得分:0)

您需要一个验证function来检查三个Entry字段的字符串变量,即:

def validate():
    if forename == valid_forename:
        print 'Valid forename'
    else:
        print '%s is not a valid forename' % forename

你可以从Button

中调用它
vButton = Button(window, text='Validate', command=validate)
vButton.grid()

您的三种类型的检查'将进入validate()功能。您应该能够通过一些简单的价值检查来完成这些工作,但是如果您不能,那么您应该发布一个关于价值检查类型的具体问题,您可以开始工作以及您尝试做什么工作

答案 1 :(得分:-2)

创建GUI / Tkinter类并调用它与普通Python类略有不同,因此下面是一个带有输入框的示例。请注意,要打开GUI窗口,您必须调用root.mainloop()#run

from Tkinter import *

import Tkinter as tk


class Application(Frame):

    """ a GUI/tkinter class application"""
    def __init__(self, root):

        Frame.__init__(self)



        self.pack()

        self.create_widgets()

    def create_widgets(self):

        # Create a label

        self.label = Label(self, text= "Type text here!")
        self.label.pack( side='top', anchor='n', fill='x', expand=False,padx=1, pady=1 )

        # Create an Entry - box where the text is typed in.
        self.text_entry = Entry(self)
        self.text_entry.pack( side='top', anchor='n', fill='x', expand=True,padx=4, pady=4)





        # Create a textbox

        self.box_txt = tk.Text(self, width = 65, height = 25, wrap = WORD)
        self.box_txt.pack(side=BOTTOM)


         # Create a submit button
        self.button = Button(self, text = "Submit!", command = self.display_text_in_listbox)
        self.button.pack( side='right', anchor='w', fill='x', expand=False,padx=1, pady=1 )





  # Method for getting the text from the entry box and displaying it
  # in the listbox

    def display_text_in_listbox(self):
        msg = self.text_entry.get() # get text from entry

        self.box_txt.delete(0.0, END)  # Clear the listbox from current text

        self.box_txt.insert(0.0, msg) # Add text written into entry


root = tk.Tk() # Instantiate tk - inter class object
root.title("My TKinter application") # Text on top of the window

root.geometry("900x700")  # the size of the window, height * width

app = Application(root)  # Instantiate root in Application class
root.mainloop() # run