潮州 做网站 有钱,内容平台策划书,wordpress不使用缩略图,2022世界互联网峰会Python支持多種圖形界面的第三方庫#xff0c;包括#xff1a;TkwxWidgetsQtGTK等等。但是Python自帶的庫是支持Tk的Tkinter#xff0c;使用Tkinter#xff0c;無需安裝任何包#xff0c;就可以直接使用。本章簡單介紹如何使用Tkinter進行GUI編程。Tkinter我們來梳理一下概…Python支持多種圖形界面的第三方庫包括TkwxWidgetsQtGTK等等。但是Python自帶的庫是支持Tk的Tkinter使用Tkinter無需安裝任何包就可以直接使用。本章簡單介紹如何使用Tkinter進行GUI編程。Tkinter我們來梳理一下概念我們編寫的Python代碼會調用內置的TkinterTkinter封裝了訪問Tk的接口Tk是一個圖形庫支持多個操作系統使用Tcl語言開發Tk會調用操作系統提供的本地GUI接口完成最終的GUI。所以我們的代碼只需要調用Tkinter提供的接口就可以了。第一個GUI程序使用Tkinter十分簡單我們來編寫一個GUI版本的“Hello, world!”。第一步是導入Tkinter包的所有內容from Tkinter import *第二步是從Frame派生一個Application類這是所有Widget的父容器class Application(Frame):def __init__(self, masterNone):Frame.__init__(self, master)self.pack()self.createWidgets()def createWidgets(self):self.helloLabel Label(self, textHello, world!)self.helloLabel.pack()self.quitButton Button(self, textQuit, commandself.quit)self.quitButton.pack()在GUI中每個Button、Label、輸入框等都是一個Widget。Frame則是可以容納其他Widget的Widget所有的Widget組合起來就是一棵樹。pack()方法把Widget加入到父容器中並實現布局。pack()是最簡單的布局grid()可以實現更復雜的布局。在createWidgets()方法中我們創建一個Label和一個Button當Button被點擊時觸發self.quit()使程序退出。第三步實例化Application並啟動消息循環app Application()# 設置窗口標題:app.master.title(Hello World)# 主消息循環:app.mainloop()GUI程序的主線程負責監聽來自操作系統的消息並依次處理每一條消息。因此如果消息處理非常耗時就需要在新線程中處理。運行這個GUI程序可以看到下面的窗口點擊“Quit”按鈕或者窗口的“x”結束程序。輸入文本我們再對這個GUI程序改進一下加入一個文本框讓用戶可以輸入文本然后點按鈕后彈出消息對話框。from Tkinter import *import tkMessageBoxclass Application(Frame):def __init__(self, masterNone):Frame.__init__(self, master)self.pack()self.createWidgets()def createWidgets(self):self.nameInput Entry(self)self.nameInput.pack()self.alertButton Button(self, textHello, commandself.hello)self.alertButton.pack()def hello(self):name self.nameInput.get() or worldtkMessageBox.showinfo(Message, Hello, %s % name)當用戶點擊按鈕時觸發hello()通過self.nameInput.get()獲得用戶輸入的文本后使用tkMessageBox.showinfo()可以彈出消息對話框。程序運行結果如下小結Python內置的Tkinter可以滿足基本的GUI程序的要求如果是非常復雜的GUI程序建議用操作系統原生支持的語言和庫來編寫。附上程序{CSDN:CODE:# -*- coding: utf-8 -*-fromTkinter import* #導入Tkinter包的所有內容importtkMessageBox#在GUI中每個Button、Label、輸入框等都是一個Widget。Frame則是可以容納其他Widget的Widget所有的Widget組合起來就是一棵樹。classApplication(Frame): #從Frame派生一個Application類這是所有Widget的父容器def__init__(self,master None):Frame.__init__(self,master)self.pack()self.createWidgets()# pack()方法把Widget加入到父容器中並實現布局。pack()是最簡單的布局grid()可以實現更復雜的布局。defcreateWidgets(self):self.nameInput Entry(self)self.nameInput.pack()#當用戶點擊按鈕時觸發hello()self.alertButton Button(self, text Hello, command self.hello)self.alertButton.pack()#通過self.nameInput.get()獲得用戶輸入的文本后使用tkMessageBox.showinfo彈出對話框defhello(self):name self.nameInput.get() or world!tkMessageBox.showinfo(Message,Hello, %s% name)#實例化Application並啟動消息循環app Application()#設置窗口標題app.master.title(Hello World!)#主消息循環app.mainloop()}