[PYTHON] 核心编程笔记(19.图形用户界面编程)

19.1 简介


19.1.1 什么是Tcl,Tk和Tkinter?


19.1.2 安装和使用Tkinter


# apt-get install python-tk -y


# python

-------------------------------

Python 2.7.3 (default, Sep 26 2012, 21:51:14)

[GCC 4.7.2] on linux2

Type "help", "copyright", "credits" or "license" for more information.

>>> import Tkinter

>>>

--------------------------------


19.2 Tkinter与Python编程


19.2.1 Tkinter模块:把Tk引入您的程序

1.导入Tkinter模块(import Tkinter,或者,from Tkinter import *)

2.创建一个顶层窗口对象,来容纳您的整个GUI程序

3.在您顶层窗口对象上或其中创建所有的GUI模块(以及功能)

4.把这些GUI模块与地层程序代码相连接

5.进入主事件循环


第一步很明显,所有使用Tkinter的GUI程序必须先导入Tkinter模块,第一步就是为


了获得Tkinter的访问权


19.2.2 GUI程序开发简介


19.2.3 顶层窗口:Tkinter.Tk()


>>> import Tkinter

>>> top = Tkinter.Tk()


19.2.4 Tk组件


例,标签组件演示(tkhello1.py)

# vi tkhello1.py

----------------------------

#!/usr/bin/env python


import Tkinter


top = Tkinter.Tk()

label = Tkinter.Label(top, text = 'Hello World!')

label.pack()

Tkinter.mainloop()

----------------------------


19.3 Tkiner 举例


19.3.1 标签组件


19.3.2 按钮组件


例,按钮组件演示

# vi tkhello2.py

------------------------------

#!/usr/bin/env python


import Tkinter


top = Tkinter.Tk()

quit = Tkinter.Button(top, text = 'Hello World!', command = top.quit)

quit.pack()

Tkinter.mainloop()

------------------------------


19.3.3 标签和按钮组件


例,标签和按钮组件演示

# vi tkhello3.py

------------------------------

#!/usr/bin/env python


import Tkinter


top = Tkinter.Tk()

hello = Tkinter.Label(top, text='Hello World!')

hello.pack()


quit = Tkinter.Button(top, text='QUIT',

     command=top.quit, bg='red',fg='white')

quit.pack(fill=Tkinter.X, expand=1)

Tkinter.mainloop()

------------------------------


19.3.4 标签,按钮和进度条组件


例,标签,按钮和进度条组件演示


我们最后一个组件例子介绍进度条组件,重点放在组件间通过回调函数的交互[诸


如resize()],您对进度条组件的动作将影响标签组件上的文字


# vi tkhello4.py

------------------------------------

#!/usr/bin/env python


from Tkinter import *


def resize(ev=None):

   label.config(font='Helvetica -%d bold' % \

       scale.get())


top = Tk()

top.geometry('250x150')


label = Label(top, text='Hello World!',

   font='Helvetica -12 bold')

label.pack(fill=Y, expand=1)


scale = Scale(top, from_=10, to=40,

   orient=HORIZONTAL, command=resize)

scale.set(12)

scale.pack(fill=X, expand=1)


quit = Button(top, text='QUIT',

   command=top.quit, activeforeground='white',

   activebackground='red')

quit.pack()


mainloop()


------------------------------------


19.3.5 偏函数应用举例


例,运用PFA的路灯指示牌GUI程序

# vi pfaGUI2.py

--------------------------------------

#!/usr/bin/env python


from functools import partial as pto

from Tkinter import Tk, Button, X

from tkMessageBox import showinfo, showwarning, showerror


WARN = 'warn'

CRIT = 'crit'

REGU = 'regu'


SIGNS = {

   'do not enter': CRIT,

   'railroad crossing': WARN,

   '55\nspeed limit': REGU,

   'wrong way': CRIT,

   'merging traffic': WARN,

   'one way': REGU,

}


critCB = lambda : showerror('Error', 'Error Button Pressed!')

warnCB = lambda : showwarning('Warning',

   'Warning Button Pressed!')

infoCB = lambda : showinfo('Info', 'Info Button Pressed!')


top = Tk()  

top.title('Road Signs')

Button(top, text='QUIT', command=top.quit,

   bg='red', fg='white').pack()


MyButton = pto(Button, top)

CritButton = pto(MyButton, command=critCB, bg='white', fg='red')

WarnButton = pto(MyButton, command=warnCB, bg='goldenrod1')

ReguButton = pto(MyButton, command=infoCB, bg='white')


for eachSign in SIGNS:

   signType = SIGNS[eachSign]

   cmd = '%sButton(text=%r%s).pack(fill=X, expand=True)' % (

       signType.title(), eachSign,

       '.upper()' if signType == CRIT else '.title()')

   eval(cmd)


top.mainloop()

--------------------------------------


19.3.6 中级Tkinter范例


例,文件遍历系统(listdir.py)


这个稍高级一些的GUI程序扩大的组件的使用范围,演员名单新增了列表框,文本框


,和滚动条,而且还有大量的回调函数,例如鼠标点击,键盘输入,和滚动条操作


# vi listdir.py

----------------------------------------

#!/usr/bin/env python


import os

from time import sleep

from Tkinter import *


class DirList:


   def __init__(self, initdir=None):

       self.top = Tk()

       self.label = Label(self.top, \

           text='Directory Lister' + ' v1.1')

       self.label.pack()


       self.cwd=StringVar(self.top)


       self.dirl = Label(self.top, fg='blue',

           font=('Helvetica', 12, 'bold'))

       self.dirl.pack()


       self.dirfm = Frame(self.top)

       self.dirsb = Scrollbar(self.dirfm)

       self.dirsb.pack(side=RIGHT, fill=Y)

       self.dirs = Listbox(self.dirfm, height=15, \

           width=50, yscrollcommand=self.dirsb.set)

       self.dirs.bind('<Double-1>', self.setdirandgo)

       self.dirsb.config(command=self.dirs.yview)

       self.dirs.pack(side=LEFT, fill=BOTH)

       self.dirfm.pack()


       self.dirn = Entry(self.top, width=50, \

           textvariable=self.cwd)

       self.dirn.bind('<Return>', self.dols)

       self.dirn.pack()


       self.bfm = Frame(self.top)

       self.clr = Button(self.bfm, text='Clear', \

           command=self.clrdir, \

           activeforeground='white', \

           activebackground='blue')

       self.ls = Button(self.bfm, \

           text='List Directory', \

           command=self.dols, \

           activeforeground='white', \

           activebackground='green')

       self.quit = Button(self.bfm, text='Quit', \

           command=self.top.quit, \

           activeforeground='white', \

           activebackground='red')

       self.clr.pack(side=LEFT)

       self.ls.pack(side=LEFT)

       self.quit.pack(side=LEFT)

       self.bfm.pack()


       if initdir:

           self.cwd.set(os.curdir)

           self.dols()


   def clrdir(self, ev=None):

       self.cwd.set('')


   def setdirandgo(self, ev=None):

       self.last = self.cwd.get()

       self.dirs.config(selectbackground='red')

       check = self.dirs.get(self.dirs.curselection())

       if not check:

           check = os.curdir

       self.cwd.set(check)

       self.dols()


   def dols(self, ev=None):

       error = ''

       tdir = self.cwd.get()

       if not tdir: tdir = os.curdir


       if not os.path.exists(tdir):

           error = tdir + ': no such file'

       elif not os.path.isdir(tdir):

           error = tdir + ': not a directory'


       if error:

           self.cwd.set(error)

           self.top.update()

           sleep(2)

           if not (hasattr(self, 'last') \

and self.last):

   self.last = os.curdir

           self.cwd.set(self.last)

           self.dirs.config( \

selectbackground='LightSkyBlue')

           self.top.update()

           return


       self.cwd.set( \

   'FETCHING DIRECTORY CONTENTS...')

       self.top.update()

       dirlist = os.listdir(tdir)

       dirlist.sort()

       os.chdir(tdir)

       self.dirl.config(text=os.getcwd())

       self.dirs.delete(0, END)

       self.dirs.insert(END, os.curdir)

       self.dirs.insert(END, os.pardir)

       for eachFile in dirlist:

           self.dirs.insert(END, eachFile)

       self.cwd.set(os.curdir)

       self.dirs.config( \

   selectbackground='LightSkyBlue')


def main():

   d = DirList(os.curdir)

   mainloop()


if __name__ == '__main__':

   main()

----------------------------------------


19.4 其他GUI简介


19.4.1 Tk interface eXtensions(Tix)


# apt-get install tix -y

# vi animalTix.pyw

-------------------------------------------

#!/usr/bin/env python


from Tkinter import Label, Button, END

from Tix import Tk, Control, ComboBox


top = Tk()

top.tk.eval('package require Tix')


lb = Label(top,

   text='Animals (in pairs; min: pair, max: dozen)')

lb.pack()


ct = Control(top, label='Number:',

   integer=True, max=12, min=2, value=2, step=2)

ct.label.config(font='Helvetica -14 bold')

ct.pack()


cb = ComboBox(top, label='Type:', editable=True)

for animal in ('dog', 'cat', 'hamster', 'python'):

   cb.insert(END, animal)

cb.pack()


qb = Button(top, text='QUIT',

   command=top.quit, bg='red', fg='white')

qb.pack()


top.mainloop()


-------------------------------------------


19.4.2 Python MegaWidgets(PMW)


19.4.3 wxWidgets和wxPython


Pmw GUI程序演示

# apt-get install python-pmw -y

# vi animalPmw.pyw

----------------------------------

#!/usr/bin/env python


from Tkinter import Button, END, Label, W

from Pmw import initialise, ComboBox, Counter


top = initialise()


lb = Label(top,

   text='Animals (in pairs; min: pair, max: dozen)')

lb.pack()


ct = Counter(top, labelpos=W, label_text='Number:',

   datatype='integer', entryfield_value=2,

   increment=2, entryfield_validate={'validator':

   'integer', 'min': 2, 'max': 12})

ct.pack()


cb = ComboBox(top, labelpos=W, label_text='Type:')

for animal in ('dog', 'cat', 'hamster', 'python'):

   cb.insert(END, animal)

cb.pack()


qb = Button(top, text='QUIT',

   command=top.quit, bg='red', fg='white')

qb.pack()


top.mainloop()


----------------------------------


wxPython GUI程序演示


# vi animalWx.pyw

-----------------------------------

#!/usr/bin/env python


from Tkinter import Button, END, Label, W

from Pmw import initialise, ComboBox, Counter


top = initialise()


lb = Label(top,

   text='Animals (in pairs; min: pair, max: dozen)')

lb.pack()


ct = Counter(top, labelpos=W, label_text='Number:',

   datatype='integer', entryfield_value=2,

   increment=2, entryfield_validate={'validator':

   'integer', 'min': 2, 'max': 12})

ct.pack()


cb = ComboBox(top, labelpos=W, label_text='Type:')

for animal in ('dog', 'cat', 'hamster', 'python'):

   cb.insert(END, animal)

cb.pack()


qb = Button(top, text='QUIT',

   command=top.quit, bg='red', fg='white')

qb.pack()


top.mainloop()


-----------------------------------


19.4.4 GTK+ 和 PyGTK


PyGTk GUI 程序演示(animalGtk.pyw)

# vi animalGtk.pyw

--------------------------------------

#!/usr/bin/env python


import pygtk

pygtk.require('2.0')

import gtk

import pango


class GTKapp(object):

   def __init__(self):

   top = gtk.Window(gtk.WINDOW_TOPLEVEL)

   top.connect("delete_event", gtk.main_quit)

   top.connect("destroy", gtk.main_quit)

   box = gtk.VBox(False, 0)

   lb = gtk.Label(

       'Animals (in pairs; min: pair, max: dozen)')

   box.pack_start(lb)


   sb = gtk.HBox(False, 0)

   adj = gtk.Adjustment(2, 2, 12, 2, 4, 0)

   sl = gtk.Label('Number:')

   sl.modify_font(

       pango.FontDescription("Arial Bold 10"))

   sb.pack_start(sl)

   ct = gtk.SpinButton(adj, 0, 0)

   sb.pack_start(ct)

   box.pack_start(sb)


   cb = gtk.HBox(False, 0)

   c2 = gtk.Label('Type:')

   cb.pack_start(c2)

   ce = gtk.combo_box_entry_new_text()

   for animal in ('dog', 'cat', 'hamster', 'python'):

       ce.append_text(animal)

   cb.pack_start(ce)

   box.pack_start(cb)


   qb = gtk.Button("")

   red = gtk.gdk.color_parse('red')

   sty = qb.get_style()

   for st in (gtk.STATE_NORMAL,

       gtk.STATE_PRELIGHT, gtk.STATE_ACTIVE):

       sty.bg[st] = red

   qb.set_style(sty)

   ql = qb.child

   ql.set_markup('<span color="white">QUIT</span>')

   qb.connect_object("clicked",

       gtk.Widget.destroy, top)

   box.pack_start(qb)

   top.add(box)

   top.show_all()


if __name__ == '__main__':

   animal = GTKapp()

   gtk.main()


--------------------------------------


19.5 相关模块和其他GUI

GUI 模块或系统描述

TkinterTK INTERface:     Python的默认GUI工具集

PmwPython                MegaWidgets(Tkinter扩展)

TixTk                    Interface eXtension(Tk 扩展)

TkZinc(Zinc)             Extended Tk Canvas type(Tk 扩展)

EasyGUI(easygui)         非常简单的非事件驱动GUI(Tk 扩展)

TIDE+(IDE Studio)        Tix集成开发环境


wxWidgets相关模块

wxPython                Python对wxWidgets的绑定,一个跨平台的GUI框架库(早期称为wxWindows)

Boa                     ConstructorPython集成开发环境兼wxPython GUI构造工具

PythonCard              基于wxPython的GUI桌面应用程序工具集

wxGlade                 另一个wxPython GUI设计工具


商业软件

win32ui                Python版的Microsoft MFC

swing                  Python版的Sun Microsystems Java/swing(基于Jython)


你可能感兴趣的:(Web,python,核心编程)