有时候,做个小项目,没有太多复杂的需求,直接使用Python自带的GUI包Tkinter是个不错的选择,本文参考了使用过程的一些理解,给大伙做些分享 。
一个小case:长度转换import tkinter as tkfrom tkinter import ttkfrom tkinter.messagebox import showerror,showinfo,showwarningdef calculate(*args):try:value=https://www.sosowu.com/a/float(feet.get)meters.set(float(0.3048*value*10000.0+0.5)/10000.0)except ValueError:passroot=tk.Tkroot.title('Feet to Meters')mainframe=ttk.Frame(root,padding='3 3 12 12',) # 设置留白距离mainframe.grid(row=0,column=0,sticky=(tk.N,tk.W,tk.E,tk.S))root.columnconfigure(0,weight=1) # 列自动延展root.rowconfigure(0,weight=1) # 行自动延展feet=tk.StringVarfeet_entry=ttk.Entry(master=mainframe,width=7,textvariable=feet)feet_entry.grid(row=1,column=2,sticky='we')meters=tk.StringVarttk.Label(mainframe,textvariable=meters).grid(row=2,column=2,sticky='we')ttk.Button(mainframe,text='Calculate',command=calculate).grid(row=3,column=3,sticky='w')ttk.Label(mainframe,text='feet').grid(column=3,row=1,sticky='w')ttk.Label(mainframe,text='is equivalent to').grid(column=1,row=2,sticky='e')ttk.Label(mainframe,text='meters').grid(column=3,row=2,sticky='w')for child in mainframe.winfo_children: # 迭代各子控件child.grid_configure(padx=5,pady=5) # 配置widgets边距feet_entry.focus # 设置焦点控件root.bind('Return',calculate) # 根窗体绑定键盘回车事件root.mainloop面向对象的方法import tkinter as tkfrom tkinter import ttkclass FeetToMeters:def __init__(self, master):master.title('Feet to Meters')mainframe = ttk.Frame(master, padding='3 3 12 12')mainframe.grid(column=0, row=0, sticky='news')master.columnconfigure(0, weight=1)master.rowconfigure(0, weight=1)self.feet = tk.StringVarfeet_entry = ttk.Entry(mainframe, width=7, textvariable=self.feet)feet_entry.grid(column=2, row=1, sticky='we')self.meters = tk.StringVarttk.Label(mainframe, textvariable=self.meters).grid(column=2, row=2, sticky='we')ttk.Button(mainframe, text='Calculate', command=self.calculate).grid(column=3, /row=3, sticky='w')ttk.Label(mainframe, text='feet').grid(column=3, row=1, sticky='w')ttk.Label(mainframe, text='is equivalent to').grid(column=1, row=2, sticky='e')ttk.Label(mainframe, text='meters').grid(column=3, row=2, sticky='w')for child in mainframe.winfo_children:child.grid_configure(padx=5, pady=5)feet_entry.focusmaster.bind('Return', self.calculate)def calculate(self, *args):try:self.value = float(self.feet.get)self.meters.set(int(0.3048*self.value*10000.0+0.5)/10000.0)except ValueError:passroot=tk.TkFeetToMeters(root)root.mainloop基本窗体部件import tkinter as tkfrom tkinter import ttkroot = tk.Tkroot.resizable(width=False,height=True) # 主窗体尺寸是否可调#! Framef=ttk.Frame(root)f.configure(padding=(2,2), # 元组定义的留白方向:lrtb/(lr,tb)/(l,t,r,b)width=500,height=180,borderwidth=5,) f['relief'] = 'sunken' # 浮雕样式f.pack(fill = 'both')#! Labellbl = ttk.Label(f, text='starting.../nthe second line', padding=20, justify='right', anchor=tk.CENTER)lbl.grid(row=0)lbl.bind('Enter', lambda event: lbl.configure(text='Move mouse insede'))lbl.bind('Leave', lambda e: lbl.configure(text='Move mouse outside'))lbl.bind('ButtonPress-1', lambda e: lbl.configure(text=f'Clicked left mouse button at {e.x}, {e.y}'))lbl.bind('3', lambda e: lbl.configure(text='Clicked right mouse button'))lbl.bind('Double-1', lambda e: lbl.configure(text='Double clicked'))lbl.bind('B3-Motion',lambda e: lbl.configure(text=f'rigth button dragto {e.x},{e.y}'))# #! Buttonbtn = ttk.Button(f, text='OK', default='active', command=lambda: lbl.configure(text='Redo again'))btn.grid(row=1, sticky=tk.SE)#// btn.configure(state='disabled') # 设置状态为禁用#// print(btn.instate(['!disabled'])) # 判断当前状态#! CheckButtonmeasureSystem1 = tk.StringVarchbtn1=ttk.Checkbutton(f,text='Use Metric',variable=measureSystem1,onvalue='metric',offvalue='imperial',command=lambda: print(measureSystem1.get))chbtn1.grid(row=2, sticky=tk.SW)measureSystem2 = tk.StringVarchbtn2=ttk.Checkbutton(f,text='Use Metric',variable=measureSystem2,onvalue='metric',offvalue='imperial',command=lambda: print(measureSystem2.get))chbtn2.grid(row=2, column=1, sticky=tk.SW)chbtn2.configure(state='disabled')print(chbtn2.instate(['alternate'])) # 状态是否可选root.bind('Return', lambda event: btn.invoke) # 调用btn#! RidioButtongender = tk.StringVar(value='Male')rad_btn1 = ttk.Radiobutton(f, text='Male', variable=gender, value='Male',/command=lambda:print(gender.get))rad_btn2 = ttk.Radiobutton(f, text='Female', variable=gender, value='Female',/command=lambda:print(gender.get))rad_btn3 = ttk.Radiobutton(f, text='Unsure', variable=gender, value='Unsure',/command=lambda:print(gender.get))rad_btn1.grid(row=3, column=0, sticky=tk.W)rad_btn2.grid(row=3, column=1, sticky=tk.W)rad_btn3.grid(row=3, column=2, sticky=tk.E)#! Entryimport redef check_num(newval):valid = re.match('^[0-9a-z]*$', newval) is not None and len(newval) = 5if not valid:showerror(title='提示', message='错误的输入')num.set(contents.get)return valid# 传递调用对象输入框内的最新值(%P)check_num_wrapper=(root.register(check_num), '%P')contents = tk.StringVarentry = ttk.Entry(f,textvariable=contents,validate='all', # 指定触发校验的事件# 调用根窗体注册的事件方法validatecommand=check_num_wrapper)entry.grid(row=4, sticky='se')#// entry.bind('Enter', lambda e: contents.set('')) # 重置输入框#// root.bind('ButtonPress-3', lambda e: entry.delete(0, 'end'))# 删除指定内容num = tk.StringVare = ttk.Entry(f, textvariable=num, state='disabled')e.grid(column=1, row=4, sticky='we')root.bind('ButtonPress-3', lambda e: entry.insert(0,'new content')) # 初始化输入框#// def it_has_been_written(*args):#//print('entry has been writting...')#// contents.trace_add('write', it_has_been_written)#//entry.configure(state='readonly')root.mainloop词条的输入有效性验证import tkinter as tkfrom tkinter import ttkimport reroot = tk.Tkv = tk.StringVardef test(P, i , s , V, w, v, S, d):valid = re.match('^china$', P) is not Noneif valid:print('correct')print(P, i , s , V, w, v, S, d)return Trueelse:print('wrong ' /'entering')print(P, i , s , V, w, v, S, d)return Falsetest_wrapper = root.register(test) # 封装函数到根窗体e1=ttk.Entry(root,textvariable=v,validate='focus',# 调用根窗体注册的事件函数,并将对象的调用参数传递给事件函数validatecommand=(test_wrapper, '%P', '%i', '%s', '%V', '%W', '%v', '%S', '%d'))e1.insert(0, "china")e2 = tk.Entry(root, textvariable=v)e1.pack(padx=5, pady=5, fill=tk.X)e2.pack(padx=5, pady=5, ill=tk.X)root.mainloop百分号占位符的意义:
以上关于本文的内容,仅作参考!温馨提示:如遇专业性较强的问题(如:疾病、健康、理财等),还请咨询专业人士给予相关指导!
「辽宁龙网」www.liaoninglong.com小编还为您精选了以下内容,希望对您有所帮助:- 现在学习编程,学什么语言比较好?
- os/2?
- 克里斯蒂娜·Christina Aguilera 首次登上《VOGUE》封面!
- BoramyViguier2022春夏男装,推动和冲刺,融合古老,乐观闪亮
- 男装 Boramy Viguier 2022春夏男装系列,推动和冲刺,融合古老,乐观更为闪亮诱人
- 德国IEGuitar吉他两分频入门音改也有细腻听感
- 目前豆瓣 5.7,但 Guidi x《黑客帝国》会发售的「彩蛋」可以先看看
- Rossum隆力奇护手霜新 Logo 撞脸 Python,网友:确实都是蛇
- 刘一帆Guinness空降福建 带来全新沉浸体验
- the Personal Information Protection: Foreign Bank's Guidance