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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章