程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python Tkinter - Chapter 6 entry & Properties

編輯:Python

The first 6 Chapter input control (Entry)
Input control (Entry. Is a control used to input or display a single line string . This control allows the user to enter or display a line of text . If the length of the text entered by the user is greater than Entry Control , The text scrolls backwards . In this case, all the input strings cannot be displayed . You can move the cursor , Move the invisible text part into the visible area . If you want to enter multiple lines of text , You need to use Text Control .
6.1 attribute
6.1.1 Property list

Property parameters describe background
bg Set the background color , Such as bg=‘red’borderwidth
bd Enter the border width of the control . The default is 1-2 Pixel .cursor Enter the cursor of the control . The default is character insertion cursor ( It's usually a “I-beam” Cursor of type )disabledbackground Defines the background color when the input control is disabled .disabledforeground Defines the foreground when the input control is disabled ( Text ) Color .exportselection Defines whether to put the selected text , Automatically copy to clipboard . This parameter has no effect on the input control fg
foreground Set foreground ( Text ) Color font Set font type and size highlightbackground Define the highlighted background color when the input control does not get input focus . Is the bright edge of the input box .highlightcolor And highlightbackground Properties are similar to . It's just the border color when the input control gets input focus .highlightthickness The width of the border when the input control gains or loses input focus . commonly 1-2 Pixel .insertbackground Input control , Insert the color of the cursor insertborderwidth Insert the border display width of the cursor . If it is a non 0 The numerical , The cursor will use RAISED The border of the effect .insertofftime
insertontime These two properties control the blinking effect of the insertion cursor . Is the time when the insertion cursor appears and disappears . In milliseconds .insertwidth The width of the insertion cursor .invalidcommand
invcmd Callback function to verify the validity of input , But it can't be used alone . Only set validatecommand Callback function and the function returns False Under the circumstances , Will activate invalidcommand Defined callback function .justify Define the alignment of text in the input control . The value that can be set is :LEFT, CENTER, RIGHT. The default value is LEFT.readonlybackground Set the input control to “ read-only ” The background color of the pattern relief Set the... Of the input control 3D effect , The default is flat, Parameters that can be set ;flat、groove、raised、ridge、solid、sunken, Such as relief=‘groove’selectbackground Set the background color of the selected area selectborderwidth Set the border width of the selected area .selectforeground Set the foreground of the selected area ( Text ) Color show Defines how to display the contents of the input control . If it is not empty , Control replaces the actual content with the defined characters . For example, when entering a password , In general use ”*” Replace the actual input .state Define the state of the input control . There are three states :NORMAL, DISABLED, READONLY.(READONLY And DISABLED similar , Only the displayed content can be selected and copied .takefocus Define whether you can use Tab Key to move the input focus to the input control .textvariable The associated tkinter Variable , It's usually StringVar type . If the variable changes , The content in the input control will also be updated .validate Define the conditions under which validation of input content is triggered :
focus: When you gain or lose input focus
focuin: Only when you get input focus
focusout: When you lose input focus
key: When changing the content
ALL: All of the above
This attribute defines when to start input validation , The callback function that verifies the input content is composed of validatecommand perhaps invalidcommand Definition validatecommand
vcmd Define a function to verify and check the input content . If the input content meets the requirements , This function returns True, Otherwise return to False. This attribute is in validate Valid when not empty .width Define the width of the input control , The unit is the character .xscrollcommand Associate a scroll bar with an input control , Handle scroll bar actions . The scroll bar can only be horizontal .6.1.2 background(bg) Set the background color of the input control .bg It's an abbreviation , And background It's the same .
import tkinter as tk
root=tk.Tk()
root.geometry('300x240')
b1=tk.Entry(root,bg='yellow',width=20)
b1.pack()
root.mainloop()

result :

6.1.3 borderwidth(bd)
Set the border width of the input control .bd and borderwidth It does the same thing , It's just an abbreviation .

import tkinter as tk
root=tk.Tk()
root.geometry('300x240')
b1=tk.Entry(root,bg='yellow',width=20,bd=10)
b1.pack()
root.mainloop()

result :

This figure is consistent with 6.1.2 Compare the figures in , You can find , An obvious border appears around the input area . This is the effect of the border .

6.1.4 cursor
When the mouse is in the input control area , The shape of the cursor . It's usually ”I-Beam”. You can also choose other shapes . stay 3.3.6 in , There are detailed names of built-in mouse shapes .

import tkinter as tk
root=tk.Tk()
root.geometry('300x240')
b1=tk.Entry(root,bg='blue',width=20,cursor='mouse')
b1.pack()
root.mainloop()

result :

This code is to change the shape of the cursor into a mouse (mouse) shape , Of course, only when the cursor passes through the input control area will it change .

6.1.5 disabledbackground
Input the background color when the control is disabled .

import tkinter as tk
root=tk.Tk()
root.geometry('300x240')
b1=tk.Entry(root,bg='yellow',width=20,
state=tk.DISABLED,disabledbackground='blue')
b1.pack()
root.mainloop()

result :


Although the background color set in the code is yellow , But because the state of the input control is DISABLED, Then the effective background color is the blue color we specified . If you do not specify the background color when the input control fails , What's going to happen ? The default background color at the time of failure will be used , It's gray .

6.1.6 disabledforeground
Set when the input control fails , The foreground in the input box ( written words ) Color .

import tkinter as tk
root=tk.Tk()
root.geometry('300x240')
txt = tk.StringVar()
b1=tk.Entry(root,textvariable=txt,width=20,
state=tk.DISABLED,disabledforeground='red')
txt.set(' Unable to input ')
b1.pack()
root.mainloop()

result :

6.1.7 exportselection
Is a Boolean value , But it has no effect on the input control .

6.1.8 foreground(fg)
Set the text color of the input control . The default is black .fg and foreground It means the same , It's an abbreviation .

import tkinter as tk
root=tk.Tk()
root.geometry('300x240')
b1=tk.Entry(root,width=20,fg='red')
b1.pack()
root.mainloop()

result :

6.1.9 font
Set the font of the input text . Specific font setting methods , Please see the 3.3.3 Relevant instructions in , No more details here .
6.1.10 highlightbackground,highlightcolor and highlightthickness
These three parameters are used to set the outer border of the input control .highlightbackground Is the background color of the border when the input control does not get input focus .highlightcolor Is the background color of the border when the input control gets input focus .highlightthickness Defines the width of the border .

import tkinter as tk
root=tk.Tk()
root.geometry('300x240')
b1=tk.Entry(root,width=20,highlightbackground='red',
highlightcolor='yellow',highlightthickness=20)
b1.pack()
b2=tk.Button(root,text='Quit')
b2.pack()
root.mainloop()

result :


Be careful : The color change of the border is determined by whether the input control has input focus . If the input focus is still in the input box , The color of the border is still highlighted . such as , In the example above , Simply clicking the button will not make the input box lose the input focus , The color of the border will not change . If you use Tab key , Let input focus to button , At this time, the border of the input control will be set highlightbackground value .
6.1.11 insertbackground
Set the color of the cursor in the input box .

import tkinter as tk
root=tk.Tk()
root.geometry('300x240')
b1=tk.Entry(root,width=20,insertbackground='red')
b1.pack()
root.mainloop()

result :

6.1.12 insertborderwidth
Set the border width of the cursor in the input box .0 There is no border ,1 To other positive integers is a border with only one pixel , Negative numbers will follow the set value , Display the border of the cursor correctly .

import tkinter as tk
root=tk.Tk()
root.geometry('300x240')
b1=tk.Entry(root,width=20,
insertbackground='red',
insertborderwidth=-50)
b1.pack()
root.mainloop()

result :

6.1.13 insertofftime and insertontime
These two parameters set the time when the cursor flashes .insertofftime Is the time when the cursor is not displayed ,insertontime Is the time displayed by the cursor . In this way, the cursor flickering effect can be realized .

import tkinter as tk
root=tk.Tk()
root.geometry('300x240')
b1=tk.Entry(root,width=20,insertofftime=2000,insertontime=5000,
insertbackground='red',insertborderwidth=-50)
b1.pack()
root.mainloop()

6.1.14 insertwidth
Set the width of the insertion cursor .

import tkinter as tk
root=tk.Tk()
root.geometry('300x240')
b1=tk.Entry(root,width=20,insertwidth=50)
b1.pack()
root.mainloop()

result :

6.1.15 invalidcommand(invcmd)
see 6.1.26 Explanation
6.1.16 justify
Set the alignment of the text in the input box . Values are LEFT, CENTER, RIGHT Three .

import tkinter as tk
root=tk.Tk()
root.geometry('300x240')
b1=tk.Entry(root,width=20,justify=tk.CENTER)
b1.pack()
root.mainloop()

result :

This is an example of a centered display . Other LEFT and RIGHT, You can modify the code to run verification by yourself .
6.1.17 readonlybackground
When the input control is in read-only mode , Can pass readonlybackground Set the background value .

import tkinter as tk
root=tk.Tk()
root.geometry('300x240')
txt = tk.StringVar()
b1=tk.Entry(root,width=20,textvariable=txt,
readonlybackground='yellow',state="readonly")
txt.set(' read only mode ')
b1.pack()
root.mainloop()

result :

6.1.18 relief
Set the border of the input control 3D effect , The value range is :flat、groove、raised、ridge、solid and sunken. See for a detailed description 3.3.5 section .
6.1.19 selectbackground
The background color after the selected text . The default is black .

import tkinter as tk
root=tk.Tk()
root.geometry('300x240')
b1=tk.Entry(root,width=20,selectbackground='red')
b1.pack()
root.mainloop()

result :

6.1.20 selectborderwidth
The border width of the selected area .

import tkinter as tk
root=tk.Tk()
root.geometry('300x240')
b1=tk.Entry(root,width=30,selectborderwidth=10)
b1.pack()
root.mainloop()

result :

6.1.21 selectforeground
The foreground of the selected area ( Text ) The color of the . Generally, the default value is used , You can also specify . Best and selectbackground It's the opposite color . It is better to modify both parameters at the same time .

import tkinter as tk
root=tk.Tk()
root.geometry('300x240')
b1=tk.Entry(root,width=30,selectforeground='red')
b1.pack()
root.mainloop()

result :

6.1.22 show
Set the alternative value of the input . The most typical use is when entering a password , use ’*’ To replace the actual input characters so as to achieve the effect of confidentiality . Actually , You can also set other characters , such as ’x’ To replace the input characters .

import tkinter as tk
root=tk.Tk()
root.geometry('300x240')
b1=tk.Entry(root,width=30,show='x')
b1.pack()
root.mainloop()

result :

6.1.23 state
There are three states of input control :normal,disabled and readonly.normal State, , All functions of the input control can be used normally . stay disabled State, , Only realistic text , Other functions cannot be used . And in the readonly Under the state of , You just can't input or modify the contents of the input control , But you can use the selection function .
But if you set textvariable attribute , In any state , Can be changed textvariable Corresponding variable , To modify the contents of the input control .

import tkinter as tk
root=tk.Tk()
root.geometry('300x240')
txt=tk.StringVar()
b1=tk.Entry(root,textvariable=txt,width=30,state='disabled')
b1.pack()
def set_entry():
txt.set('change')
b2=tk.Button(root,text='Entry',command=set_entry)
b2.pack()
root.mainloop()

result :


Set up state=’readonly’ You can select the contents in the input box . however disabled State, , You can't do that. . This is a readonly And disabled The difference between .

6.1.24 takefocus
Set whether the input control can pass through Tab Get input focus . Is a Boolean property . For more information, see the previous section .
6.1.25 textvariable
Set correlation tkinter The variable of , Used to modify or obtain the data of the input control . In general use StringVar(). You can also use IntVar, DoubleVar, BooleanVar etc. . The previous introduction is to use set() To set the value of the associated variable , This example uses get() To get the value of the associated variable .

import tkinter as tk
root=tk.Tk()
root.geometry('300x240')
txt=tk.StringVar()
txt2=tk.StringVar()
b1=tk.Entry(root,textvariable=txt,width=20)
b1.pack()
b2=tk.Entry(root,textvariable=txt2,width=20)
b2.pack()
def set_entry():
txt2.set(txt.get())
b3=tk.Button(root,text='Entry',command=set_entry)
b3.pack()
root.mainloop()

result :


6.1.26 validate,invalidcommand and validatecommand
vaidate Defines the conditions under which input validation is triggered :
focus: When you gain or lose input focus
focuin: Only when you get input focus
focusout: When you lose input focus
key: When the contents of the input box change
ALL: All of the above

validatecommand Is the input validation function . When the input content meets the conditions , For example, all the required inputs are 0-9 The number of , It will return True, Otherwise return to False. and invalidatecommand Coincide with validatecommand contrary , Return if the requirements are not met False, Meet the requirements and return to True.

validatecommand and invalidatecommand Can define the callback function . This callback function can pass in parameters . In the setting validatecommand and invalidatecommand The explicit description of . The specific parameter transfer meanings are as follows :

Parameters meaning ‘%d’ Insert or delete characters .
1: Insert characters
0: Delete character ‘%i’ Position of operation character ,0 Represents the first ‘%P’ Text in current input box ‘%s’ Modify the contents of the previous input box ‘%S’ Inserted or deleted characters ‘%v’validate Parameters set in ‘%V’ Specific conditions for triggering verification . such as focusout etc. .‘%W’ Enter the control id

If... Is set at the same time validatecommand and invalidatecommand, Execute that option first ? The first thing to execute is validatecommand. If the return value is True, Not execute invalidatecommand Defined callback function . If it is False, Would call invalidatecommand Defined callback function . But here's the thing , If the verification trigger condition is key perhaps all, Can't be used at the same time validatecommand and invalidatecommand, Otherwise, you will not be able to enter anything .

invalidatecommand Can't be used alone . There has to be validatecommand,invalidatecommand It works . Only invalidatecommand Input validation cannot be completed , Because there is no trigger at all .

The following example is to check whether the input is numeric , Otherwise, it is not allowed to enter .

import tkinter as tk
root=tk.Tk()
root.geometry('300x240')
def check_digit(content):
if content.isdigit() or content == "":
return True
else:
return False
entry_validate=root.register(check_digit)
b1 = tk.Entry(root,width=20,validate='key',vcmd=(entry_validate,'%P'))
b1.pack()
root.mainloop()

In fact, the above example requires that the input must be an integer , What if you want to enter a floating point number ? Replace isdigit() function , Use the custom check function . such as :

def int_float(value):
try:
x=int(value)
except ValueError:
try:
y = float(value)
except ValueError:
return False
else:
return True
else:
return True

This function can detect whether the input string is an integer or a floating-point number . But only positive numbers can be detected , Negative numbers cannot be detected . We can also modify and improve it , Is to first judge whether the first character input is “-”, If it is , Just use the characters after the copy to detect . Just in int_float At the beginning of the function, add the function to check whether the input string is equal to ’-’ that will do :

 if value=='-':
return True

Another possible problem is that the input field cannot be cleared , At least one number must be retained . This is because the callback function does not handle the case that the content of the input field is empty . If you delete all the characters , The value passed into the callback function is ’’, In this case, the judgment function returns False, Because none of the conditions are met . Therefore, it is necessary to add the case that the input box is empty :

if value=='':
return True

As for more complex tests , You need to write the corresponding detection function .
6.1.27 width
This property sets the width of the input control . The unit is the character . The previous example already uses this property , No more details here .

6.1.28 xscrollcommand
If you enter a lot of long characters , It exceeds the width defined by the input control , In addition to using arrows to move the cursor to browse , You can also use the scroll bar to scroll through the contents of the input box . Scroll bars will be introduced later , I won't introduce it in detail here .

import tkinter as tk
root=tk.Tk()
root.geometry('300x240')
f=tk.Frame(root)
s1 = tk.Scrollbar(f,orient=tk.HORIZONTAL)
b1 = tk.Entry(f,width=20,xscrollcommand=s1.set)
b1.pack()
s1.pack(side=tk.BOTTOM,fill=tk.X)
s1.config(command=b1.xview)
f.pack()
root.mainloop()

result :

explain :
Use Frame As a container , Put the input control and scroll bar in it , In this way, the scroll bar can be set in Frame The bottom of , Just below the input control . Pay attention to use fill=tk.X, It means that X In the direction of , Scroll bar and Frame Same width . Because the widest is the input control , In this way, the scroll bar is the same width as the input control .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved