Python GUI 编程 01 : Tkinter基础控件( 二 )


'%P'--当输入框可编辑时,值为输入框的最新文本内容;
'%i'--用户插入或删除操作的位置索引,获失焦点或textvariable变量值被修改该值为-1;
'%s'--调用验证函数前输入框的文本内容;
'%V'--调用验证函数的原因;
'%W'--当前组件名;
'%v'--当前validate选项的值;
'%S'--当插入和删除操作触发验证时,表示文本被插入和删除的内容;
'%d'--操作代码0删除/1插入/2获失焦点或textvariable变量值被修改;
【Python GUI 编程 01 : Tkinter基础控件】Case: 加法计算器import tkinter as tkfrom tkinter import ttkroot = tk.Tkframe = ttk.Frame(root) # 把整个布局放到框架中,更好调节frame.pack(padx=10, pady=10)v1 = tk.StringVarv2 = tk.StringVarv3 = tk.StringVardef validate(content):if content.isdigit: # isdigit方法,这是str的一个函数,只允许输入数字return Trueelse:print("invalid inputing")return False# 注册根窗体事件方法testCmd = root.register(validate) # 通过register方法转换为validatecommand选项能接收的函数ttk.Entry(frame, textvariable=v1, width=10, validate='key', \validatecommand=(testCmd, '%P')).grid(row=0, column=0) # 用%P获取最新输入的字符串ttk.Label(frame, text='+').grid(row=0, column=1)ttk.Entry(frame, textvariable=v2, width=10, validate='key', \validatecommand=(testCmd, '%P')).grid(row=0, column=2)ttk.Label(frame, text='=').grid(row=0, column=3)ttk.Entry(frame, textvariable=v3, width=10, state='readonly', validate='key', \validatecommand=(testCmd, '%P')).grid(row=0, column=4)def calc:result = int(v1.get) + int(v2.get)v3.set(result)ttk.Button(frame, text='计算结果', command=calc).grid(row=1, column=2, pady=5)root.mainloopCase:邮编格式验证import tkinter as tkfrom tkinter import ttkimport re root = tk.Tkerrmsg = tk.StringVarformatmsg = "Zip should be ##### or #####-####"def check_zip(newval, op):errmsg.set('')valid = re.match('^[0-9]{5}(\-[0-9]{4})?$', newval) is not Nonebtn.state(['!disabled'] if valid else ['disabled'])if op == 'key': # 当validate='key'时ok_so_far = re.match('^[0-9\-]*$', newval) is not None and len(newval) = 10if not ok_so_far:errmsg.set(formatmsg)return ok_so_farelif op == 'focusout':if not valid:errmsg.set(formatmsg)return validcheck_zip_wrapper = (root.register(check_zip), '%P', '%V') # validatecommand对象必须是元组或列表zip = tk.StringVarf = ttk.Frame(root)f.grid(column=0, row=0)ttk.Label(f, text='Name:').grid(column=0, row=0, padx=5, pady=5)ttk.Entry(f).grid(column=1, row=0, padx=5, pady=5)ttk.Label(f, text='Zip:').grid(column=0, row=1, padx=5, pady=5)e=ttk.Entry(f, textvariable=zip, validate='all', validatecommand=check_zip_wrapper, \invalidcommand=lambda: e.focus)e.grid(column=1, row=1, padx=5, pady=5)btn=ttk.Button(f, text='Process')btn.grid(column=2, row=1, padx=5, pady=5)btn.state(['disabled'])msg=ttk.Label(f, foreground='red', textvariable=errmsg, anchor='center')msg.grid(column=0, row=2, padx=5, columnspan=3, pady=5)root.mainloop下拉列表框:Comboboximport tkinter as tkfrom tkinter import ttkfrom faker import Fakerroot = tk.Tkf = ttk.Frame(root)f.grid(column=0, row=0, sticky='news')countryVar = tk.StringVarcountry = ttk.Combobox(f, textvariable=countryVar, height=10,) # height 可见高度10行def getCountrys(n):f = Fakerfor _ in range(n):yield str(_+1) + " " + f.countrycountry.configure(values = list(getCountrys(15)))country.state(['readonly']) # 列表框状态为只读country.bind('ComboboxSelected',lambda e: print(f'{countryVar.get} select ...')) # 绑定虚拟事件country.current(5)# combobox.current(index) 通过设置索引值选定取值country.pack(fill=tk.X)#! 样式管理器ttk.styles = ttk.Styles.configure('Danger.TFrame', background='red', borderwidth=5, relief='raised')ttk.Frame(root, width=250, height=200, style='Danger.TFrame').gridroot.mainloop 事件处理:Event HandlingActivate: 窗体被激活Deactivate: 窗体被切换或未被激活MouseWheel: 鼠标滚轮动作KeyPress: 键盘按键被按下KeyRelease: 键盘按键释放ButtonPress: 鼠标按键按下ButtonRelease: 鼠标按键释放Motion: 鼠标运动Configure: 窗体部件大小或位置发生变化Destroy: 部件被销毁FocusIn: 部件获得键盘输入焦点FocusOut: 部件失去键盘输入焦点Enter: 鼠标进入部件范围Leave: 鼠标离开部件范围


以上关于本文的内容,仅作参考!温馨提示:如遇专业性较强的问题(如:疾病、健康、理财等),还请咨询专业人士给予相关指导!

「辽宁龙网」www.liaoninglong.com小编还为您精选了以下内容,希望对您有所帮助: