The ultimate choice of the GUI: Tkinter4: Entry input box assembly

The Entry ##
   the Entry : the Entry component is usually used to obtain user input text.
       (Input box is a way of dealing with the program, for example, the program asks you to enter the account number and password, then he needs to provide two input boxes to you, and to receive input box password must also use an asterisk * to the actual content hidden.
       learned in front of several components, the components can be found in many ways and options tkinter the (parameters) are common among them, that they are the same name, the content is similar, for example, in the input box, use the code add and delete content, that is, use the insert () and delete () method.)

from tkinter import *

root = Tk()

e = Entry(root)
e.pack(padx = 20,pady = 20)

mainloop()

Here Insert Picture Description
       (Analysis: Similarly, the first root to a top-level window, then instantiate Entry assembly, into the parameter indicates the root window, and then assigned to the variable e, then e.pack () bring it up, I do not want to enter the box and attached to the bezel together, so set about the padding
       and this input box you can enter Chinese letters, numbers, special characters can be, if the input box is large enough to accommodate these words, he will scroll automatically)

       ※ can use the delete (0 content, the END) to empty the input box, may be used insert (0, "...") methods to set the default text box content

from tkinter import *

root = Tk()

e = Entry(root)
e.pack(padx = 20,pady = 20)

e.delete(0,END)
e.insert(0,"默认文本...")

mainloop()

Here Insert Picture Description
       ※ You can use get Entry component () method to get the contents of the input box
       (you can also tkinter a variable (usually a string of variables: StringVar ()) linked to textvariable this option, then by the get method variables also can obtain) of the following through an example to demonstrate
       requirements : when the information acquisition button is pressed, will clear input box, and the information to print out the
Here Insert Picture Description
Here Insert Picture Description
       analysis : the first graph can be added in an analysis window works of two authors Label, two Entry and access to information, two button exit button
       first: generate Label show two works and authors
       of the second: use grid () to the grid layout
       (the usual practice, have learned will include two frame it up, and now with a new method, Tkinter provided a total of three ways to layout components, the first is the familiar pack (), then there is a kind (grid) grid (), is the form of a table to manage your components, there is a place behind the talk, this time to use grid layout components)

from tkinter import *

root = Tk()

Label(root,text="作品").grid(row=0,column=0)
Label(root,text="作者").grid(row=1,column=0)

e1 = Entry(root)
e2 = Entry(root)
e1.grid(row=0,column=1,padx=10,pady=5)
e2.grid(row=1,column=1,padx=10,pady=5)

def show():
    print("作品:《%s》" %e1.get())
    print("作者:%s" %e2.get())
    e1.delete(0, "end")
    e2.delete(0, "end")

Button(root,text = "获取信息",width = 10,command = show)\
                 .grid(row = 3,column = 0,sticky = W,padx =10,pady =5)
Button(root,text = "退出", width = 10,command = root.quit)\
                 .grid(row = 3,column = 1,sticky = E,padx =10,pady =5)

mainloop()

Here Insert Picture Description
       (Code analysis: The first is to first two Label label, are the work and the author, then just say this time using the (grid) grid () to layout components, grid if he is allowed to use in the form of a table to manage components position, he has the option to represent the row and column are the row and column position of this component is to work in line 0 0, in the author's position is line 0 0 distribution as shown above is
       followed by two input boxes , are on the root window, and then to use the grid layout, the two input frame assembly, the figure can be seen that they are position 0 is a row and a row 1, and then by padx disposed about pady padding, look good
       and then to add two buttons, the first is the first button is to obtain information, and then he set about to width, set in a command option, when the next point went to perform the show button method, then show input box object is to e1 and e2 obtained by the method to get the contents of the text box, and then output, the output after using the delete method of the input box, and then quit the command button is set root.quit on it That method calls the quit root method,
       followed by these two buttons placed well, that are 2 rows 0 and 2 rows 1, but requires a partial left button, a on the right, where you need to set a sticky of properties, Sticky is to control the position of the assembly in the space grid allocated, whose value and the previous anchor is very similar, using the same "n", "e", "s", "w" , and combinations thereof to position (ewsn on behalf of East and West, North-West and right left East) on, and then set about padx and pady he would not be the next corner)

       ※ after running a successful exit click is no response, and do not come back, because we are using IDLE tkinter also use to write out, they can conflict here, you double-click the file to open source to run a cmd window you can exit the system properly, if you want to exit the IDLE, you can use root.destroy
Here Insert Picture Description

   ※ then you can set an option to show the password input box design

from tkinter import *

root = Tk()

Label(root,text="账号:").grid(row=0,column=0)
Label(root,text="密码:").grid(row=1,column=0)

v1 = StringVar()
v2 = StringVar()

e1 = Entry(root,textvariable = v1)
e2 = Entry(root,textvariable = v2,show ="*")
e1.grid(row=0,column=1,padx=10,pady=5)
e2.grid(row=1,column=1,padx=10,pady=5)

def show():
    print("账号:%s" %e1.get())
    print("密码:%s" %e2.get())
    e1.delete(0, "end")

Button(root,text = "芝麻开门",width = 10,command = show)\
                 .grid(row = 3,column = 0,sticky = W,padx =10,pady =5)
Button(root,text = "退出", width = 10,command = root.destroy)\
                 .grid(row = 3,column = 1,sticky = E,padx =10,pady =5)

mainloop()

Here Insert Picture Description
       (解析:这里就是把上面一个例题的一些按钮改了,然后加了两个变量,因为这里需要两个变量存放账号和密码,输入框里边输入的是字符串,所以就是用Tkinter的StringVar来存放,然后Entry按钮里边就要设置textvarible属性,后边show方法要通过get方法获取输出,当然你不用加这两个变量也可以,加了就是使用前面提到的第二种获取文本框内容的方法,接着第二个输入框需要用*来显示,就直接用show ="*"就可以了,你想显示什么就传什么,也可以传show = “$”)

   ※接着来设计一个计算器
       (计算器不能够输入除了数字之外的任何字符,但是没关系,Entry 本身就自带了 验证功能,就是验证输入框里的内容的合法性比如要求输入数字,你输入了字母那就是非法。实现该功能,需要通过设置 validatevalidatecommandinvalidcommand 选项。)
        ※首先启用验证的“开关”是 validate 选项,该选项可以设置的值有:

含义
'focus' 当 Entry 组件获得或失去焦点的时候验证
'focusin' 当 Entry 组件获得焦点的时候验证
'focusout' 当 Entry 组件失去焦点的时候验证
'key' 当输入框被编辑的时候验证
'all' 当出现上边任何一种情况的时候验证
'none' 1. 关闭验证功能
2. 默认设置该选项(即不启用验证)
3. 注意,是字符串的 'none',而非 None

       (上面是他可以设置的值有哪些,表示在什么情况下去验证,去调用验证函数,而验证函数是在validatecommand里边指定的,跟button里边的command选项是一样的道理,validatecommand函数只能返回 True 或 False 表示验证的结果。一般情况下验证函数只需要知道输入框的内容即可,可以通过 Entry 组件的 get() 方法获得该字符串。)
        下边的例子中,在第一个输入框输入“老甲鱼”,并通过 Tab 键将焦点转移到第二个输入框的时候,验证功能被成功触发:

from tkinter import *

master = Tk()
 
def test():
    if e1.get() == "老甲鱼":
        print("正确!")
        return True
    else:
        print("错误!")
        e1.delete(0, "end")
        return False
 
 
v = StringVar()
 
e1 = Entry(master, textvariable=v, validate="focusout", validatecommand=test)
e2 = Entry(master)
e1.pack(padx=10, pady=10)
e2.pack(padx=10, pady=10)
 
master.mainloop()

Here Insert Picture Description
Here Insert Picture Description
        然后,invalidcommand 选项指定的函数只有在 validatecommand 的返回值为 False 的时候才被调用。

        下边的例子中,在第一个输入框输入“老甲鱼”,并通过 Tab 键将焦点转移到第二个输入框,validatecommand 指定的验证函数被触发并返回 False,接着 invalidcommand 被触发:

from tkinter import *

master = Tk()
 
def test():
    if e1.get() == "老甲鱼":
        print("正确!")
        return True
    else:
        print("错误!")
        e1.delete(0, "end")
        return False

def test2():
    print("我被调用了......")
    return True
 
v = StringVar()
 
e1 = Entry(master, textvariable=v, validate="focusout",\
           validatecommand=test, invalidcommand=test2)
e2 = Entry(master)
e1.pack(padx=10, pady=10)
e2.pack(padx=10, pady=10)
 
master.mainloop()


Here Insert Picture Description
Here Insert Picture Description
        最后,其实 Tkinter 还有隐藏技能,不过需要冷却才能触发,请听老甲鱼一一道来…

        Tkinter 为验证函数提供一些额外的选项:

额外选项 含义
'%d' 操作代码:0 表示删除操作;1 表示插入操作;2 表示获得、失去焦点或 textvariable 变量的值被修改
'%i' 1. 当用户尝试插入或删除操作的时候,该选线表示插入或删除的位置(索引号)
2. 如果是由于获得、失去焦点或 textvariable 变量的值被修改而调用验证函数,那么该值是 -1
'%P' 1. 当输入框的值允许改变的时候,该值有效
2. 该值为输入框的最新文本内容
'%s' 该值为调用验证函数前输入框的文本内容
'%S' 1. 当插入或删除操作触发验证函数的时候,该值有效
2. 该选项表示文本被插入和删除的内容
'%v' 该组件当前的 validate 选项的值
'%V' 1. 调用验证函数的原因
2. 该值是 'focusin','focusout','key' 或 'forced'(textvariable 选项指定的变量值被修改)中的一个
'%W' 该组件的名字,不过是 tk 变量在内部注册的名字,为一串数字。

        为了使用这些选项,你可以这样写:validatecommand=(f, s1, s2, …)

        其中,f 就是你“冷却后”的验证函数名,s1、s2、s3 这些就是上面表里额外的选项,这些选项会作为参数依次传给 f 函数。我们刚刚说了,使用隐藏技能前需要冷却,其实就是调用 register() 方法将验证函数包装起来:
       (这个f也就是刚刚的上个例子validatecommand=test方法,在这里直接套进去不行,因为这样子Tkinter他不认,认不了你,所以需要先调用register() 方法将验证函数先包装起来,包装成Tkinter能够认出来的东西)

from tkinter import *

master = Tk()
 
v = StringVar()
 
def test(content, reason, name):
    if content == "老甲鱼":
        print("正确!")
        print(content, reason, name)
        return True
    else:
        print("错误!")
        print(content, reason, name)
        return False
 
testCMD = master.register(test)
e1 = Entry(master, textvariable=v, validate="focusout", validatecommand=(testCMD, '%P', '%v', '%W'))
e2 = Entry(master)
e1.pack(padx=10, pady=10)
e2.pack(padx=10, pady=10)
 
master.mainloop()

Here Insert Picture Description

       (解析:对比上个例子可以发现,test方法不再是没有参数的方法了,他有三个参数,是在Entry组件的validatecommand选项中出现:validatecommand=(testCMD, ‘%P’, ‘%v’, ‘%W’),第一个%P查看上面的表可以知道是表示说他的值是输入框的最新文本内容,就是当输入框的值有改变的时候,%P就会有内容作为参数传到test方法的content参数,另外两个也是类似的道理,他们三个作为额外选项,作为参数传给test方法,然后%v就是表示该组件当前的 validate 选项的值,%W就是表示该组件的名字,在这里该组件就是e1,输出的就是e1在Tkinter里边注册的名字)

   ※下面可以开始来写计算器了
       (刚才的要求就是输入框不能存在数字以外的东西,有的小伙伴要获得文本框的内容,他可能会用e1.get来获取,然后设置validate = “key”,即表示当输入框有任何改变的时候就会触发调用验证的函数验证输入的内容正不正确,如果设置为key的话,就不能使用e1.get或者说一个textvariable的.get来获取内容了, 因为validate选项被指定为key的时候,有任何输入操作都会立刻被拦截,然后去调用验证函数,然后验证完之后,只有验证函数返回True,他才会将这个内容放到变量里边那个textvariable关联的变量里边,所以这里要用那个加强版的技能,就是上个例子的额外选项。%P来实现,%P就是来实现输入框发生任何改变就会获得输入框里边的内容,然后传递过去,)

from tkinter import *

master = Tk()

frame = Frame(master)
frame.pack(padx =10,pady=10)
 
v1 = StringVar()
v2 = StringVar()
v3 = StringVar()
 
def test(content):
        if content.isdigit() or content == "":
                return True
        else:
                return False
    
   
testCMD = master.register(test) #使用额外选项时需要先将测试函数包装
e1 = Entry(frame, width=10,textvariable=v1, validate="key",\
           validatecommand=(testCMD, '%P')).grid(row = 0,column=0)

Label(frame,text="+").grid(row = 0,column=1)


e2 = Entry(frame, width=10,textvariable=v2, validate="focusout",\
           validatecommand=(testCMD, '%P')).grid(row = 0,column=2)

Label(frame,text="=").grid(row = 0,column=3)

e3 = Entry(frame,width=10,textvariable=v3,state = "readonly").grid(row = 0,column=4)


def calc():
    result = int(v1.get())+int(v2.get())
    v3.set(str(result))


Button(frame,text = "计算结果",command =calc).grid(row = 1,column=2,pady=5)
 
master.mainloop()

Here Insert Picture Description
       (Analysis: First, the layout of this calculator is the first line of the three input box, and two Label components show the "+" and "=" sign in front of two input boxes need to verify the legitimacy of his input, only It is digital, and the third is to put the result of him not verify, but to set up a state property is readonly, that can only be read, not modified, and the difference is disable, readonly can also copy, and disable what is operation will be prohibited
       there is a caveat is if the value is the key, then validate, test function test returns True, then you enter the content will remain in the input box inside, very intelligent, if the return is False, he will automatically help you clear out, so it will return False when the input is not a number, it will not show up)

Published 247 original articles · won praise 116 · views 280 000 +

Guess you like

Origin blog.csdn.net/w15977858408/article/details/104154391