tkinter
知识内容:
1.Tkinter介绍
2.Tkinter实战1-用户登录界面
3.Tkinter实战2-选择类组件综合应用
4.Tkinter实战3-简单文本编辑器
5.Tkinter实战4-简单画图程序
6.Tkinter实战5-电子时钟
一、Tkinter介绍
1.tkinter简单介绍
tkinter是python标准库中专门用来做GUI界面的模块,可以使用tkinter开发一些界面
2.tkinter简单使用
1 # __author__ = "wyb" 2 # date: 2018/4/29 3 4 import tkinter # 导入tkinter模块 5 6 root = tkinter.Tk() # 创建主窗口 7 8 root.mainloop() # 进行主循环显示窗口直达关闭窗口
二、Tkinter实战1-用户登录界面
1 # __author__ = "wyb" 2 # date: 2018/5/10 3 4 import tkinter 5 import tkinter.messagebox 6 7 8 # OK按钮响应事件 9 def login(): 10 name = entryName.get() # 获取用户名 11 pwd = entryPwd.get() # 获取密码 12 if name == 'admin' and pwd == '123456': 13 tkinter.messagebox.showinfo(title="python tkinter", message="welcome login") 14 else: 15 tkinter.messagebox.showerror(title="python tkinter", message="Wrong username or password") 16 17 18 # Cancel按钮响应事件 19 def cancel(): 20 varName.set('') 21 varPwd.set('') 22 23 24 root = tkinter.Tk() 25 26 # 申明变量存储用户名和密码 27 varName = tkinter.StringVar(value='') 28 varPwd = tkinter.StringVar(value='') 29 30 # 建立用户名和密码输入提示和输入框: 31 labelName = tkinter.Label(root, text='User Name:', justify=tkinter.RIGHT, width=80) 32 labelName.place(x=10, y=5, width=80, height=20) 33 entryName = tkinter.Entry(root, width=80, textvariable=varName) 34 entryName.place(x=100, y=5, width=80, height=20) 35 labelPwd = tkinter.Label(root, text='User pwd:', justify=tkinter.RIGHT, width=80) 36 labelPwd.place(x=10, y=30, width=80, height=20) 37 entryPwd = tkinter.Entry(root, show='*', width=80, textvariable=varPwd) 38 entryPwd.place(x=100, y=30, width=80, height=20) 39 40 # 建立OK和Cancel按钮并绑定事件: 41 buttonOk = tkinter.Button(root, text='Login', command=login) 42 buttonOk.place(x=30, y=70, width=50, height=20) 43 buttonCancel = tkinter.Button(root, text='Cancel', command=cancel) 44 buttonCancel.place(x=90, y=70, width=50, height=20) 45 46 root.mainloop() # 启动消息循环
三、Tkinter实战2-选择类组件综合应用
1 # __author__ = "wyb" 2 # date: 2018/5/10 3 4 import tkinter 5 import tkinter.messagebox 6 import tkinter.ttk 7 8 # 创建窗体并设置标题以及高和宽 9 root = tkinter.Tk() 10 root.title('选择类组件综合运用') 11 root['height'] = 390 12 root['width'] = 350 13 14 # 创建姓名标签和输入框 15 labelName = tkinter.Label(root, text='Name:', justify=tkinter.RIGHT, width=50) 16 labelName.place(x=10, y=5, width=50, height=20) 17 varName = tkinter.StringVar(value='') 18 entryName = tkinter.Entry(root, width=120, textvariable=varName) 19 entryName.place(x=70, y=5, width=120, height=20) 20 21 # 创建年纪班级标签及选择框 22 studentClasses = { 23 '1': ['1', '2', '3', '4'], 24 '2': ['1', '2'], 25 '3': ['1', '2', '3'] 26 } 27 labelGrade = tkinter.Label(root, text='Grade: ', justify=tkinter.RIGHT, width=50) 28 labelGrade.place(x=10, y=40, width=50, height=20) 29 comboGrade = tkinter.ttk.Combobox(root, values=tuple(studentClasses.keys()), width=50) 30 comboGrade.place(x=70, y=40, width=50, height=20) 31 labelClass = tkinter.Label(root, text='Class:', justify=tkinter.RIGHT, width=50) 32 labelClass.place(x=130, y=40, width=50, height=20) 33 comboClass = tkinter.ttk.Combobox(root, width=50) 34 comboClass.place(x=190, y=40, width=50, height=20) 35 36 # 创建性别标签及单选框 37 labelSex = tkinter.Label(root, text='Sex:', justify=tkinter.RIGHT, width=50) 38 labelSex.place(x=10, y=70, width=50, height=20) 39 sex = tkinter.IntVar(value=1) # 绑定变量 40 radioMan = tkinter.Radiobutton(root, variable=sex, value=1, text='Man') 41 radioMan.place(x=70, y=70, width=50, height=20) 42 radioWoman = tkinter.Radiobutton(root, variable=sex, value=0, text='Woman') 43 radioWoman.place(x=130, y=70, width=70, height=20) 44 45 # 创建班长多选框 46 monitor = tkinter.IntVar(value=0) # 是否是班长 默认为0表示不是班长 47 checkMonitor = tkinter.Checkbutton(root, text='Is Monitor?', variable=monitor, onvalue=1, offvalue=0) 48 checkMonitor.place(x=20, y=100, width=100, height=20) 49 50 51 # 按钮事件处理函数 52 # 53 def comboChange(event): 54 grade = comboGrade.get() 55 if grade: 56 comboClass["values"] = studentClasses.get(grade) 57 58 # 添加信息 59 def addInformation(): 60 result = 'Name:' + entryName.get() 61 result = result + ';Grade:' + comboGrade.get() 62 result = result + ';Class:' + comboClass.get() 63 result = result + ';Sex:' + ('Man' if sex.get() else 'Woman') 64 result = result + ';Monitor:' + ('Yes' if monitor.get() else 'No') 65 listboxStudents.insert(0, result) 66 67 68 # 创建添加按钮 69 buttonAdd = tkinter.Button(root, text='Add', width=40, command=addInformation) 70 buttonAdd.place(x=130, y=100, width=40, height=20) 71 72 73 # 删除信息 74 def deleteSelection(): 75 selection = listboxStudents.curselection() 76 if not selection: 77 tkinter.messagebox.showinfo(title='infomation', message='No Selection') 78 else: 79 listboxStudents.delete(selection) 80 81 82 # 创建删除按钮 83 buttonDelete = tkinter.Button(root, text='DeleteSelection', width=100, command=deleteSelection) 84 buttonDelete.place(x=180, y=100, width=100, height=20) 85 86 # 创建多行文本框 87 listboxStudents = tkinter.Listbox(root, width=30) 88 listboxStudents.place(x=10, y=130, width=300, height=200) 89 90 root.mainloop()
四、Tkinter实战3-简单文本编辑器
1 # __author__ = "wyb" 2 # date: 2018/5/10 3 import tkinter 4 import tkinter.filedialog 5 import tkinter.colorchooser 6 import tkinter.messagebox 7 import tkinter.scrolledtext 8 import tkinter.simpledialog 9 10 # 创建应用程序窗口 11 app = tkinter.Tk() 12 app.title('简单文本编辑器') 13 app['width'] = 800 14 app['height'] = 600 15 16 textChanged = tkinter.IntVar(value=0) 17 # 当前文件名 18 filename = '' 19 20 # 创建菜单 21 menu = tkinter.Menu(app) 22 # File菜单 23 submenu = tkinter.Menu(menu, tearoff=0) 24 25 26 # 打开 27 def Open(): 28 global filename 29 # 如果内容以及改变,先保存 30 if textChanged.get(): 31 yesno = tkinter.messagebox.askyesno(title='保存', message='是否保存') 32 if yesno == tkinter.YES: 33 Save() 34 filename = tkinter.filedialog.askopenfilename(title='打开文件', filetype=[('Text files', '*.txt')]) 35 36 if filename: 37 # 清空内容,0.0是lineNumber.Column的表示方法 38 txtContent.delete(0.0, tkinter.END) 39 fp = open(filename, 'r') 40 txtContent.insert(tkinter.INSERT, ''.join(fp.readlines())) 41 fp.close() 42 # 标记为尚未修改 43 textChanged.set(0) 44 45 46 # 创建File菜单选项Open并绑定菜单事件处理函数 47 submenu.add_command(label='Open', command=Open) 48 49 50 # 保存 51 def Save(): 52 global filename 53 # 如果是第一次保存新建则打开另存为窗口 54 if not filename: 55 SaveAs() 56 # 如果内容发送变化就保存 57 elif textChanged.get(): 58 fp = open(filename, 'w') 59 fp.write(txtContent.get(0.0, tkinter.END)) 60 fp.close() 61 textChanged.set(0) 62 63 64 # 创建File菜单选项Save并绑定菜单事件处理函数 65 submenu.add_command(label='Save', command=Save) 66 67 68 # 另存 69 def SaveAs(): 70 global filename 71 # 打开另存为窗口 72 newfilename = tkinter.filedialog.asksaveasfilename(title='Save As', initialdir=r'c:\\', initialfile='new.txt') 73 # 如果指定了文件名则保存文件 74 if newfilename: 75 fp = open(newfilename, 'w') 76 fp.write(txtContent.get(0.0, tkinter.END)) 77 fp.close() 78 textChanged.set(0) 79 80 81 # 创建File菜单选项Save As并绑定菜单事件处理函数 82 submenu.add_command(label='Save As', command=SaveAs) 83 # 添加分割线 84 submenu.add_separator() 85 86 87 # 关闭 88 def Close(): 89 global filename 90 Save() 91 txtContent.delete(0.0, tkinter.END) 92 # 置空文件名 93 filename = '' 94 95 96 # 创建File菜单选项Close并绑定菜单事件处理函数 97 submenu.add_command(label='Close', command=Close) 98 # 将File菜单关联到主菜单上 99 menu.add_cascade(label='File', menu=submenu) 100 101 # Edit菜单 102 submenu = tkinter.Menu(menu, tearoff=0) 103 104 105 # 撤销 106 def Undo(): 107 # 启用undo标志 108 txtContent['undo'] = True 109 try: 110 txtContent.edit_undo() 111 except Exception as e: 112 pass 113 114 115 # 创建Edit菜单选项Undo并绑定菜单事件处理函数 116 submenu.add_command(label='Undo', command=Undo) 117 118 119 # 120 def Redo(): 121 txtContent['undo'] = True 122 try: 123 txtContent.edit_redo() 124 except Exception as e: 125 pass 126 127 128 # 创建Edit菜单选项Redo并绑定菜单事件处理函数 129 submenu.add_command(label='Redo', command=Redo) 130 # 添加分割线 131 submenu.add_separator() 132 133 134 # 赋值 135 def Copy(): 136 txtContent.clipboard_clear() 137 txtContent.clipboard_append(txtContent.selection_get()) 138 139 140 # 创建Edit菜单选项Copy并绑定菜单事件处理函数 141 submenu.add_command(label='Copy', command=Copy) 142 143 144 # 剪切 145 def Cut(): 146 Copy() 147 # 删除所选内容 148 txtContent.delete(tkinter.SEL_FIRST, tkinter.SEL_LAST) 149 150 151 # 创建Edit菜单选项Cut并绑定菜单事件处理函数 152 submenu.add_command(label='Cut', command=Cut) 153 154 155 # 粘贴 156 def Paste(): 157 # 如果没有选择内容则直接粘贴到鼠标位置 158 # 如果有所选内容,则先删除再粘贴 159 try: 160 txtContent.insert(tkinter.SEL_FIRST, txtContent.clipboard_get()) 161 txtContent.delete(tkinter.SEL_FIRST, tkinter.SEL_LAST) 162 # 如果粘贴成功就结束本函数以免异常处理结构执行完成之后再次粘贴 163 return 164 except Exception as e: 165 pass 166 167 168 # 创建Edit菜单选项Paste并绑定菜单事件处理函数 169 submenu.add_command(label='Paste', command=Paste) 170 # 添加分割线 171 submenu.add_separator() 172 173 174 # 搜索 175 def Search(): 176 # 获取要查找的内容 177 textToSearch = tkinter.simpledialog.askstring(title='Search', prompt='What to search?') 178 start = txtContent.search(textToSearch, 0.0, tkinter.END) 179 if start: 180 tkinter.messagebox.showinfo(title='Found', message='OK') 181 182 183 # 创建Edit菜单选项Search并绑定菜单事件处理函数 184 submenu.add_command(label='Search', command=Search) 185 # 将Edit菜单关联到主菜单上 186 menu.add_cascade(label='Edit', menu=submenu) 187 188 # Help菜单 189 submenu = tkinter.Menu(menu, tearoff=0) 190 191 192 def About(): 193 tkinter.messagebox.showinfo(title='About the author', message='Author: wyb') 194 195 196 # 创建Help菜单选项About并绑定菜单事件处理函数 197 submenu.add_command(label='About', command=About) 198 # 将Help菜单关联到主菜单上 199 menu.add_cascade(label='Help', menu=submenu) 200 # 将创建的菜单关联到应用程序窗口 201 app.config(menu=menu) 202 203 # 创建文本编辑器组件并自动适应窗口大小 204 txtContent = tkinter.scrolledtext.ScrolledText(app, wrap=tkinter.WORD) 205 txtContent.pack(fill=tkinter.BOTH, expand=tkinter.YES) 206 207 208 def KeyPress(event): 209 textChanged.set(1) 210 211 212 txtContent.bind('<KeyPress>', KeyPress) 213 214 # 开始主循环 215 app.mainloop()
五、Tkinter实战4-简单画图程序
1 # __author__ = "wyb" 2 # date: 2018/5/11 3 4 import tkinter 5 import tkinter.colorchooser 6 import tkinter.simpledialog 7 import tkinter.filedialog 8 from PIL import Image 9 10 app = tkinter.Tk() 11 12 app.title('Paint') 13 app['width'] = 800 14 app['height'] = 600 15 16 # 控制是否允许画图的变量,1:允许,0:不允许 17 yesno = tkinter.IntVar(value=0) 18 # 控制画图类型的变量, 1:曲线, 2:直线,3:矩形, 4:文本,5:橡皮 19 what = tkinter.IntVar(value=1) 20 # 记录鼠标位置的变量 21 X = tkinter.IntVar(value=0) 22 Y = tkinter.IntVar(value=0) 23 # 前景色 24 foreColor = '#000000' 25 backColor = '#FFFFFF' 26 27 # 创建画布 28 image = tkinter.PhotoImage() 29 canvas = tkinter.Canvas(app, bg='white', width=800, height=600) 30 canvas.create_image(800, 600, image=image) 31 32 33 # 单击 允许画图 34 def onLeftButtonDown(event): 35 yesno.set(1) 36 X.set(event.x) 37 Y.set(event.y) 38 if what.get() == 4: 39 # 输出文本 40 canvas.create_text(event.x, event.y, text=text) 41 42 43 canvas.bind('<Button-1>', onLeftButtonDown) 44 45 # 记录最后绘制图形的id 46 lastDraw = 0 47 48 49 # 按住鼠标左键移动,画图 50 def onLeftButtonMove(event): 51 if yesno.get() == 0: 52 return 53 if what.get() == 1: 54 # 使用当前选择的前景色绘制曲线 55 canvas.create_line(X.get(), Y.get(), event.x, event.y, fill=foreColor) 56 X.set(event.x) 57 Y.set(event.y) 58 elif what.get() == 2: 59 # 绘制直线,先删除刚刚画过的直线再画一条新的直线 60 global lastDraw 61 try: 62 canvas.delete(lastDraw) 63 except Exception as e: 64 pass 65 lastDraw = canvas.create_line(X.get(), Y.get(), event.x, event.y, fill=foreColor) 66 elif what.get() == 3: 67 # 绘制矩形,先删除刚刚画过的矩形,再画一个新的矩形 68 # global lastDraw 69 try: 70 canvas.delete(lastDraw) 71 except Exception as e: 72 pass 73 lastDraw = canvas.create_rectangle(X.get(), Y.get(), event.x, event.y, fill=backColor, outline=foreColor) 74 elif what.get() == 5: 75 # 橡皮 使用背景色填充10*10的矩形区域 76 canvas.create_rectangle(event.x-5, event.y-5, event.x+5, event.y+5, outline=backColor, fill=backColor) 77 78 79 canvas.bind('<B1-Motion>', onLeftButtonMove) 80 81 82 # 鼠标左键抬起,不允许画图 83 def onLeftButtonUp(event): 84 if what.get() == 2: 85 # 绘制直线 86 canvas.create_line(X.get(), Y.get(), event.x, event.y, fill=foreColor) 87 elif what.get() == 3: 88 # 绘制矩形 89 canvas.create_rectangle(X.get(), Y.get(), event.x, event.y, fill=backColor, outline=foreColor) 90 yesno.set(0) 91 global lastDraw 92 lastDraw = 0 93 94 95 canvas.bind('<ButtonRelease-1>', onLeftButtonUp) 96 97 98 # 创建菜单 99 menu = tkinter.Menu(app, tearoff=0) 100 101 102 # 打开图像文件 103 def Open(): 104 filename = tkinter.filedialog.askopenfilename(title='Open Image', filetypes=[('image', '*.jpg', '*.png', '*.gif')]) 105 if filename: 106 global image 107 image = tkinter.PhotoImage(file=filename) 108 canvas.create_image(80, 80, image=image) 109 110 111 # 向菜单中添加Open并绑定事件处理函数 112 menu.add_command(lable='Open', command=Open) 113 114 115 # 清除绘制的图形 116 def Clear(): 117 for item in canvas.find_all(): 118 canvas.delete(item) 119 120 121 # 向菜单中添加Clear并绑定事件处理函数 122 menu.add_command(lable='Clear', command=Clear) 123 menu.add_separator() # 添加分割线 124 125 126 # 创建子菜单用来选择绘图类型 127 menuType = tkinter.Menu(menu, tearoff=0) 128 129 130 def drawCurve(): 131 what.set(1) 132 133 134 def drawLine(): 135 what.set(2) 136 137 138 def drawRectangle(): 139 what.set(3) 140 141 142 def drawText(): 143 global text 144 text = tkinter.simpledialog.askstring(title='Input what you want to draw', prompt='') 145 what.set(4) 146 147 148 # 向子菜单中添加Curve并绑定事件处理函数 149 menuType.add_command(lable='Curve', command=drawCurve) 150 # 向子菜单中添加Curve并绑定事件处理函数 151 menuType.add_command(lable='Line', command=drawLine) 152 # 向子菜单中添加Rectangle并绑定事件处理函数 153 menuType.add_command(lable='Rectangle', command=drawRectangle) 154 # 向子菜单中添加Text并绑定事件处理函数 155 menuType.add_command(lable='Text', command=drawText) 156 menuType.add_separator() # 添加分割线 157 158 159 # 选择前景色 160 def chooseForeColor(): 161 global foreColor 162 foreColor = tkinter.colorchooser.askcolor() 163 164 165 # 选择背景色 166 def chooseBackColor(): 167 global backColor 168 backColor = tkinter.colorchooser.askcolor() 169 170 171 menuType.add_command(lable='Choose Foreground Color', command=chooseForeColor) 172 menuType.add_command(lable='Choose Backgound Color', command=chooseBackColor) 173 174 175 # 橡皮 176 def onErase(): 177 what.set(5) 178 179 180 menuType.add_command(label='Erase', command=onErase) 181 menu.add_cascade(label='Type', menu=menuType) 182 183 184 # 鼠标右键抬起,在鼠标位置弹出菜单 185 def onRightButtonUp(event): 186 menu.post(event.x_root, event.y_root) 187 188 189 canvas.bind('<ButtonRelease-3>', onRightButtonUp) 190 canvas.pack(fill=tkinter.BOTH, expand=tkinter.YES) 191 192 app.mainloop()
六、Tkinter实战5-电子时钟
1 import tkinter 2 import threading 3 import datetime 4 import time 5 6 app = tkinter.Tk() 7 app.overrideredirect(True) # 不显示标题栏 8 app.attributes('-alpha', 0.9) # 半透明 9 app.attributes('-topmost', 1) # 总是在顶端 10 app.geometry('110x25+500+200') # 初始大小与位置 11 labelDateTime = tkinter.Label(app) 12 labelDateTime.pack(fill=tkinter.BOTH, expand=tkinter.YES) 13 labelDateTime.configure(bg='gray') 14 X = tkinter.IntVar(value=0) # 记录鼠标左键按下的位置 15 Y = tkinter.IntVar(value=0) 16 canMove = tkinter.IntVar(value=0) # 窗口是否可拖动 17 still = tkinter.IntVar(value=1) # 是否仍在运行 18 19 20 def onLeftButtonDown(event): 21 app.attributes('-alpha', 0.4) # 开始拖动时增加透明度 22 X.set(event.x) # 鼠标左键按下,记录当前位置 23 Y.set(event.y) 24 canMove.set(1) # 并标记窗口可拖动 25 labelDateTime.bind('<Button-1>', onLeftButtonDown) 26 27 28 def onLeftButtonUp(event): 29 app.attributes('-alpha', 0.9) # 停止拖动时恢复透明度 30 31 32 canMove.set(0) # 鼠标左键抬起,标记窗口不可拖动 33 labelDateTime.bind('<ButtonRelease-1>', onLeftButtonUp) 34 35 36 def onLeftButtonMove(event): 37 if canMove.get()==0: 38 return 39 newX = app.winfo_x() + (event.x - X.get()) 40 newY = app.winfo_y() + (event.y - Y.get()) 41 g = '110x25+' + str(newX) + '+' + str(newY) 42 app.geometry(g) # 修改窗口的位置 43 labelDateTime.bind('<B1-Motion>', onLeftButtonMove) 44 45 46 def onRightButtonDown(event): 47 still.set(0) 48 t.join(0.2) 49 app.destroy() # 关闭窗口 50 labelDateTime.bind('<Button-3>', onRightButtonDown) 51 52 53 def nowDateTime(): 54 while still.get() == 1: 55 now = datetime.datetime.now() 56 s = str(now.year) + '-' + str(now.month) + '-' + str(now.day) + ' ' 57 s = s + str(now.hour) + ':' + str(now.minute) + ':' + str(now.second) 58 labelDateTime['text'] = s # 显示当前时间 59 time.sleep(0.2) 60 61 62 t = threading.Thread(target=nowDateTime) 63 t.daemon = True 64 t.start() 65 app.mainloop()
too young too simple sometimes native!