標籤:tkinter python
from Tkinter import *class Application(Frame): def say_hi(self): print ‘hello‘ def createWiegets(self): self.QUIT = Button(self) self.QUIT["text"] = "QUIT" self.QUIT["fg"] = "red" self.QUIT["command"] = self.quit self.QUIT.pack({"side":"left"}) self.hi_there = Button(self) self.hi_there["text"] = "hello" self.hi_there["command"] = self.say_hi self.hi_there.pack({"side":"left"}) def __init__(self,master=None): Frame.__init__(self,master) self.pack() self.createWiegets()root = Tk()app = Application(master = root)app.mainloop()root.destroy()
這段代碼說明了如何使用Python來建立一個圖形介面。使用的是python中的Tkinter這個圖形介面庫。
- 匯入相應的模組:
from Tkinter import *
- 定義一個類,繼承Frame
class Application(Frame): def say_hi(self): print ‘hello‘ def createWiegets(self): self.QUIT = Button(self) self.QUIT["text"] = "QUIT" self.QUIT["fg"] = "red" self.QUIT["command"] = self.quit self.QUIT.pack({"side":"left"}) self.hi_there = Button(self) self.hi_there["text"] = "hello" self.hi_there["command"] = self.say_hi self.hi_there.pack({"side":"left"}) def __init__(self,master=None): Frame.__init__(self,master) self.pack() self.createWiegets()
def createWiegets(self): self.QUIT = Button(self) self.QUIT["text"] = "QUIT" self.QUIT["fg"] = "red" self.QUIT["command"] = self.quit self.QUIT.pack({"side":"left"}) self.hi_there = Button(self) self.hi_there["text"] = "hello" self.hi_there["command"] = self.say_hi self.hi_there.pack({"side":"left"})
root = Tk()app = Application(master = root)app.mainloop()root.destroy()
在上面的程式碼片段中,root是代表的是視窗的容器,我們建立Application對象,並且指定了它的視窗容器,開啟訊息佇列迴圈,最後銷毀視窗。
Python入門案例之Hello