Python之Tkinter:動作
進行界面程式設計,首先少不了以下幾個重要部分:
l 窗體
l 控件
l 動作
窗體是容器,各式各樣的控件放置在容器中,每種控件在觸發之後都會執行一定的指令,即完成它的動作。
怎樣将控件綁定到一個指令上?一般來說在建立控件的時候,使用參數command來指定要執行的動作,這個動作可以使以下幾類情況:
l 普通函數
l 同屬于一個類的其他成員函數
l 内置函數
l lamda函數
怎樣建立視窗?一般來說有這麼幾種方法,一種是過程式的,使用Tk()。還有一種是面向對象式的,即:繼承自Frame. Tk()傳回的對象是根容器,Frame産生的對象可以放置在Tk()傳回的對象中。
每個視窗在建立之後,使用pack對自己進行布局,并使自己可見。布局的方式可以使用expand、fill、side等。
控件對事件的綁定調用函數bind,第一個參數為表示事件的字元串,第二個為要執行的動作,動作的來源前面已經叙述。
下面為一些例子:
#!/usr/bin/python
from Tkinter import *
def quit():
print "I have to leave now ..."
import sys
sys.exit()
b = Button(None,text="quit",bg="red",command=quit)
b.pack()
b.mainloop()
建立一個Button,點選後執行的動作為退出。
class ClassCall():
def __init__(self):
self.msg="call from a class.\n"
def __call__(self):
print self.msg
import sys
sys.exit()
widget = Button(None,text="test",command=ClassCall())
widget.pack()
widget.mainloop()
将一個類的執行個體指定為動作,預設時調用該類的__call__方法。
class InnerClass():
self.b = Button(None,text="test",command = self.call)
self.b.pack()
def call(self):
print "I am leaving now..."
InnerClass()
mainloop()
調用同一個類内部的成員函數
class GuiDesign():
def __init__(self,parent=None):
self.top = Frame(parent)
self.top.pack()
self.data = 0
self.layout()
def layout(self):
Button(self.top,text="exit",command=self.top.quit).pack(side = LEFT)
Button(self.top,text="hi",command=self.hi).pack(side = RIGHT)
def hi(self):
self.data += 1
print "hi:%d" % self.data
frm = Frame()
frm.pack() #easy to make mistake here.
Label(frm,text="hello").pack(side=TOP)
GuiDesign(frm).top.mainloop()
将Frame對象作為參數使用
def showPosEvent(event):
print 'Widget=%s X=%s Y=%s' % (event.widget, event.x, event.y)
print 'Got key perss:',event.char
tkroot = Tk()
labelfont = ('courier', 20, 'bold')
widget = Label(tkroot, text='Hello bind world')
widget.config(bg='red', font=labelfont)
widget.config(height=5, width=20)
widget.pack(expand=YES, fill=BOTH)
widget.bind('<KeyPress>', showPosEvent)
widget.focus()
tkroot.title('Click Me')
tkroot.mainloop()
響應按鍵事件,以及動态配置控件的方式
本文轉自hipercomer 51CTO部落格,原文連結:http://blog.51cto.com/hipercomer/865342