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

运行效果:

Python简单的GUI程序示例详解_第1张图片

二、简单画图

# 画图程序
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('', onClickLeft)
canvas.bind('',onMoveLeft)
canvas.bind('',onReleaseLeft)
canvas.bind('',onReleaseRight)
canvas.pack(fill=tkinter.BOTH,expand=tkinter.YES)
root.mainloop()

 运行效果:

Python简单的GUI程序示例详解_第2张图片

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注脚本之家的更多内容!   

你可能感兴趣的:(Python简单的GUI程序示例详解)