Python中的tkinter库简单案例详解

目录

  • 案例一
    • Label & Button 标签和按钮
  • 案例二
    • Entry & Text 输入和文本框
  • 案例三
    • Listbox 部件
  • 案例四
    • Radiobutton 选择按钮
  • 案例五
    • Scale 尺度
  • 案例六
    • Checkbutton 勾选项
  • 案例七
    • Canvas 画布
  • 案例八
    • Menubar 菜单
  • 案例九
    • Frame 框架
  • 案例十
    • messagebox 弹窗
  • 案例十一
    • pack grid place 放置
    • 登录窗口
TKinter库,Python 的 GUI 库非常多,之所以选择 Tkinter,一是最为简单,二是自带库,不需下载安装,随时使用,跨平台兼容性非常好,三则是从需求出发的,Python 在实际应用中极少用于开发复杂的桌面应用,毕竟,Python 的各种 GUI 工具包都“一般得很”,不具备优势。

案例一
Label & Button 标签和按钮
import tkinter as tk window = tk.Tk()# 实例化Tkwindow.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 = Falsedef hit_me():global hit_me1if not hit_me1:hit_me1 = Truevar1.set("this is tk")# 给变量赋值else:hit_me1 = Falsevar1.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()# 实例化Tkwindow.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()# 实例化Tkwindow.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)# 将值赋值给var1b1 = 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()# 实例化Tkwindow.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="https://www.it610.com/article/A",command=print_selection).pack()# variable=var1, value="https://www.it610.com/article/A" 的意思是,将var1赋值成Arad2 = tk.Radiobutton(window, text="select b", variable=var1, value="https://www.it610.com/article/B", command=print_selection).pack()rad3 = tk.Radiobutton(window, text="select c", variable=var1, value="https://www.it610.com/article/C", command=print_selection).pack()window.mainloop()# 显示窗口


案例五
Scale 尺度
import tkinter as tk window = tk.Tk()# 实例化Tkwindow.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=https://www.it610.com/article/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()# 实例化Tkwindow.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=https://www.it610.com/article/1, offvalue=0, command=print_selection)# 选择var1的值为1,否则为0c2 = tk.Checkbutton(window, text="C++", variable=var2, onvalue=https://www.it610.com/article/1, offvalue=0, command=print_selection)cl.pack()c2.pack()window.mainloop()# 显示窗口


案例七
Canvas 画布
import tkinter as tk window = tk.Tk()# 实例化Tkwindow.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, 80line = 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()# 实例化Tkwindow.title("my window")# 设置标题window.geometry("200x200")# 设置窗口的大小count = 0l = tk.Label(window, text="", bg="yellow")l.pack()def do_job():global countl.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()# 实例化Tkwindow.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 tkimport tkinter.messagebox window = tk.Tk()# 实例化Tkwindow.title("my window")# 设置标题window.geometry("200x200")# 设置窗口的大小def hit_me():tk.messagebox.showinfo(title="hi", message="hit")# 注意,要导入模块,还有showwarning, showerror,"""tkinter.messagebox.askokcancel('提示', '要执行此操作吗')#确定/取消,返回值true/falsetkinter.messagebox.askquestion('提示', '要执行此操作吗')#是/否,返回值yes/notkinter.messagebox.askyesno('提示', '要执行此操作吗')#是/否,返回值true/falsetkinter.messagebox.askretrycancel('提示', '要执行此操作吗')#重试/取消,返回值true/false文件对话框import tkinter.filedialoga = 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()# 实例化Tkwindow.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 tkimport tkinter.messagebox window = tk.Tk()# 实例化Tkwindow.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")# usertk.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)# 输入用户名# pwdtk.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 Buttontk.Button(window, text="Login", command=login).place(x=130, y=130)# 登录按钮# sign Buttontk.Button(window, text="Sign Up", command=sign).place(x=200, y=130)# 注册按钮window.mainloop()# 显示窗口

【Python中的tkinter库简单案例详解】到此这篇关于Python中的tkinter库简单案例详解的文章就介绍到这了,更多相关Python中的tkinter库内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    推荐阅读