首頁 > 軟體

Python簡單的GUI程式範例詳解

2022-02-13 13:00:31

一、記事本

原始碼

#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()

 執行效果:

總結

本篇文章就到這裡了,希望能夠給你帶來幫助,也希望您能夠多多關注it145.com的更多內容!   


IT145.com E-mail:sddin#qq.com