Python簡單的GUI程序示例詳解
一、記事本
源碼
#python簡易記事本 from tkinter import * from tkinter import messagebox from tkinter import filedialog import os filename='' #文件名,全局變量 def about(): messagebox.showinfo('提示','這是一個消息框') def openFile(): global filename #使用全局變量 filename=filedialog.askopenfilename(defaultextension='.txt') #打開文件,默認擴展名是xtxt if filename=='': #如果沒有選擇 filename=None else: root.title('FileName:'+os.path.basename(filename)) #將文件名顯示在標題欄中 textPad.delete(1.0,END) #刪除文本框中原有內容 f=open(filename,'r',encoding='UTF-8') #獲取文件中內容 textPad.insert(1.0,f.read()) #顯示到文本框 f.close() def saveOtherFile(): global filename f=filedialog.asksaveasfilename(initialfile='未命名.txt',defaultextension='.txt') #保存文件 filename=f root.title('FileName:' + os.path.basename(filename)) fh=open(f,'w',encoding='UTF-8') #隻寫方式打開文件 msg=textPad.get(1.0,END) #從文本框中獲取內容 fh.write(msg) fh.close() root=Tk() #設置菜單欄 root.title('記事本') root.geometry('500x500+100+100') #widthxheight+x+y menubar=Menu(root) root.config(menu=menubar) filemenu=Menu(menubar) #第一個菜單欄 filemenu.add_command(label='打開',accelerator='Ctrl+N',command=openFile) filemenu.add_command(label='保存',accelerator='Ctrl+T',command=saveOtherFile) menubar.add_cascade(label='文件',menu=filemenu) aboutmenu=Menu(menubar) aboutmenu.add_command(label='關於',accelerator='Ctrl+Y',command=about) menubar.add_cascade(label='幫助',menu=aboutmenu) status=Label(root,text='Ln20',bd=1,relief=SUNKEN,anchor=W) #底部狀態欄 status.pack(side=BOTTOM,fill=X) lnlabel=Label(root,width=2,bg='antique white') #左邊邊界欄 lnlabel.pack(side=LEFT,fill=Y) textPad=Text(root,undo=True) #設置文本框 textPad.pack(expand=YES,fill=BOTH) scroll=Scrollbar(textPad) #右邊進度條欄 textPad.config(yscrollcommand=scroll.set) scroll.config(command=textPad.yview) scroll.pack(side=RIGHT,fill=Y) root.mainloop()#python簡易記事本 from tkinter import * from tkinter import messagebox from tkinter import filedialog import os filename='' #文件名,全局變量 def about(): messagebox.showinfo('提示','這是一個消息框') def openFile(): global filename #使用全局變量 filename=filedialog.askopenfilename(defaultextension='.txt') #打開文件,默認擴展名是xtxt if filename=='': #如果沒有選擇 filename=None else: root.title('FileName:'+os.path.basename(filename)) #將文件名顯示在標題欄中 textPad.delete(1.0,END) #刪除文本框中原有內容 f=open(filename,'r',encoding='UTF-8') #獲取文件中內容 textPad.insert(1.0,f.read()) #顯示到文本框 f.close() def saveOtherFile(): global filename f=filedialog.asksaveasfilename(initialfile='未命名.txt',defaultextension='.txt') #保存文件 filename=f root.title('FileName:' + os.path.basename(filename)) fh=open(f,'w',encoding='UTF-8') #隻寫方式打開文件 msg=textPad.get(1.0,END) #從文本框中獲取內容 fh.write(msg) fh.close() root=Tk() #設置菜單欄 root.title('記事本') root.geometry('500x500+100+100') #widthxheight+x+y menubar=Menu(root) root.config(menu=menubar) filemenu=Menu(menubar) #第一個菜單欄 filemenu.add_command(label='打開',accelerator='Ctrl+N',command=openFile) filemenu.add_command(label='保存',accelerator='Ctrl+T',command=saveOtherFile) menubar.add_cascade(label='文件',menu=filemenu) aboutmenu=Menu(menubar) aboutmenu.add_command(label='關於',accelerator='Ctrl+Y',command=about) menubar.add_cascade(label='幫助',menu=aboutmenu) status=Label(root,text='Ln20',bd=1,relief=SUNKEN,anchor=W) #底部狀態欄 status.pack(side=BOTTOM,fill=X) lnlabel=Label(root,width=2,bg='antique white') #左邊邊界欄 lnlabel.pack(side=LEFT,fill=Y) textPad=Text(root,undo=True) #設置文本框 textPad.pack(expand=YES,fill=BOTH) scroll=Scrollbar(textPad) #右邊進度條欄 textPad.config(yscrollcommand=scroll.set) scroll.config(command=textPad.yview) scroll.pack(side=RIGHT,fill=Y) root.mainloop()
運行效果:
二、簡單畫圖
# 畫圖程序 import os import tkinter import tkinter.simpledialog import tkinter.colorchooser import tkinter.filedialog from PIL import Image from PIL import ImageGrab def openItem(): global img filename=tkinter.filedialog.askopenfilename(title="Open",filetypes=[('Image','*.png *.gif')]) if filename: img=tkinter.PhotoImage(file=filename) canvas.create_image(400,300,image=img) def saveItem(): saveX=int(root.winfo_rootx()) saveY=int(root.winfo_rooty()) saveW=root.winfo_width() saveH=root.winfo_height() im=ImageGrab.grab((saveX,saveY,saveX+saveW,saveY+saveH)) filename=tkinter.filedialog.asksaveasfilename(title='Save',filetypes=[('Image','*.png *.gif')]) if not filename: return try: if filename[filename.index('.'):] in ['.png','.gif']==False: filename+='.png' except: filename+='.png' im.save(filename) def clearItem(): for i in canvas.find_all(): canvas.delete(i) def curveType(): penType.set(1) def lineType(): penType.set(2) def rectangleType(): penType.set(3) def textType(): global userText userText=tkinter.simpledialog.askstring(title="Please input your words", prompt='') penType.set(4) def eraseType(): penType.set(5) def chooseForeColor(): global foreColor foreColor=tkinter.colorchooser.askcolor()[1] def chooseBackColor(): global backColor backColor=tkinter.colorchooser.askcolor()[1] def onClickLeft(event): global userText canDraw.set(1) X.set(event.x) Y.set(event.y) if penType.get()==4: canvas.create_text(event.x,event.y,text=userText) def onMoveLeft(event): global lastPaint,foreColor,backColor if canDraw.get()==0: return if penType.get()==1: #繪制曲線 canvas.create_line(X.get(),Y.get(),event.x,event.y,fill=foreColor) X.set(event.x) Y.set(event.y) elif penType.get()==2: #繪制直線(預覽) try: canvas.delete(lastPaint) except: pass lastPaint=canvas.create_line(X.get(),Y.get(),event.x,event.y,fill=foreColor) elif penType.get()==3: #繪制矩形(預覽) try: canvas.delete(lastPaint) except: pass lastPaint=canvas.create_rectangle(X.get(),Y.get(),event.x,event.y,fill=backColor,outline=foreColor) elif penType.get()==5: #橡皮擦 canvas.create_rectangle(event.x-5,event.y-5,event.x+5,event.y+5,fill=backColor,outline=backColor) def onReleaseLeft(event): global lastPaint,foreColor,backColor lastPaint=0 if penType.get()==2: #抬起左鍵畫直線 canvas.create_line(X.get(),Y.get(),event.x,event.y,fill=foreColor) elif penType.get()==3: #抬起左鍵就畫矩形 canvas.create_rectangle(X.get(),Y.get(),event.x,event.y,fill=backColor,outline=foreColor) canDraw.set(0) def onReleaseRight(event): menu.post(event.x_root, event.y_root) root=tkinter.Tk() root.title("Paint") root.geometry("800x600+280+50") lastPaint=0 userText="" foreColor='black' backColor='white' X=tkinter.IntVar(value=0) Y=tkinter.IntVar(value=0) canDraw=tkinter.IntVar(value=0) #能否畫圖,1:能,0:不能 penType=tkinter.IntVar(value=1) #畫筆類型,1:曲線,2:直線,3:矩形,4:文本,5:橡皮擦 menu=tkinter.Menu(root,tearoff=0) subMenu=tkinter.Menu(menu,tearoff=0) img=tkinter.PhotoImage() canvas=tkinter.Canvas(root,bg='white',width=800,height=600) canvas.create_image(800,600,image=img) menu.add_command(label='Open',command=openItem) menu.add_command(label='Save as',command=saveItem) menu.add_separator() subMenu.add_command(label='Curve',command=curveType) subMenu.add_command(label='Line',command=lineType) subMenu.add_command(label='Rectangle',command=rectangleType) subMenu.add_command(label='Text',command=textType) subMenu.add_command(label='Erase',command=eraseType) menu.add_cascade(label='Pen Type',menu=subMenu) menu.add_separator() menu.add_command(label='Foreground Color',command=chooseForeColor) menu.add_command(label='Bakckground Color',command=chooseBackColor) menu.add_separator() menu.add_command(label='Clear',command=clearItem) canvas.bind('<Button-1>', onClickLeft) canvas.bind('<B1-Motion>',onMoveLeft) canvas.bind('<ButtonRelease-1>',onReleaseLeft) canvas.bind('<ButtonRelease-3>',onReleaseRight) canvas.pack(fill=tkinter.BOTH,expand=tkinter.YES) root.mainloop()
運行效果:
總結
本篇文章就到這裡瞭,希望能夠給你帶來幫助,也希望您能夠多多關註WalkonNet的更多內容!
推薦閱讀:
- python實現記事本功能
- 教你用python實現一個加密的文字處理器
- python TKinter彈出式菜單的實例方法
- Python GUI 圖形用戶界面
- Python中的tkinter庫簡單案例詳解