IP地址的Tkinter条目验证

时间:2019-08-14 09:45:47

标签: python python-3.x validation tkinter tkinter-entry

我正在使用Tkinter Entry从用户输入IPv4地址,并且我更喜欢使用小部件的validatecommand属性,该属性仅允许使用X位数格式为XXX.XXX.XXX.XXX的条目。 / p>

可以通过重新模块将条目与表达式^ \ d {1,3}。\ d {1,3}。\ d {1,3}。\ d {1,3} $匹配来解决问题但我想事先做。

我尝试如下使用ipaddress模块​​:

import tkinter as tk
import ipaddress as ip
import re

def validate(value):
    if ip.ip_address(value):
        return True
    return False

window = tk.Tk()

tk.Label(window, text = "IP", font = 'Arial 10 bold').grid(row = 0, column = 0, padx = 5, pady = 5, sticky = 'ew')
varip = tk.StringVar()
vcmd = window.register(validate)
ipadd = tk.Entry(window, textvariable = varip, width = 23, validate = 'key', validatecommand = (vcmd, '%P'))
ipadd.grid(row = 0, column = 1, padx = 5, pady = 5)
window.mainloop()

问题在于,只有引入的第一个字符被检查为IPv4地址,并且所有字符都被允许,不仅是数字和点。

怎么办?

3 个答案:

答案 0 :(得分:1)

如果您在验证Ipv4时遇到问题,可以在代码中添加以下逻辑。我有一个类似的tkinter程序,需要 Ipv4验证。这对我有用。

import re 

# Make a regular expression 
# for validating an Ip-address 
regex = '''^(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.( 
            25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.( 
            25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.( 
            25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)'''

# Define a function for 
# validate an Ip addess 
def check(Ip):  

    # pass the regular expression 
    # and the string in search() method 
    if(re.search(regex, Ip)):  
        print("Valid Ip address")  

    else:  
        print("Invalid Ip address")  


# Driver Code  
if __name__ == '__main__' :  

    # Enter the Ip address 
    Ip = "192.168.0.1"

    # calling run function  
    check(Ip) 

    Ip = "110.234.52.124"
    check(Ip) 

    Ip = "366.1.2.2"
    check(Ip) 

答案 1 :(得分:1)

如果您不希望它接受诸如999.999.999.999之类的地址,则必须对其进行更改,但是下面在类似应用程序中对我有用的正则表达式如下。我写它来验证八位字节。我对此还很陌生,所以您必须原谅PEP8格式问题。

import tkinter as tk
import re


def validate(P):
    test = re.compile('(^\d{0,3}$|^\d{1,3}\.\d{0,3}$|^\d{1,3}\.\d{1,3}\.\d{0,3}$|^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{0,3}$)')
    if test.match(P):
        return True
    else:
        return False

window = tk.Tk()

tk.Label(window, text = "IP", font = 'Arial 10 bold').grid(row = 0, column = 0, padx = 5, pady = 5, sticky = 'ew')
varip = tk.StringVar()
vcmd = window.register(validate)
ipadd = tk.Entry(window, textvariable = varip, width = 23, validate = 'key', validatecommand = (vcmd, '%P'))
ipadd.grid(row = 0, column = 1, padx = 5, pady = 5)
window.mainloop()

答案 2 :(得分:0)

我设法解决了以下问题:

import tkinter as tk

def validate(P, S):
    if S.isdigit():
        if 0 <= len(str(P)) <= 3:
            return True
    return False

window = tk.Tk()

tk.Label(window, text = "IP", font = 'Arial 10 bold').grid(row = 0, column = 0, padx = 5, pady = 5, sticky = 'ew')
varip = tk.StringVar()
vcmd = window.register(validate)
ipadd = tk.Entry(window, textvariable = varip, width = 23, validate = 'key', validatecommand = (vcmd, '%P', '%S'))
ipadd.grid(row = 0, column = 1, padx = 5, pady = 5)
window.mainloop()