歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python入門案例之Hello World!

Python入門案例之Hello World!

日期:2017/3/1 9:30:10   编辑:Linux編程

Python入門案例之Hello World!

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對象,並且指定了它的窗口容器,開啟消息隊列循環,最後銷毀窗口。

--------------------------------------分割線 --------------------------------------

CentOS上源碼安裝Python3.4 http://www.linuxidc.com/Linux/2015-01/111870.htm

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved