亲宝软件园·资讯

展开

Python中的tkinter库

A-L-Kun 人气:0

TKinter库,Python 的 GUI 库非常多,之所以选择 Tkinter,一是最为简单,二是自带库,不需下载安装,随时使用,跨平台兼容性非常好,三则是从需求出发的,Python 在实际应用中极少用于开发复杂的桌面应用,毕竟,Python 的各种 GUI 工具包都“一般得很”,不具备优势。

案例一

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("exampe@python.com")  # 默认值
    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("exampe@python.com")  # 默认值
    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()  # 显示窗口

加载全部内容

相关教程
猜你喜欢
用户评论