Python Tkinter Entry 属性和方法介绍
- 1. Entry
- 1.1标准属性
- 1.2方法
- 2. Entry属性和方法说明程序
- 2.1 窗口代码
- 2.2 属性和方法代码
1. Entry
Entry提供了用户输入内容的功能,也可以作为显示使用。Entry的属性有:
1.1标准属性
background, bd, bg, borderwidth, cursor,
exportselection, fg, font, foreground, highlightbackground,
highlightcolor, highlightthickness, insertbackground,
insertborderwidth, insertofftime, insertontime, insertwidth,
invalidcommand, invcmd, justify, relief, selectbackground,
selectborderwidth, selectforeground, show, state, takefocus,
textvariable, validate, validatecommand, vcmd, width,
xscrollcommand
以上属性来自于python tkinter的__init__文件。感兴趣的读者可以打开查看。
1.2方法
Entry有14种方法:
delete,get,icursor,index,
insert,selection_adjust,selection_clear,selection_from,
selection_present, selection_range, selection_to, xview,
xview_moveto, xview_scroll,
Entry的方法主要是选择输入框中的内容以及索引。
2. Entry属性和方法说明程序
此程序说明了Entry的所有属性和方法。可以通过下拉框选择,查看属性或者方法的效果以及如何设置属性。示例如下:
代码由两部分组成,第一部分是Tkinter窗口代码,第二部分是Entry属性数据
2.1 窗口代码
# coding:utf8
import tkinter as tk
from tkinter.ttk import *
from Entry_Parameter import *
import time
cbx_para = None # 属性下拉框
cbx_method = None # 方法下拉框
lbl_status = None # 输出说明性文字
lbl_code = None #示例代码
lbl_result = None #结果以及说明
entry_result = None #示例输入框
frm_code = None #代码Frame
frm_result = None #结果Frame
init_para = {} #记录输入框的初始设置
v_str = None #StringVar变量
check = None #检查条件注册
srl = None
def GetInitParameter():
global entry_result
global init_para
init_para = {}
for item in Entry_Parameter.parameter:
index = item.split("/")[0]
init_para[index] = entry_result[index]
def ClearParameter():
global entry_result
global init_para
for item in Entry_Parameter.parameter:
index = item.split("/")[0]
entry_result[index] = init_para[index]
def check_digit(content):
global lbl_result
if content.isdigit() or content == "":
lbl_result['text']='vcmd:'+content
lbl_result.grid(row=2,column=1)
return True
else:
lbl_result['text']='invvcmd:'+content
lbl_result.grid(row=2, column=1)
return False
def Para_Demo(*args):
global cbx_para
global lbl_code
global lbl_status
global lbl_result
global frm_result
global frm_code
global v_str
global check
global srl
index = cbx_para.current()
lbl_result.grid_forget()
entry_result.delete(0,tk.END)
srl.grid_forget()
#
if index in Entry_Parameter.Entry_Para:
ClearParameter()
frm_code.grid(row=3, column=1, padx=5, pady=5)
frm_result.grid(row=3, column=2, padx=5, pady=5)
frm_code["text"] = Entry_Parameter.parameter[index] + ":代码"
frm_result["text"] = Entry_Parameter.parameter[index] + ":效果"
temp = Entry_Parameter.Entry_Para[index]
dis_code = ""
for item in range(1, len(temp[0])):
dis_code = dis_code + temp[0][item] + "\n"
dis_code += temp[1]
lbl_code['text'] = dis_code
for item in range(1, len(temp[0])):
exec(temp[0][item])
lbl_status['text'] = temp[2]
else:
frm_code.grid_forget()
frm_result.grid_forget()
def Method_Demo(*args):
global cbx_method
global lbl_code
global lbl_status
global lbl_result
global frm_result
global frm_code
index = cbx_method.current()
lbl_result.grid_forget()
entry_result.delete(0, tk.END)
#
if index in Entry_Parameter.Entry_Method:
ClearParameter()
frm_code.grid(row=3, column=1, padx=5, pady=5)
frm_result.grid(row=3, column=2, padx=5, pady=5)
frm_code["text"] = Entry_Parameter.method[index] + ":代码"
frm_result["text"] = Entry_Parameter.method[index] + ":效果"
temp = Entry_Parameter.Entry_Method[index]
dis_code = ""
for item in range(1, len(temp[0])):
dis_code = dis_code + temp[0][item] + "\n"
dis_code += temp[1]
lbl_code['text'] = dis_code
for item in range(1, len(temp[0])):
exec(temp[0][item])
lbl_status['text'] = temp[2]
else:
frm_code.grid_forget()
frm_result.grid_forget()
def center_window(root, width, height):
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
size = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
root.geometry(size)
def main():
root = tk.Tk()
# 属性下拉框
# 输入框
global frm_code
global frm_result
global v_str
v_str = tk.StringVar()
frm_top = tk.Frame(root)
frm_top.grid(row=1, column=1, sticky="W", columnspan=3, pady=2)
sp = Separator(root, orient='horizontal')
sp.grid(row=2, column=1, columnspan=2, sticky="nwse")
frm_code = tk.LabelFrame(root, text="")
frm_code.grid(row=3, column=1, padx=10)
sp = Separator(root, orient='vertical')
sp.grid(row=3, column=2, sticky="nwse")
frm_result = tk.LabelFrame(root, text="")
frm_result.grid(row=3, column=2, pady=5)
sp = Separator(root, orient='horizontal')
sp.grid(row=4, column=1, columnspan=2, sticky="nwse")
frm_bottom = tk.Frame(root)
frm_bottom.grid(row=5, column=1, columnspan=3, sticky="w")
nCbx_Height = 10
tk.Label(frm_top, text="属性:").grid(row=1, column=1, sticky="e")
global cbx_para
global cbx_method
# 属性
txt = [Entry_Parameter.parameter[item] + ":" + Entry_Parameter.parameter_info[item] for item in range(len(Entry_Parameter.parameter))]
cbx_para = Combobox(frm_top, height=nCbx_Height, values=txt, width=38)
cbx_para.bind("<<ComboboxSelected>>", Para_Demo)
cbx_para.set(txt[0])
cbx_para.grid(row=1, column=2)
# 方法
tk.Label(frm_top, text="方法:").grid(row=1, column=3, sticky="e", padx=10)
txt = [Entry_Parameter.method[item] + ":" + Entry_Parameter.method_info[item]
for item in range(len(Entry_Parameter.method))]
cbx_method = Combobox(frm_top, height=nCbx_Height, value=txt, width=33)
cbx_method.bind("<<ComboboxSelected>>", Method_Demo)
cbx_method.set(txt[0])
cbx_method.grid(row=1, column=4)
global lbl_status
lbl_status = tk.Label(frm_bottom, text="", anchor="w", justify="left")
lbl_status.grid(row=1, column=1, sticky="w")
global lbl_code
lbl_code = tk.Label(frm_code, text="", justify="left")
lbl_code.grid(row=1, column=1)
global entry_result
entry_result = tk.Entry(frm_result)
entry_result.grid(row=1, column=1)
global lbl_result
lbl_result = tk.Label(frm_result, text="", justify="left", pady=5)
lbl_result.grid(row=2, column=1)
global srl
srl = tk.Scrollbar(frm_result, orient=tk.HORIZONTAL)
GetInitParameter()
frm_result.grid_forget()
frm_code.grid_forget()
global check
check=root.register(check_digit)
root.title("Tkinter 输入框使用说明")
center_window(root, 650, 360)
root.mainloop()
if __name__ == "__main__":
main()
"""tkinter中关于Entry的注释
background, bd, bg, borderwidth, cursor,
exportselection, fg, font, foreground, highlightbackground,
highlightcolor, highlightthickness, insertbackground,
insertborderwidth, insertofftime, insertontime, insertwidth,
invalidcommand, invcmd, justify, relief, selectbackground,
selectborderwidth, selectforeground, show, state, takefocus,
textvariable, validate, validatecommand, vcmd, width,
xscrollcommand
"""
2.2 属性和方法代码
Entry_Parameter.py
#coding:utf8
class Entry_Parameter():
#Entry 参数名称
parameter=["background/bg","borderwidth/bd","cursor", "exportselection",
"font","foreground/fg","highlightbackground", "highlightcolor",
"highlightthickness","insertbackground","insertborderwidth","insertofftime",
"insertontime","insertwidth" ,"invalidcommand/invcmd","justify",
"relief","selectbackground","selectborderwidth","selectforeground",
"show","state","takefocus","textvariable",
"validate","validatecommand/vcmd","width", "xscrollcommand"]
#Entry 参数说明
parameter_info=["背景颜色", "边框宽度", "光标样式","保留选择",
"字体","文本颜色","未获得焦点时边框颜色","获得焦点时边框颜色",
"焦点边框宽度","输入框内光标的颜色","输入框内光标的边框宽度","不显示光标的时间",
"显示光标的时间","插入光标的宽度","验证输入不符合要求","文字对齐方式",
"边框效果","选中文本的背景颜色","选中区域的边框宽度","选中区域的文本颜色",
"设定输入内容的替代值","状态", "使用Tab获得焦点","StringVar变量与输入框相关联",
"定义输入验证触发条件","验证输入符合要求","宽度","设置滚动条"
]
#Entry 方法
method=["delete","get","icursor","index",
"insert","selection_adjust","selection_clear","selection_from",
"selection_present", "selection_range", "selection_to", "xview",
"xview_moveto", "xview_scroll",
]
#Entry 方法说明
method_info=["删除内容","获取内容","移动光标到指定位置","指定参数的位置",
"插入内容","选择区域调整","选择取消","选择开始位置",
"检测字符是否被选中", "选择范围", "选择结束位置", "移动到指定位置",
"按百分比移动到指定位置", "滚动到指定位置"
]
#Entry 说明,包括序号、代码说明、代码、运行效果
Entry_Para = {
0: [["background/bg:", "entry_result['bg']='green'",],
"",
"background/bg:指定输入框的背景颜色"],
1: [["borderwidth/bd:", "entry_result['bd']=20"],
"",
"bd:设置文本到Label边界的宽度\nbd参数相当于设置了padx和pady参数"
],
2: [["cursor:", "entry_result['cursor']='watch'"],
"",
"cursor:鼠标经过输入框时的光标"
],
3: [["exportselection:","entry_result['exportselection']=True"],
"",
"exportselection:可以设置为True或者False。当设置为False时,可以保留在其他Widget中的选择值。\nEntry中无效。可参考Listbox。"
],
4: [["font:", "entry_result['font']=('宋体',20,)", "entry_result.insert(tk.END,'font=20')"],
"",
"font:设置文本字体。\n一个输入框只能用一种字体。\n字体定义可以使用三元组(字体名称,大小,修饰)\n也可以使用Font类"
],
5: [["foreground/fg:", "entry_result['fg']='red'", "entry_result.insert(tk.END,'红色文本')"],
"",
"fg:设置输入框文本的颜色"],
6: [["highlightbackground:", "entry_result['highlightbackground']='blue'","entry_result['highlightcolor']='green'",
"entry_result['highlightthickness']=10","entry_result.insert(tk.END,'输入框获得/失去焦点时边框的设置')"],
"",
"highlightbackground:未获得焦点时边框颜色\n一般与highlightcolor、highlightthickness配合使用\n按Tab键变换输入焦点可以看到效果"],
7: [["highlightcolor:", "entry_result['highlightbackground']='blue'","entry_result['highlightcolor']='green'",
"entry_result['highlightthickness']=10","entry_result.insert(tk.END,'输入框获得/失去焦点时边框的设置')"],
"",
"highlightcolor:获得焦点时边框颜色\n一般与highlightbackground、highlightthickness配合使用\n按Tab键变换输入焦点可以看到效果"],
8: [["highlightthickness:", "entry_result['highlightbackground']='blue'","entry_result['highlightcolor']='green'",
"entry_result['highlightthickness']=10","entry_result.insert(tk.END,'输入框获得/失去焦点时边框的设置')"],
"",
"highlightthickness:焦点边框宽度\n一般与highlightbackground、highlightcolor配合使用\n按Tab键变换输入焦点可以看到效果"],
9: [["insertbackground:", "entry_result['insertbackground']='red'","entry_result.insert(tk.END,'输入光标')"],
"",
"insertbackground:输入框光标状态。"],
10: [["insertborderwidth:", "entry_result['insertborderwidth']=-2", "entry_result.insert(tk.END,'光标的边框')"],
"",
"insertborderwidth:设定输入框内光标的边框宽度。\n0:没有边框\n1+:一个像素的边框\n负数:按照绝对值设置光标的边框"],
11: [["insertofftime:","entry_result['insertofftime']=500", "entry_result['insertontime']=500",
"entry_result.insert(tk.END,'光标闪烁')","entry_result.focus_set()"],
"",
"insertofftime:不显示光标的时间\n与insertontime一起使用,产生光标闪烁效果"
],
12: [["insertontime:","entry_result['insertofftime']=500", "entry_result['insertontime']=500",
"entry_result.insert(tk.END,'光标闪烁')","entry_result.focus_set()"],
"",
"insertontime:显示光标的时间\n与insertofftime一起使用,产生光标闪烁效果"],
13: [["insertwidth:","entry_result['insertwidth']=5","entry_result.focus_set()"],
"",
"insertwidth:插入光标的宽度"],
14: [["invalidcommand/invcmd:", "entry_result['validate']='key'","entry_result['vcmd']=(check,'%P')", "entry_result['invcmd']=(check,'%P')"],
"def check_digit(content):\n if content.isdigit() or content == ‘’:\n return True\n"
" else:\n return False\ncheck=root.register(check_digit)",
"invalidcommand/invcmd:输入不符合validate设置的条件触发\n必须与validate、validatecmd一起使用,\nvalidate触发条件有多种,参考validate属性说明"],
15: [["justify", "entry_result['justify']=tk.RIGHT", "entry_result.insert(tk.END,'文字右对齐')"],
"",
"justify:文本的对齐方式\n支持left,right,center"],
16: [["relief:", "entry_result.insert(tk.END,'边框修饰效果')", "entry_result['bd']=10", "entry_result['relief']='raised'"],
"",
"relief:输入框边框的修饰效果\n可设为flat, groove, raised, ridge, solid, or sunken"],
17: [["selectbackground:", "entry_result.insert(tk.END,'选中文本的背景是红色')","entry_result['selectbackground']='red'"],
"",
"selectbackground:选中文本的背景颜色"],
18: [["selectborderwidth:","entry_result.insert(tk.END,'选中区域的边框宽度')","entry_result['selectborderwidth']=5"],
"",
"selectborderwidth:选中区域的边框宽度"],
19: [["selectforeground:","entry_result.insert(tk.END,'选择文本的颜色')","entry_result['selectforeground']='red'"],
"",
"selectforeground:选择文本的颜色"],
20: [["show:", "entry_result['show']='*'"],
"",
"show:设定输入内容的替代值"],
21: [["state:", "entry_result.insert(tk.END,'禁止状态,不能进行任何操作')","entry_result['state']=tk.DISABLED"],
"",
"state:设置输入框状态,有normal,disabled和readonly三种状态"],
22: [["takefocus:", "entry_result['takefocus']=True", "entry_result.insert(tk.END,'获得输入焦点')"],
"",
"takefocus:支持获得输入焦点。"],
23: [["textvariable", "v_str.set('通过textvariable改变输入框文本')","entry_result['textvariable']=v_str"],
"",
"textvariable:设置关联tkinter的变量,用来修改或者获得输入控件的数据"],
24: [["validate:", "entry_result['validate']='key'","entry_result['vcmd']=(check,'%P')", "entry_result['invcmd']=(check,'%P')"],
"def check_digit(content):\n if content.isdigit() or content == ‘’:\n return True\n"
" else:\n return False\ncheck=root.register(check_digit)",
"validate:设置如何触发验证条件\n1.focus:获得或者失去输入焦点时候\n2.focuin:仅在获得输入焦点的时候\n3.focusout: 失去输入焦点的时候\n"
"4.key: 输入框种内容改变的时候\n5. ALL:以上全部情况\n必须有validatecommand,invalidatecommand是可选的"],
25: [["validatecommand/vcmd:", "entry_result['validate']='key'","entry_result['vcmd']=(check,'%P')", "entry_result['invcmd']=(check,'%P')"],
"def check_digit(content):\n if content.isdigit() or content == ‘’:\n return True\n"
" else:\n return False\ncheck=root.register(check_digit)",
"validatecommand/vcmd:验证输入符合要求\n与validate配合使用"],
26: [["width:","entry_result['width']=30","lbl_result.insert(tk.END,'width=30')"],
"",
"width:定义输入框宽度。单位是字符"],
27: [["xscrollcommand:", "entry_result['xscrollcommand']=srl.set","srl.grid(row=2,column=1,sticky='nwse')",
"srl.config(command=entry_result.xview)"],
"\nsrl = tk.Scrollbar(frm_result,orient=tk.HORIZONTAL)",
"xscrollcommand:设置滚动条。\n当输入内容过长时,可以用滚动条来滚动显示文本"],
}
#Entry 方法代码说明
Entry_Method = {
0:[["delete:","entry_result.insert(tk.END,'123456789')","entry_result.delete(1,4)",
"lbl_result['text']='原始内容为123456789'","lbl_result.grid(row=2,column=1)",],
"",
"delete(first,last=None):从first开始删除到last定义的位置"],
1:[["get:","entry_result.insert(tk.END,'123456789')",
"lbl_result['text']='entry_result.get()='+entry_result.get()","lbl_result.grid(row=2,column=1)",],
"",
"get():获得输入控件中的当前内容"],
2: [["icursor:", "entry_result.insert(tk.END,'123456789')","entry_result.focus_force()",
"entry_result.icursor(4)" ],
"",
"icursor(index):移动输入光标到指定的位置"],
3: [["index:", "entry_result.insert(tk.END,'123456789')", "lbl_result.grid(row=2,column=1)",
"lbl_result['text']='end:'+str(entry_result.index(tk.END))"],
"",
"index(index):返回输入参数的位置\n1.tk.END : 输入框最后一个字符后的位置\n"
"2.tk.INSERT :插入光标所在的位置\n"
"3.tk.ANCHOR : 选择的锚定位置\n"
"4.tk.SEL_FIRST :选择区域开始的位置\n"
"5.tk.SEL_LAST :选择区域结束后的位置\n"
"6.‘@x’ :输入x坐标,返回位于该坐标的字符的位置"
],
4: [["insert:", "entry_result.insert(tk.END,'123456789')", "lbl_result.grid(row=2,column=1)",
"lbl_result['text']=entry_result.get()"],
"",
"insert(index,string):在指定位置插入字符串"],
5: [["selection_adjust:", "entry_result.insert(tk.END,'123456789')","entry_result.selection_adjust(5)",
"entry_result.focus_force()",
"lbl_result.grid(row=2,column=1)","lbl_result['text']=entry_result.selection_get()"],
"",
"selection_adjust(index):选择从光标到index位置的字符\n废弃的函数是select_adjust"],
6: [["selection_clear:", "entry_result.insert(tk.END,'123456789')", "entry_result.selection_adjust(5)",
"entry_result.focus_force()",
"lbl_result.grid(row=2,column=1)", "lbl_result['text']=entry_result.selection_get()",
"entry_result.selection_clear()",
],
"",
"selection_clear():清除当前选择\n废弃的函数是select_clear"],
7: [["selection_from:", "entry_result.insert(tk.END,'123456789')",
"entry_result.selection_from(2)","entry_result.selection_to(7)",
"entry_result.focus_force()"],
"",
"selection_from(index):选择从index开始\n与selection_to配合使用\n废弃的函数是select_from"],
8: [["selection_present:", "entry_result.insert(tk.END,'123456789')",
"entry_result.selection_adjust(5)", "entry_result.focus_force()",
"lbl_result.grid(row=2,column=1)", "lbl_result['text']=entry_result.selection_present()",
],
"",
"selection_present():检测字符是否被选中。有被选择的字符返回True,否则返回False"],
9: [["selection_range:", "entry_result.insert(tk.END,'123456789')",
"entry_result.selection_range(2,5)", "entry_result.focus_force()",
"lbl_result.grid(row=2,column=1)", "lbl_result['text']=entry_result.selection_get()",
],
"",
"selection_range(start,end):选择[start,end)区域内的文本"],
10: [["selection_to:", "entry_result.insert(tk.END,'123456789')",
"entry_result.selection_from(2)", "entry_result.selection_to(7)",
"entry_result.focus_force()"],
"",
"selection_to(index):选择在index结束\n与selection_from配合使用\n废弃的函数是select_to"],
11: [["xview:", "entry_result.insert(tk.END,'1234567890abcdefghijklmnopq')",
"entry_result.xview(10)",
"entry_result.focus_force()"],
"",
"xview(index):保证index位置的字符可以显示\n如果字符很长,index会显示在最左边,否则在输入框中可见就行"],
12: [["xview_moveto:", "entry_result.insert(tk.END,'1234567890abcdefghijklmnopq')",
"entry_result.xview_moveto(0.8)",
"entry_result.focus_force()"],
"",
"xview_moveto(index):方法和xview类似,不过参数是一个浮点数,按照百分比设定要滚动到的位置"
],
13:[["xview_scroll:", "entry_result.insert(tk.END,'1234567890abcdefghijklmnopqrstuvwxyz')",
"entry_result.xview_scroll(7,'unit')",
"entry_result.focus_force()"],
"",
"xview_scroll(number,what):滚动到指定的位置,number是位置,what是单位\n单位有unit和page两种\n"
"unit:按照字符个数来计量的\n"
"page:按照输入框的宽度来计量的。如果输入控件的宽度是10,则滚动的数量就是10的倍数"],
}