跳轉到內容

Python 程式設計/Tkinter

來自華夏公益教科書,開放的世界中的開放書籍

Tkinter 是 Tcl/Tk 的 Python 包裝器,提供跨平臺的 GUI 工具包。在 Windows 上,它與 Python 捆綁在一起;在其他作業系統上,它可以安裝。可用小部件集比其他一些工具包中的小部件集小,但由於 Tkinter 小部件是可擴充套件的,許多缺少的複合小部件可以使用可擴充套件性建立,例如組合框和滾動窗格。

IDLE,Python 的整合開發和學習環境,是用 Tkinter 編寫的,通常與 Python 一起分發。您可以透過使用 IDLE 的選單和對話方塊來了解 Tkinter 的功能。例如,“選項”>“配置 IDLE...”對話方塊顯示了各種 GUI 元素,包括選項卡式介面。您可以透過研究 IDLE 原始碼來學習使用 Tkinter 進行程式設計,該程式碼在 Windows 上可以在 C:\Program Files\Python27\Lib\idlelib 中找到。

Python 3:此頁面上的示例適用於 Python 2。在 Python 3 中,以前稱為模組 Tkinter 的模組現在是 tkinter,以前稱為 tkMessageBox 的模組現在是 messagebox,等等。

最小示例

[編輯 | 編輯原始碼]

一個最小的示例

from Tkinter import *
root = Tk()
frame = Frame(root)
frame.pack()
label = Label(frame, text="Hey there.")
label.pack()
quitButton = Button(frame, text="Quit", command=frame.quit)
quitButton.pack()
root.mainloop()

一個更緊湊的最小示例 - 後面不再需要對 GUI 專案的引用

from Tkinter import *
root = Tk()
frame = Frame(root)
frame.pack()
Label(frame, text="Hey there.").pack()
Button(frame, text="Quit", command=frame.quit).pack()
root.mainloop()

一個建立從 Frame 派生的應用程式類的最小示例

from Tkinter import *

class App(Frame):
  def __init__(self, master):
    Frame.__init__(self)
    self.label = Label(master, text="Hey there.")
    self.label.pack()    
    self.quitButton = Button(master, text="Quit", command=self.quit)
    self.quitButton.pack()

if __name__ == '__main__':
  root = Tk()
  app = App(root)
  root.mainloop()

訊息框

[編輯 | 編輯原始碼]

可以使用 tkMessageBox 建立簡單的訊息框,如下所示

import Tkinter, tkMessageBox
Tkinter.Tk().withdraw() # Workaround: Hide the window
answer = tkMessageBox.askokcancel("Confirmation", "File not saved. Discard?")
answer = tkMessageBox.askyesno("Confirmation", "Do you really want to delete the file?")
# Above, "OK" and "Yes" yield True, and "Cancel" and "No" yield False
tkMessageBox.showwarning("Warning", "Timeout has elapsed.")
tkMessageBox.showwarning("Warning", "Timeout has elapsed.", icon=tkMessageBox.ERROR)
tkMessageBox.showerror("Warning", "Timeout has elapsed.")

連結

檔案對話方塊

[編輯 | 編輯原始碼]

檔案對話方塊可以建立如下所示

import Tkinter, tkFileDialog
Tkinter.Tk().withdraw() # Workaround: Hide the window
filename1 = tkFileDialog.askopenfilename()
filename2 = tkFileDialog.askopenfilename(initialdir=r"C:\Users")
filename3 = tkFileDialog.asksaveasfilename()
filename4 = tkFileDialog.asksaveasfilename(initialdir=r"C:\Users")
if filename1 <> "":
  for line in open(filename1): # Dummy reading of the file
    dummy = line.rstrip()

連結

單選按鈕

[編輯 | 編輯原始碼]

單選按鈕可用於建立具有多個選項的簡單選擇對話方塊

from Tkinter import *
master = Tk()  
choices = [("Apple", "a"), ("Orange", "o"), ("Pear", "p")]
defaultChoice = "a"
userchoice = StringVar()
userchoice.set(defaultChoice)
def cancelAction(): userchoice.set("");master.quit()
    Label(master, text="Choose a fruit:").pack()
for text, key in choices: 
    Radiobutton(master, text=text, variable=userchoice, value=key).pack(anchor=W)
Button(master, text="OK", command=master.quit).pack(side=LEFT, ipadx=10)
Button(master, text="Cancel", command=cancelAction).pack(side=RIGHT, ipadx=10)
mainloop()
if userchoice.get() <>"":
    print userchoice.get() # "a", or "o", or "p"
else:
    print "Choice canceled."

單選按鈕的替代方法,它會立即對按鈕按下做出反應

from Tkinter import *
import os
buttons = [("Users", r"C:\Users"),
           ("Windows", r"C:\Windows"),
           ("Program Files", r"C:\Program Files")]
master = Tk()
def open(filePath):
  def openInner():
    os.chdir(filePath) # Cross platform
    #os.system('start "" "'+filePath+'') # Windows
    master.quit()
  return openInner
Label(master, text="Choose a fruit:").pack()
for buttonLabel, filePath in buttons:
  Button(master, text=buttonLabel, command=open(filePath)).pack(anchor=W)
mainloop()

連結

列表框

[編輯 | 編輯原始碼]

列表框可用於建立簡單的多項選擇對話方塊

from Tkinter import *
master = Tk()  
choices = ["Apple", "Orange", "Pear"]
canceled = BooleanVar()
def cancelAction(): canceled.set(True); master.quit()
Label(master, text="Choose a fruit:").pack()
listbox = Listbox(master, selectmode=EXTENDED) # Multiple options can be chosen
for text in choices: 
  listbox.insert(END, text)
listbox.pack()    
Button(master, text="OK", command=master.quit).pack(side=LEFT, ipadx=10)
Button(master, text="Cancel", command=cancelAction).pack(side=RIGHT, ipadx=10)
mainloop()
if not canceled.get():
  print listbox.curselection() # A tuple of choice indices starting with 0
  # The above is a tuple even if selectmode=SINGLE
  if "0" in listbox.curselection(): print "Apple chosen."
  if "1" in listbox.curselection(): print "Orange chosen."
  if "2" in listbox.curselection(): print "Pear chosen."  
else:
  print "Choice canceled."

連結

複選框

[編輯 | 編輯原始碼]

複選框或複選按鈕可以建立如下所示

from Tkinter import *
root = Tk()
checkbuttonState = IntVar()
Checkbutton(root, text="Recursive", variable=checkbuttonState).pack()
mainloop()
print checkbuttonState.get() # 1 = checked; 0 = unchecked

連結

輸入框

[編輯 | 編輯原始碼]

Entry 小部件,一個單行文字輸入欄位,可以按如下方式使用

from Tkinter import *
root = Tk()
Label(text="Enter your first name:").pack()
entryContent = StringVar()
Entry(root, textvariable=entryContent).pack()
mainloop()
print entryContent.get()

連結

選單可以建立如下所示

from Tkinter import *
root = Tk()
def mycommand(): print "Chosen."
menubar = Menu(root)

menu1 = Menu(menubar, tearoff=0)
menu1.add_command(label="New", command=mycommand)
menu1.add_command(label="Clone", command=mycommand)
menu1.add_separator()
menu1.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="Project", menu=menu1)
  
menu2 = Menu(menubar, tearoff=0)
menu2.add_command(label="Oval", command=mycommand)
menu2.add_command(label="Rectangle", command=mycommand)
menubar.add_cascade(label="Shapes", menu=menu2)

root.config(menu=menubar)

mainloop()

連結

標籤框架

[編輯 | 編輯原始碼]

可以使用 LabelFrame 小部件建立其他元素周圍的框架,如下所示

from Tkinter import *
root = Tk()
Label(text="Bus").pack()
frame = LabelFrame(root, text="Fruits") # text is optional
frame.pack()
Label(frame, text="Apple").pack()
Label(frame, text="Orange").pack()
mainloop()

連結

Message 類似於 Label,但可以跨多行換行。示例

from Tkinter import *
root = Tk()
Message(text="Lazy brown fox jumped. " * 5, width=100).pack() # width is optional
mainloop()

連結

選項選單

[編輯 | 編輯原始碼]

下拉列表,在 Tkinter 選項選單中,可以建立如下所示

from Tkinter import *
root = Tk()
options = ["Apple", "Orange", "Pear"]
selectedOption = StringVar()
selectedOption.set("Apple") # Default
OptionMenu(root, selectedOption, *options).pack()  
mainloop()
print selectedOption.get() # The text in the options list

連結

Text 小部件更復雜,允許編輯純文字和格式化文字,包括多種字型。

要新增的示例。

連結

Tcl/Tk 版本

[編輯 | 編輯原始碼]

Python 2.3 的 Windows 安裝程式附帶了 Tcl/Tk 8.4.3。您可以瞭解有關該版本的更多資訊

import Tkinter
print Tkinter.TclVersion # Up to 8.5
print Tkinter.TkVersion # Up to 8.5

連結

[編輯 | 編輯原始碼]
[編輯 | 編輯原始碼]
華夏公益教科書