验证tkinter用户输入,检查存在性

0 投票
2 回答
1623 浏览
提问于 2025-04-17 22:48

我需要在一个tkinter图形界面上验证用户输入。我需要检查输入是否存在、格式是否正确(比如日期),还有一个输入只能是三个选项中的一个,但我不知道该怎么做。我看过其他的例子,但因为我还没有使用类,所以那些例子对我来说很难理解。有没有人知道该怎么做?

下面是一些示例代码

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 个回答

-2

创建一个图形用户界面(GUI)/Tkinter类并调用它,跟普通的Python类有点不同。下面是一个包含输入框的例子。请注意,要打开这个GUI窗口,你需要调用 root.mainloop() # 运行

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 
0

你需要一个验证的 function,这个函数要检查三个 Entry 输入框里的字符串变量,也就是说:

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

你可以通过一个 按钮来调用这个函数:

vButton = Button(window, text='Validate', command=validate)
vButton.grid()

你要进行的三种“检查”会放在 validate() 函数里。你应该能通过一些简单的值检查来完成这些工作。如果你遇到困难,不能搞定某种值检查,那就请你具体描述一下你遇到的问题,以及你尝试过的解决方法。

撰写回答