Tkinter模塊是Python的標準Tk GUI工具包的接口。可以在大多數的Unix平臺下使用,同樣可以應用在Windows和Mac系統裏。
最基本的使用:
顯示一個窗口,窗口裏面有一個標籤
import tkinter as tk
#top level, root window
app = tk.Tk()
app.title("CXY demo")
mLabel = tk.Label(app,text="this is a label")
#自動調節組件尺寸
mLabel.pack()
app.mainloop()
按鈕的基本使用方法:
設置按鈕字體顏色,設置按下後的回調函數
import tkinter as tk
class APP:
def __init__(self, master):
#一個框架,通常用於給控件分組
frame = tk.Frame(master)
#設置對齊方式和邊距
frame.pack(side = tk.LEFT, padx = 10, pady = 10)
#創建一個按鈕,設置文言和前景色, 設置點擊按鈕後觸發的事件
self.button = tk.Button(frame,text = "say hello", fg = "blue",
command = self.say_hello)
self.button.pack()
def say_hello(self):
print("hello world!")
root = tk.Tk()
app = APP(root)
root.mainloop()
在標籤中加入圖片,改變標籤內容的demo
from tkinter import *
def m_callback():
var.set("Run!Quick!")
root = Tk()
frame1 = Frame(root)
frame2 = Frame(root)
var = StringVar()
var.set("Warning! \nnuclear weapon detected!")
textLabel = Label(frame1, textvariable = var,
justify = LEFT,
padx = 10)
textLabel.pack(side = LEFT)
#不支持jpg格式。。。
photo = PhotoImage(file = "nuclear.gif")
imgLabel = Label(frame1, image = photo)
imgLabel.pack(side = RIGHT)
mButton = Button(frame2, text = "Help!", command = m_callback)
mButton.pack()
frame1.pack(padx = 10, pady = 10)
frame2.pack(padx = 10, pady = 10)
mainloop()
讓文字顯示在圖片之上(Label的compound參數)
from tkinter import *
root = Tk()
photo = PhotoImage(file = "nuclear.gif")
#compound 讓文字顯示在圖片之上
imgLabel = Label(root, text = "Warning\n!!!!!",
justify = LEFT, image = photo,
compound = CENTER, font = ("微軟雅黑", 20),
fg = "yellow")
imgLabel.pack()
mainloop()
多選按鈕的基本使用方法:
按下按鈕可以顯示用戶選擇結果(0爲未選中,1爲選中)
from tkinter import *
root = Tk()
root.title("這個週末去幹啥?")
Options = ["去沙漠滑冰", "去火星度假", "在海底遛狗","洗洗睡吧。。。"]
#記錄到底選了什麼
selected = []
for opt in Options:
#創建一個變量用於存儲用戶的選擇
selected.append(IntVar())
#創建多選按鈕
temp = Checkbutton(root, text = opt, variable = selected[-1])
#掛在最左邊(用WESN表示上下左右(東南西北))
temp.pack(anchor = W)
def m_callback():
for sel in selected:
print(sel.get())
mButton = Button(root, text = "決定就是你了!", command = m_callback)
mButton.pack()
mainloop()
單選按鈕的基本使用方法:
from tkinter import *
root = Tk()
v = IntVar()
#variable一組Radiobutton必須用一個變量,比如選中Two時,v的值就爲後面的value的值,即2
Radiobutton(root, text = "One", variable = v, value = 1).pack(anchor = W)
Radiobutton(root, text = "Two", variable = v, value = 2).pack(anchor = W)
Radiobutton(root, text = "Three", variable = v, value = 3).pack(anchor = W)
Radiobutton(root, text = "Four", variable = v, value = 4).pack(anchor = W)
#做一個LabelFrame來存放單選按鈕
group = LabelFrame(root, text = "你認爲最厲害的人是誰?", padx = 5, pady = 5)
group.pack(padx = 10, pady = 10)
Options = [
("超人", 1),
("孫悟空", 2),
("比爾蓋茨", 3),
("你自己", 4),
]
v = IntVar()
v.set(1)
#indicatoron = False使前面不再是小圓圈的形式,fill = X爲橫向填充
for name, num in Options:
b = Radiobutton(group, text = name, variable = v, value = num, indicatoron = False)
b.pack(fill = X)
mainloop()
輸入框的基本使用方法:
from tkinter import *
root = Tk()
e = Entry(root)
e.pack(padx = 20, pady = 20)
#清空
e.delete(0, END)
#插入默認文本
e.insert(0,"defaults")
mainloop()
加入驗證和隱藏功能的輸入框
from tkinter import *
root = Tk()
#用表格的方式佈局控件
Label(root, text = "賬戶:").grid(row = 0, column = 0)
Label(root, text = "密碼:").grid(row = 1, column = 0)
e1 = Entry(root)
def m_test():
if e2.get() == "good":
print("OK")
return True
else:
print("NG")
e2.delete(0, END)
return False
def m_invalid():
print("try again!")
#密碼輸入框要求顯示*,並且必須爲good,當失去焦點時進行驗證,驗證函數註冊在validatecommand裏
#validatecommand爲False時,會調用invalidcommand
e2 = Entry(root, show = "*", validate = "focusout",
validatecommand = m_test, invalidcommand = m_invalid)
e1.grid(row = 0, column = 1, padx = 10, pady = 5)
e2.grid(row = 1, column = 1, padx = 10, pady = 5)
def m_show():
print("賬戶:%s" % e1.get())
print("密碼:%s" % e2.get())
Button(root, text = "確認", width = 10, command = m_show)\
.grid(row = 3, column = 0, sticky = W, padx = 10, pady = 5)
#quit方法要想正常退出,需要雙擊打開py文件,在IDE裏啓動不好使
Button(root, text = "退出", width = 10, command = root.quit)\
.grid(row = 3, column = 1, sticky = E, padx = 10, pady = 5)
mainloop()