知識內容:python
1.Tkinter介紹canvas
2.Tkinter實戰1-用戶登陸界面app
3.Tkinter實戰2-選擇類組件綜合應用編輯器
4.Tkinter實戰3-簡單文本編輯器ide
5.Tkinter實戰4-簡單畫圖程序函數
6.Tkinter實戰5-電子時鐘oop
1、Tkinter介紹post
1.tkinter簡單介紹spa
tkinter是python標準庫中專門用來作GUI界面的模塊,能夠使用tkinter開發一些界面code
2.tkinter簡單使用
1 # __author__ = "wyb" 2 # date: 2018/4/29 3 4 import tkinter # 導入tkinter模塊 5 6 root = tkinter.Tk() # 建立主窗口 7 8 root.mainloop() # 進行主循環顯示窗口直達關閉窗口
2、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() # 啓動消息循環
3、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()
4、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()
5、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()
6、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()