python—tkinter编程实战(一)

tkinter编程实战

Python标准库tkinter是对Tcl/Tk的进一步封装,并提供了强大的跨平台图形用户界面(GUI)编程的功能。tkinter库学习手册

tkinter常用组件

组件名称 说明
Button 按钮
Canvas 画布
Checkbutton 复选按钮
Entry 单行文本框
Frame 框架,可作为其他组件的容器
Label 标签
Listbox 列表框
Menu 菜单
Message 多行文本框
Radiobutton 单选按钮
Scrollbar 滚动条
Toplevel 常用来创建窗口

实例1(模拟用户登录)

import tkinter
import tkinter.messagebox
import os
import os.path

path=os.getenv('temp')
filename=os.path.join(path,'info.txt')

root=tkinter.Tk()
root['height']=140
root['width']=200

labelName=tkinter.Label(root,text='User Name:',anchor='e',justify=tkinter.RIGHT,width=80)
labelName.place(x=10,y=5,width=80,height=20)

varName=tkinter.StringVar(root,value='')
entryName=tkinter.Entry(root,width=80,textvariable=varName)

entryName.place(x=100,y=5,width=80,height=20)

labelPwd=tkinter.Label(root,text='User Pwd:',justify=tkinter.RIGHT,anchor='e',width=80)
labelPwd.place(x=10,y=30,width=80,height=20)

varPwd=tkinter.StringVar(root,value='')
entryPwd=tkinter.Entry(root,show='*',width=80,textvariable=varPwd)
entryPwd.place(x=100,y=30,width=80,height=20)

try:
    with open(filename) as fp:
        n,p=fp.read().strip().split(',')
        varName.set(n)
        varPwd.set(p)
except:
    pass

rememberMe=tkinter.IntVar(root,value=1)
checkRemember=tkinter.Checkbutton(root,text='Remember me?',variable=rememberMe,onvalue=1,offvalue=0)
checkRemember.place(x=30,y=70,width=120,height=20)

def login():
    name=entryName.get()
    pwd=entryPwd.get()
    if name=='admin' and pwd=='123456':
        tkinter.messagebox.showinfo(title='恭喜',message='登录成功!')

        if rememberMe.get()==1:
            with open(filename,'w') as fp:
                fp.write(',',''.join((name,pwd)))
        else:
            try:
                os.remove(filename)
            except:
                pass
    else:
        tkinter.messagebox.showerror('警告',message='用户名或密码错误')

buttonOk=tkinter.Button(root,text='Login',command=login)
buttonOk.place(x=30,y=100,width=50,height=20)

def cancel():
    varName.set('')
    varPwd.set('')

buttonCancel=tkinter.Button(root,text='Cancel',command=cancel)
buttonCancel.place(x=90,y=100,width=50,height=20)

root.mainloop()

效果图如下:
python—tkinter编程实战(一)_第1张图片

实例2(选择类组件应用)

import tkinter
import tkinter.messagebox
import tkinter.ttk

root=tkinter.Tk()
root.title('Selection widgets')
root['height']=400
root['width']=320
varName=tkinter.StringVar()
varName.set('')
labelName=tkinter.Label(root,text='Name:',justify=tkinter.RIGHT,width=50)
labelName.place(x=10,y=5,width=50,height=20)
entryName=tkinter.Entry(root,width=120,textvariable=varName)
entryName.place(x=70,y=5,width=120,height=20)

labelGrade=tkinter.Label(root,text='Grade:',justify=tkinter.RIGHT,width=50)
labelGrade.place(x=10,y=40,width=50,height=20)
studentClasses={'1':['1','2','3','4'],
                '2':['1','2'],
                '3':['1','2','3']}
comboGrade=tkinter.ttk.Combobox(root,width=50,value=tuple(studentClasses.keys()))
comboGrade.place(x=70,y=40,width=50,height=20)

def comboChange(event):
    grade=comboGrade.get()
    if grade:
        comboClass["values"]=studentClasses.get(grade)
    else:
        comboClass.set([])

comboGrade.bind('<>',comboChange)

labelClass=tkinter.Label(root,text='Class:',justify=tkinter.RIGHT,width=50)
labelClass.place(x=130,y=40,width=50,height=20)
comboClass=tkinter.ttk.Combobox(root,width=50)
comboClass.place(x=190,y=40,width=50,height=20)

labelSex=tkinter.Label(root,text='Sex:',justify=tkinter.RIGHT,width=50)
labelSex.place(x=10,y=70,width=50,height=20)
sex=tkinter.IntVar()
sex.set(1)
radioMan=tkinter.Radiobutton(root,variable=sex,value=1,text='Man')
radioMan.place(x=70,y=70,width=50,height=20)
radioWoman=tkinter.Radiobutton(root,variable=sex,value=0,text='Woman')
radioWoman.place(x=130,y=70,width=70,height=20)
monitor=tkinter.IntVar()
monitor.set(0)
checkMonitor=tkinter.Checkbutton(root,text='Is Monitor?',variable=monitor,onvalue=1,offvalue=0)
checkMonitor.place(x=20,y=100,width=100,height=20)

def addInformation():
    result='Name:'+entryName.get()
    result=result+';Grade:'+comboGrade.get()
    result=result+';Class:'+comboClass.get()
    result=result+';Sex:'+('Man' if sex.get() else 'Woman')
    result=result+';Monitor:'+('Yes' if monitor.get() else 'No')
    listboxStudents.insert(0,result)
buttonAdd=tkinter.Button(root,text='Add',width=40,command=addInformation)
buttonAdd.place(x=130,y=100,width=40,height=20)

def deleteSelection():
    selection=listboxStudents.curselection()
    if not selection:
        tkinter.messagebox.showinfo(title='Information',message='No Selction')
    else:
        listboxStudents.delete(selection)

buttonDelete=tkinter.Button(root,text='DeleteSelction',width=100,command=deleteSelection)
buttonDelete.place(x=180,y=100,width=100,height=20)

listboxStudents=tkinter.Listbox(root,width=300)
listboxStudents.place(x=100,y=130,width=300,height=200)

root.mainloop()

效果如如下:
python—tkinter编程实战(一)_第2张图片
实例3(简单画图程序)

import os
import tkinter
import tkinter.simpledialog
import tkinter.colorchooser
import tkinter.filedialog
from PIL import ImageGrab

root=tkinter.Tk()
root.title('My Paint')
root['width']=800
root['height']=600

canDraw=tkinter.IntVar(value=0)
what=tkinter.IntVar(value=1)
X=tkinter.IntVar(value=0)
Y=tkinter.IntVar(value=0)

foreColor='#000000'
backColor='#FFFFFF'
image=tkinter.PhotoImage()
canvas=tkinter.Canvas(root,bg='white',width=800,height=600)
canvas.create_image(800,600,image=image)

def onLeftButtonDown(event):
    canDraw.set(1)
    X.set(event.x)
    Y.set(event.y)
    if what.get()==4:
        canvas.create_text(event.x,event.y,text=text)
canvas.bind('',onLeftButtonDown)
lastDraw=0
def onLeftButtonMove(event):
    global lastDraw
    if canDraw.get()==0:
        return
    if what.get()==1:
        canvas.create_line(X.get(),Y.get(),event.x,event.y,fill=foreColor)
        X.set(event.x)
        Y.set(event.y)
    elif what.get()==2:
        try:
            canvas.delete(lastDraw)
        except Exception as e:
            pass
        lastDraw=canvas.create_line(X.get(),Y.get(),event.x,event.y,fill=foreColor)
    elif what.get()==3:
        try:
            canvas.delete(lastDraw)
        except Exception as e:
            pass
        lastDraw=canvas.create_rectangle(X.get(),Y.get(),event.x,event.y,fill=backColor,outline=foreColor)
    elif what.get()==5:
        canvas.create_rectangle(event.x-5,event.y-5,event.x+5,event.y+5,outline=backColor,fill=backColor)

canvas.bind('',onLeftButtonMove)

def onLeftButtonUp(event):
    if what.get()==2:
        canvas.create_line(X.get(),Y.get(),event.x,event.y,fill=foreColor)
    elif what.get()==3:
        canvas.create_rectangle(X.get(),Y.get(),event.x,event.y,fill=backColor,outline=foreColor)
    canDraw.set(0)
    global lastDraw
    lastDraw=0
canvas.bind('',onLeftButtonUp)
menu=tkinter.Menu(root,tearoff=0)
def Open():
    filename=tkinter.filedialog.askopenfilename(title='Open Image',filetypes=[('image','*.jpg *.png *.gif')])
    if filename:
        global image
        image=tkinter.PhotoImage(file=filename)
        canvas.create_image(80,80,image=image)
menu.add_command(label='Open',command=Open)

def Save():
    left=int(root.winfo_rootx())
    top=input(root.winfo_rooty())
    width=root.winfo_width()
    height=root.winfo_height()
    im=ImageGrab.grab((left,top,left+width,top+height))

    filename=tkinter.filedialog.asksaveasfilename(title='保存图片',filetypes=[('图片文件','*.png')])
    if not filename:
        return
    if not filename.endswith('.png'):
        filename=filename+'.png'
    im.save(filename)
menu.add_command(label='Save',command=Save)

def Clear():
    for item in canvas.find_all():
        canvas.delete(item)

menu.add_command(label='Clear',command=Clear)
menu.add_separator()
menuType=tkinter.Menu(menu,tearoff=0)
def drawCurve():
    what.set(1)
menuType.add_command(label='Curve',command=drawCurve)
def drawLine():
    what.set(2)
menuType.add_command(label='Line',command=drawLine)
def drawRectangle():
    what.set(3)
menuType.add_command(label='Rectangle',command=drawRectangle)
def drawText():
    global text
    text=tkinter.simpledialog.askstring(title='Input what you want to draw',prompt='')
    what.set(4)
menuType.add_command(label='Text',command=drawText)
menuType.add_separator()

def chooseForeColor():
    global foreColor
    foreColor=tkinter.colorchooser.askcolor()[1]
menuType.add_command(label='Choose Foreground Color',command=chooseForeColor)
def chooseBackColor():
    global backColor
    backColor=tkinter.colorchooser.askcolor()[1]
menuType.add_command(label='Choose Background Color',command=chooseBackColor)

def onErase():
    what.set(5)
menuType.add_command(label='Erase',command=onErase)

menu.add_cascade(label='Type',menu=menuType)
def onRightButtonUp(event):
    menu.post(event.x_root,event.y_root)
canvas.bind('',onRightButtonUp)
canvas.pack(fill=tkinter.BOTH,expand=tkinter.YES)

root.mainloop()

效果图如下:
python—tkinter编程实战(一)_第3张图片
实例4(电子时钟)

import tkinter
import threading
import datetime
import time

app=tkinter.Tk()
app.overrideredirect(True)
app.attributes('-alpha',0.9)
app.attributes('-topmost',1)
app.geometry('110x25+100+100')
lableDateTime=tkinter.Label(app)
lableDateTime.pack(fill=tkinter.BOTH,expand=tkinter.YES)
lableDateTime.configure(bg='gray')
X=tkinter.IntVar(value=0)
Y=tkinter.IntVar(value=0)
canMove=tkinter.IntVar(value=0)
still=tkinter.IntVar(value=1)

def onLeftButtonDown(event):
    app.attributes('-alpha',0.4)
    X.set(event.x)
    Y.set(event.y)
    canMove.set(1)

lableDateTime.bind('',onLeftButtonDown)

def onLeftButtonUp(event):
    app.attributes('-alpha',0.9)
    canMove.set(0)

lableDateTime.bind('',onLeftButtonUp)

def onLeftButtonMove(event):
    if canMove.get()==0:
        return
    newX=app.winfo_x()+(event.x-X.get())
    newY=app.winfo_y()+(event.y-Y.get())
    g='110x25'+str(newX)+'+'+str(newY)
    app.geometry(g)
lableDateTime.bind('',onLeftButtonMove)

def onRightButtonDown(event):
    still.set(0)
    t.join(0.2)
    app.destroy()

lableDateTime.bind('',onRightButtonDown)

def nowDateTime():
    while still.get()==1:
        now=datetime.datetime.now()
        s=str(now.year)+'-'+str(now.month)+\
            '-'+str(now.day)+' '
        s=s+str(now.hour)+':'+str(now.minute)+\
            ':'+str(now.second)
        lableDateTime['text']=s
        time.sleep(0.5)

t=threading.Thread(target=nowDateTime)
t.daemon=True
t.start()

app.mainloop()

实例5(屏幕颜色选择器)

import tkinter
import tkinter.filedialog
import tkinter.messagebox
import os
from PIL import ImageGrab,Image
from time import sleep

root=tkinter.Tk()
root.geometry('100x40+400+300')
root.resizable(False,False)

class MyCapture:
    def __init__(self,png):
        self.X=tkinter.IntVar(value=0)
        self.Y=tkinter.IntVar(value=0)
        screenWidth=root.winfo_screenwidth()
        screenHeight=root.winfo_screenheight()
        self.top=tkinter.Toplevel(root,width=screenWidth,height=screenHeight)
        self.top.overrideredirect(True)
        self.canvas=tkinter.Canvas(self.top,bg='white',width=screenWidth,height=screenHeight)
        self.image=tkinter.PhotoImage(file=png)
        self.canvas.create_image(screenWidth//2,screenHeight//2,image=self.image)

        def onLeftButtonUp(event):
            im=Image.open(png)
            color=im.getpixel((event.x,event.y))[:3]
            msg=str(color)+'\n'
            color="#"+''.join(map(lambda x:hex(x)[2:],color))
            msg+=color
            tkinter.messagebox.showinfo('',msg)
            self.top.destroy()
        self.canvas.bind(',onLeftButtonUp)
        self.canvas.pack(fill=tkinter.BOTH,expand=tkinter.YES)

def buttonCaptureClick():
    root.state('icon')
    sleep(0.2)
    filename='temp.png'
    im=ImageGrab.grab()
    im.save(filename)
    im.close()
    w=MyCapture(filename)
    buttonCapture.wait_window(w.top)
    root.state('normal')
    os.remove(filename)
buttonCapture=tkinter.Button(root,text='取色',command=buttonCaptureClick)
buttonCapture.place(x=10,y=10,width=80,height=20)

root.mainloop()

你可能感兴趣的:(Python)