Python中的tkinter庫簡單案例詳解

案例一

Label & Button 標簽和按鈕

import tkinter as tk
 
window = tk.Tk()  # 實例化Tk
window.title("muy window")  # 設置標題
window.geometry("200x100")  # 設置窗口的大小
var1 = tk.StringVar()  # 定義tk變量
l1 = tk.Label(window, textvariable=var1, bg="green", font=("Arial", 12), width=15, height=2)  # 設置標簽,內容顯示為var1變量
l1.pack()  # 擺放這個標簽
hit_me1 = False
def hit_me():
    global hit_me1
    if not hit_me1:
        hit_me1 = True
        var1.set("this is tk")  # 給變量賦值
    else:
        hit_me1 = False
        var1.set("this is tk, too")
b1 = tk.Button(window, text="hit me", width=15, height=2, command=hit_me)  # 點擊按鈕,運行hit_me這個函數
b1.pack()
window.mainloop()  # 顯示窗口

案例二

Entry & Text 輸入和文本框

import tkinter as tk
 
window = tk.Tk()  # 實例化Tk
window.title("muy window")  # 設置標題
window.geometry("200x150")  # 設置窗口的大小
e = tk.Entry(window, show=None)  # 如果輸入密碼的話,show="*"
e.pack()
def insert_point():
    var = e.get()  # 得到文本輸入框的值
    t.insert("insert", var)  # 文本放到光標位置
def insert_end():
    var = e.get()
    t.insert("end", var)  # 將文本放到文本框的末尾
    # t.insert(1.1, var)  # 將文本放到第一行第一列
b1 = tk.Button(window, text="insert point", width=15, height=2, command=insert_point).pack()  # 定義一個按鈕,顯示在光標位置插入文本
b2 = tk.Button(window, text="insert end", width=15, height=2, command=insert_end).pack()  # 在末尾出插入
t = tk.Text(window, height=2, width=15)
t.pack()  # 註意不能一行寫完,pack要寫在下一行
window.mainloop()  # 顯示窗口

案例三

Listbox 部件

import tkinter as tk
 
window = tk.Tk()  # 實例化Tk
window.title("muy window")  # 設置標題
window.geometry("200x150")  # 設置窗口的大小
var1 = tk.StringVar()
l = tk.Label(window, bg="yellow", width=4, textvariable=var1)
l.pack()
def print_selection():
    var = lb.get(lb.curselection())  # 得到鼠標點擊的內容
    var1.set(var)  # 將值賦值給var1
b1 = tk.Button(window, text="insert point", width=15, height=2,
               command=print_selection).pack()  # 定義一個按鈕,顯示在光標位置插入文本
var2 = tk.StringVar()  # 存儲可迭代對象的值
var2.set((1, 2, 3, 4))  # 列表也可,設置初始值
lb = tk.Listbox(window, listvariable=var2)
list_item = [1, 2, 11, 54]
for i in list_item:
    lb.insert("end", i)  # 向列表框中插入值
lb.delete(1)  # 刪除下標索引為2的值
lb.pack()
window.mainloop()  # 顯示窗口

案例四

Radiobutton 選擇按鈕

import tkinter as tk
 
window = tk.Tk()  # 實例化Tk
window.title("muy window")  # 設置標題
window.geometry("200x150")  # 設置窗口的大小
var1 = tk.StringVar()
l = tk.Label(window, bg="yellow", width=15)
l.pack()
def print_selection():
    l.config(text=f"you have select {var1.get()}")  # 將text重新賦值
rad1 = tk.Radiobutton(window, text="select a", variable=var1, value="A",
                      command=print_selection).pack()  # variable=var1, value="A" 的意思是,將var1賦值成A
rad2 = tk.Radiobutton(window, text="select b", variable=var1, value="B", command=print_selection).pack()
rad3 = tk.Radiobutton(window, text="select c", variable=var1, value="C", command=print_selection).pack()
window.mainloop()  # 顯示窗口

案例五

Scale 尺度

import tkinter as tk
 
window = tk.Tk()  # 實例化Tk
window.title("muy window")  # 設置標題
window.geometry("200x150")  # 設置窗口的大小
l = tk.Label(window, bg="yellow", width=15)
l.pack()
def print_selection(v):  # Scale調用函數,其有自動的傳入值
    l.config(text=f"you have select {v}")
    
s = tk.Scale(window, label="try me", from_=5, to=11, orient=tk.HORIZONTAL,
             length=200, showvalue=0, tickinterval=3, resolution=0.01, command=print_selection)
# label設置名字,from to 設置刻度,orient設置方向,length設置長度,showvalue展示的值,tickinterval刻度,resolution精度
s.pack()
window.mainloop()  # 顯示窗口

案例六

Checkbutton 勾選項

import tkinter as tk
 
window = tk.Tk()  # 實例化Tk
window.title("muy window")  # 設置標題
window.geometry("200x150")  # 設置窗口的大小
l = tk.Label(window, bg="yellow", width=15, text="empty")
l.pack()
def print_selection():  # Scale調用函數,其有自動的傳入值
    if (var1.get() == 1) & (var2.get() == 0):
        l.config(text="i love python")
    elif (var1.get() == 1) & (var2.get() == 1):
        l.config(text="i love both")
    elif (var1.get() == 0) & (var2.get() == 1):
        l.config(text="i love C++")
    else:
        l.config(text="i don't love either")
var1 = tk.IntVar()
var2 = tk.IntVar()
cl = tk.Checkbutton(window, text="Python", variable=var1, onvalue=1, offvalue=0
                    , command=print_selection)  # 選擇var1的值為1,否則為0
c2 = tk.Checkbutton(window, text="C++", variable=var2, onvalue=1, offvalue=0
                    , command=print_selection)
cl.pack()
c2.pack()
window.mainloop()  # 顯示窗口

案例七

Canvas 畫佈

import tkinter as tk
 
window = tk.Tk()  # 實例化Tk
window.title("muy window")  # 設置標題
window.geometry("200x200")  # 設置窗口的大小
canvas = tk.Canvas(window, bg="blue", height=100, width=200)
image_file = tk.PhotoImage(file=r"D:\programme\web\web_file\web學習\images\image01.jpg")  # 註意,隻能導入.gif的圖片
image = canvas.create_image(0, 0, anchor="nw", image=image_file).pack()  # 錨點為左上角,西北方向
x0, y0, x1, y1 = 20, 50, 80, 80
line = canvas.create_line(x0, y0, x1, y1)  # 畫線
oval = canvas.create_oval(x0, y0, x1, y1, fill="red")  # 繪制扇形
arc = canvas.create_arc(x0 + 30, y0 + 30, x1 + 30, x1 + 30, y1 + 30, start=0, extent=180)  # 扇形
rect = canvas.create_rectangle(100, 30, 100 + 20, 30 + 20)  # 繪制正方形
canvas.pack()
def moveit():
    canvas.move(rect, 0, 2)  # 移動正方形,使其往下走兩個單位
a = tk.Button(window, text="move", command=moveit).pack()
window.mainloop()  # 顯示窗口

案例八

Menubar 菜單

import tkinter as tk
 
window = tk.Tk()  # 實例化Tk
window.title("my window")  # 設置標題
window.geometry("200x200")  # 設置窗口的大小
count = 0
l = tk.Label(window, text="", bg="yellow")
l.pack()
def do_job():
    global count
    l.config(text=f"do{str(count)}")
    count += 1
"""定義文件選項"""
mb = tk.Menu(window)
file = tk.Menu(mb, tearoff=0)  # 有沒有分隔線
mb.add_cascade(label="File", menu=file)  # 添加一個功能
file.add_command(label="New", command=do_job)  # 每一個選項都是一個功能,命令
file.add_command(label="Open", command=do_job)
file.add_command(label="Save", command=do_job)
sm = tk.Menu(file)  # 在File裡面繼續添加命令
file.add_cascade(label="Submit", menu=sm)
sm.add_command(label="New", command=do_job)
window.config(menu=mb)  # 將菜單添加到window上面
window.mainloop()  # 顯示窗口

案例九

Frame 框架

import tkinter as tk
 
window = tk.Tk()  # 實例化Tk
window.title("my window")  # 設置標題
window.geometry("200x200")  # 設置窗口的大小
tk.Label(window, text="on the window").pack()
# 添加框架
fm = tk.Frame(window)
fm.pack()
fm_1 = tk.Frame(fm)
fm_r = tk.Frame(fm)
fm_1.pack(side="left")
fm_r.pack(side="right")
tk.Label(fm_1, text="on the frame_1").pack()
tk.Label(fm_r, text="on the frame_r").pack()
window.mainloop()  # 顯示窗口

案例十

messagebox 彈窗

import tkinter as tk
import tkinter.messagebox
 
window = tk.Tk()  # 實例化Tk
window.title("my window")  # 設置標題
window.geometry("200x200")  # 設置窗口的大小
def hit_me():
    tk.messagebox.showinfo(title="hi", message="hit")  # 註意,要導入模塊,還有showwarning, showerror,
"""
tkinter.messagebox.askokcancel('提示', '要執行此操作嗎')#確定/取消,返回值true/false
tkinter.messagebox.askquestion('提示', '要執行此操作嗎')#是/否,返回值yes/no
tkinter.messagebox.askyesno('提示', '要執行此操作嗎')#是/否,返回值true/false
tkinter.messagebox.askretrycancel('提示', '要執行此操作嗎')#重試/取消,返回值true/false
文件對話框
import tkinter.filedialog
a = tkinter.filedialog.asksaveasfilename()#返回文件名
print(a)
a = tkinter.filedialog.asksaveasfile()#會創建文件
a = tkinter.filedialog.askopenfilename()#返回文件名
a = tkinter.filedialog.askopenfile()#返回文件流對象
a = tkinter.filedialog.askdirectory()#返回目錄名
a = tkinter.filedialog.askopenfilenames()#可以返回多個文件名
a = tkinter.filedialog.askopenfiles()#多個文件流對象
    
tk.Button(window, text="hit me", command=hit_me).pack()
window.mainloop()  # 顯示窗口

案例十一

pack grid place 放置

import tkinter as tk
 
window = tk.Tk()  # 實例化Tk
window.title("my window")  # 設置標題
window.geometry("200x200")  # 設置窗口的大小
# tk.Label(window, text="pack").pack(side="top")
# tk.Label(window, text="pack").pack(side="bottom")
# tk.Label(window, text="pack").pack(side="left")
# tk.Label(window, text="pack").pack(side="right")
# for i in range(4):  # 行
#     for j in range(3):  # 列
#         tk.Label(window, text="grid").grid(row=i, column=j, padx=10, pady=10)  # 以方格的形式放置
tk.Label(window, text="place").place(x=100, y=100, anchor="nw")  # 點的形式
window.mainloop()  # 顯示窗口

登錄窗口

import tkinter as tk
import tkinter.messagebox
 
window = tk.Tk()  # 實例化Tk
window.title("login")  # 設置標題
window.geometry("450x300")  # 設置窗口的大小
user_info = [{"name": "admin", "pwd": "1"}, {"name": "user", "pwd": "1"}]  # 存儲賬號信息
# 定義函數
def login():
    user_info_name = [i["name"] for i in user_info]
    user_info_pwd = [i["pwd"] for i in user_info]
    user_name = var_user_name.get()
    user_pwd = var_pwd.get()
    if user_name in user_info_name:
        if user_pwd == user_info_pwd[user_info_name.index(user_name)]:
            tk.messagebox.showinfo(title="歡迎回來", message="How are you")
        else:
            tk.messagebox.showerror(message="pwd error")
    else:
        answer = tk.messagebox.askquestion(title="warn", message="您還沒有賬號,是否需要註冊?")
        if answer:
            sign()
def sign():
    def store():
        new_pwd1 = new_pwd.get()
        new_user_name1 = new_user_name.get()
        user_info.append({"name": new_user_name1, "pwd": new_pwd1})
        tk.messagebox.showinfo(message="註冊成功")
        window_sign.destroy()  # 關閉窗口
    def close():
        window_sign.destroy()
    window_sign = tk.Toplevel(window)  # 窗口上的窗口
    window_sign.geometry("350x200")
    window_sign.title("Sign up window")
    # user
    tk.Label(window_sign, text="Name:").place(x=60, y=60)
    new_user_name = tk.StringVar()  # 註意要使用.get()得到值
    new_user_name.set("[email protected]")  # 默認值
    tk.Entry(window_sign, textvariable=new_user_name).place(x=90, y=60)  # 輸入用戶名
    # pwd
    tk.Label(window_sign, text="Pwd:").place(x=60, y=100)
    new_pwd = tk.StringVar()
    tk.Entry(window_sign, textvariable=new_pwd, show="*").place(x=90, y=100)  # 輸入密碼
    # 確認按鈕
    tk.Button(window_sign, text="確認", command=store).place(x=100, y=140)
    # 取消按鈕
    tk.Button(window_sign, text="取消", command=close).place(x=170, y=140)
if __name__ == '__main__':
    
    tk.Label(window, text="User Name:").place(x=50, y=50)
    var_user_name = tk.StringVar()  # 註意要使用.get()得到值
    var_user_name.set("[email protected]")  # 默認值
    tk.Entry(window, textvariable=var_user_name).place(x=130, y=50)  # 輸入用戶名
    tk.Label(window, text="Password:").place(x=50, y=90)
    var_pwd = tk.StringVar()
    tk.Entry(window, textvariable=var_pwd, show="*").place(x=130, y=90)  # 輸入密碼
    # login Button
    tk.Button(window, text="Login", command=login).place(x=130, y=130)  # 登錄按鈕
    # sign Button
    tk.Button(window, text="Sign Up", command=sign).place(x=200, y=130)  # 註冊按鈕
    window.mainloop()  # 顯示窗口

本文來自博客園,作者:A-L-Kun,轉載請註明原文鏈接:https://www.cnblogs.com/liuzhongkun/p/15829678.html

到此這篇關於Python中的tkinter庫簡單案例詳解的文章就介紹到這瞭,更多相關Python中的tkinter庫內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: