一、Tkinter模块的基本使用
1)实例化窗口程序
import tkinter as tk app = tk.Tk() app.title("FishC Demo") app.mainloop()
2)窗口生成一个标题文本
import tkinter as tk # 第一步实例化tk,用于容纳整个程序 app = tk.Tk() app.title("FishC Demo") # 设置标题栏 # 第二步,用于显示文本,或图片 thelabel =tk.Label(app,text="我的第二个窗口程序") # Label 实例化标签 thelabel.pack() # 用于自动调节组件的尺寸 # 窗口的组事件循环 app.mainloop()
3)用类来实现简单的窗口
import tkinter as tk class App: def __init__(self,master): frame = tk.Frame(master) frame.pack() self.hi_there = tk.Button(frame,text='打招呼',fg = 'blue') self.hi_there.pack() root = tk.Tk() app = App(root) root.mainloop()
4)类中,创建点击方法,修改文本位置,及背景方法
import tkinter as tk class App: def __init__(self,master): frame = tk.Frame(master) frame.pack(side = tk.LEFT,padx = 10,pady = 10) self.hi_there = tk.Button(frame,text='打招呼',bg = 'blue',fg = 'white',command=self.say_hi) self.hi_there.pack() def say_hi(self): print('欢迎来到GUI编程') root = tk.Tk() app = App(root) root.mainloop()
5)添加图片功能
from tkinter import * root = Tk() textlabel = Label(root,text='你勇敢吗!') textlabel.pack(side = LEFT) photo = PhotoImage(file = "1.png") imgLabel = Label(root,image=photo) imgLabel.pack(side = RIGHT) mainloop()
6)对文字属性编辑
from tkinter import * root = Tk() textlabel = Label(root,text='你勇敢吗!,\n敢来吗',justify=LEFT,padx=10) # justify=LEFT 左对齐 padx=10 边距是10 textlabel.pack(side = LEFT) photo = PhotoImage(file = "1.png") imgLabel = Label(root,image=photo) imgLabel.pack(side = RIGHT) mainloop()
7)设置成背景图片
from tkinter import * root = Tk() photo = PhotoImage(file='1.jpg') theLabel = Label(root, text="the beautiful girl", justify= LEFT, image=photo, compound=CENTER, font=("宋体",25), fg="black") theLabel.pack() mainloop()
二、Button组件
1)Button点击触发事件
from tkinter import * def callback(): var.set("吹吧,我才不信") pass root = Tk() frame1 = Frame(root) frame2 = Frame(root) var = StringVar() var.set("你勇敢吗!,\n敢来吗") textlabel = Label(frame1, textvariable=var, justify=LEFT, padx=10) # textvariable是变量字符串 justify=LEFT 左对齐 padx=10 边距是10 textlabel.pack(side = LEFT) photo = PhotoImage(file = "1.png") imgLabel = Label(frame1,image=photo) imgLabel.pack(side = RIGHT) theButton = Button(frame2,text="确定,你就点啊",command = callback) theButton.pack() frame1.pack(padx=10,pady=10) frame2.pack(padx=10,pady=10) mainloop()
2)记录Button的点击记录事件
from tkinter import * root = Tk() v = IntVar() c = Checkbutton(root,text="测试一下",variable=v) # variable=v 表示按钮状态是否被按下 c.pack() l = Label(root,textvariable=v) # 记录选中状态 l.pack() mainloop()
3)Button点击事件列表应用
from tkinter import * root = Tk() GIRLS = ["西施","苍老师",'东施'] v = [] for girl in GIRLS: v.append(IntVar()) b = Checkbutton(root,text=girl,variable=v[-1]) b.pack(anchor=W) # 名字左对齐 mainloop()
4)互斥事件
from tkinter import * root = Tk() v = IntVar() 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='Threr',variable=v,value=3).pack(anchor=W) mainloop()
5)for循环使用互斥事件和按钮的多样式
from tkinter import * root = Tk() LANGS=[("python",1), ("java",2), ("php",3), ("ruby",4)] v = IntVar() v.set(1) for lang,num in LANGS: b = Radiobutton(root,text=lang,variable=v,value=num,indicatoron=False) # indicatoron=False 设置点击的样式,默认的小原点 b.pack(fill=X) # 按钮横向填充 mainloop()
6)选择回答选项设置
from tkinter import * root = Tk() group = LabelFrame(root,text="最好的脚本语言是?",padx=5,pady=5) group.pack(padx=10,pady=10) LANGS=[("python",1), ("java",2), ("php",3), ("ruby",4)] v = IntVar() # v.set(1) # 这个是默认选择第一个 for lang,num in LANGS: b = Radiobutton(group,text=lang,variable=v,value=num) # indicatoron=False 设置点击的样式,默认的小原点 b.pack(anchor=W) mainloop()
三、Entry输入框方法
1)初探输入框
from tkinter import * root = Tk() e = Entry(root) e.pack(padx=20,pady=20) mainloop()
2)生成默认输入框文本
from tkinter import * root = Tk() e = Entry(root) e.pack(padx=20,pady=20) e.delete(0,END) e.insert(0,"默认文本...") mainloop()
3)获取用户交互点击信息
from tkinter import * root = Tk() Label(root,text="作品:").grid(row=0,column=0) Label(root,text="作者:").grid(row=1,column=0) e1 = Entry(root) e2 = Entry(root) e1.grid(row=0,column=1,padx=10,pady=5) e2.grid(row=1,column=1,padx=10,pady=5) def show(): print("作品:<%s>" % e1.get()) print("作者:<%s>" % e2.get()) Button(root,text="获取信息",width=10,command=show)\ .grid(row=3,column=0,sticky=W,padx=10,pady=5) Button(root,text="退出",width=10,command=root.quit) \ .grid(row=3, column=1, sticky=E, padx=10, pady=5) mainloop()
4)输入框隐藏输入密码功能
from tkinter import * root = Tk() Label(root,text="账号:").grid(row=0,column=0) Label(root,text="密码:").grid(row=1,column=0) v1 = StringVar() v2 = StringVar() e1 = Entry(root,textvariable=v1) e2 = Entry(root,textvariable=v2,show="*") e1.grid(row=0,column=1,padx=10,pady=5) e2.grid(row=1,column=1,padx=10,pady=5) def show(): print("账号:%s" % e1.get()) print("密码:%s" % e2.get()) Button(root,text="芝麻开门",width=10,command=show)\ .grid(row=3,column=0,sticky=W,padx=10,pady=5) Button(root,text="退出",width=10,command=root.quit) \ .grid(row=3, column=1, sticky=E, padx=10, pady=5) mainloop()
5)输入框正确则保留,错误清空重新输入
from tkinter import * master = Tk() def test(): if e1.get() == "python": print("正确") return True else: print("错误") e1.delete(0,END) return False v = StringVar() e1 = Entry(master,textvariable=v,validate="focusout",validatecommand=test) e2 = Entry(master) e1.pack(padx = 10,pady=10) e2.pack(padx = 10,pady=10) mainloop()
6)函数调用使用
#-*-coding: utf-8 -*- from tkinter import * master = Tk() def test1(): if e1.get() == "python": print("正确") return True else: print("错误") e1.delete(0,END) return False def test2(): print("python被调用了") return True v = StringVar() e1 = Entry(master,textvariable=v,validate="focusout",\ validatecommand=test1,invalidcommand=test2) e2 = Entry(master) e1.pack(padx = 10,pady=10) e2.pack(padx = 10,pady=10) mainloop()
7)验证函数的额外选项
from tkinter import * master = Tk() v = StringVar() def test(content,reason,name): if content == "python": print("正确") print(content,reason,name) return True else: print("错误") print(content, reason, name) return False testCMD = master.register(test) e1 = Entry(master,textvariable=v,validate="focusout",\ validatecommand=(testCMD,'%P','%v','%W')) e2 = Entry(master) e1.pack(padx = 10,pady=10) e2.pack(padx = 10,pady=10) mainloop()
8)实现一个简单的加法计算器
from tkinter import * master = Tk() frame = Frame(master) frame.pack(padx=10,pady=10) v1 = StringVar() v2 = StringVar() v3 = StringVar() def test(content): return content.isdigit() testCMD = master.register(test) e1 = Entry(frame,width=10,textvariable=v1,validate="key",\ validatecommand=(testCMD,'%P')).grid(row=0,column=0) Label(frame,text="+").grid(row=0,column=1) e2 = Entry(frame,width=10,textvariable=v2,validate="key",\ validatecommand=(testCMD,'%P')).grid(row=0,column=2) Label(frame,text="=").grid(row=0,column=3) e3 = Entry(frame,width=10,textvariable=v3,state="readonly").grid(row=0,column=4) def calc(): result = int(v1.get()) + int(v2.get()) v3.set(str(result)) Button(frame,text='计算结果',command=calc).grid(row=1,column=2,pady=5) mainloop()
9)Listbox组件使用,引出滚动条
实现单一的删除操作
from tkinter import * master = Tk() theLB = Listbox(master) theLB.pack() for item in ['鸡蛋','鸭蛋','鹅蛋','狗蛋']: theLB.insert(END,item) theButton = Button(master, text="删除它",\ command = lambda x=theLB:x.delete(ACTIVE)) theButton.pack() # theLB.delete(0,END) # 全部删除 mainloop()
theLB = Listbox(master,selectmode=EXTENDED) # 多选 theLB = Listbox(master,selectmode=SINGLE) # 单选 theLB = Listbox(master,selectmode=SINGLE,height=15) # 增加高度
四、滚动条操作
1)Scrikkbar生成滚动条方法
from tkinter import * root = Tk() sb = Scrollbar(root) sb.pack(side=RIGHT,fill =Y) mainloop()
2)另一种 Scale增加精度的滚动条
from tkinter import * root = Tk() Scale(root,from_=0, to =42).pack() Scale(root,from_=0, to =200,orient = HORIZONTAL).pack() mainloop()
3)获取该精度的位置
from tkinter import * root = Tk() s1 = Scale(root,from_=0, to =42) s1.pack() s2 = Scale(root,from_=0, to =200,orient = HORIZONTAL) s2.pack() def show(): print(s1.get(),s2.get()) Button(root,text="获取位置",command =show).pack() mainloop()
4)精度的具体演示
from tkinter import * root = Tk() s1 = Scale(root,from_=0, to =42,tickinterval=5,resolution=5,length=200) s1.pack() s2 = Scale(root,from_=0, to =200,tickinterval=10,orient = HORIZONTAL,length=600) s2.pack() mainloop()
五、insert插入功能
1)插入文本
from tkinter import * root = Tk() text = Text(root, width=30, height=5) text.pack() text.insert(INSERT,"I love \n") text.insert(END,"YOU") def show(): print("我被点了一下") b1 = Button(text,text="点我啊",command=show) text.window_create(INSERT,window=b1)
2)插入图片
from tkinter import * root = Tk() text = Text(root, width=30, height=30) text.pack() phone = PhotoImage(file = "1.jpg") def show(): text.image_create(END,image=phone) b1 = Button(text,text="点我啊",command=show) text.window_create(INSERT,window=b1) mainloop()
3)指定位置改变字体颜色
from tkinter import * root = Tk() text = Text(root,width=30,height=5) text.pack() text.insert(INSERT,"I love FishC.com!") text.tag_add("tag1","1.7","1.12","1.14") text.tag_config("tag1",background="yellow",foreground="red") mainloop()
4)颜色覆盖,后者覆盖前者
from tkinter import * root = Tk() text = Text(root,width=30,height=5) text.pack() text.insert(INSERT,"I love FishC.com!") text.tag_add("tag1","1.7","1.12","1.14") text.tag_add("tag2","1.1","1.9","1.14") text.tag_config("tag1",background="yellow",foreground="red") text.tag_config("tag2",foreground="blue") mainloop()
5)绑定事件,超链接
from tkinter import * import webbrowser root = Tk() text = Text(root,width=30,height=5) text.pack() text.insert(INSERT,"I love FishC.com!") text.tag_add("link","1.7","1.16") text.tag_config("link",foreground="blue",underline=True) def show_arrow_cursor(event): text.config(cursor="arrow") def show_xterm_curror(event): text.config(cursor="xterm") def click(event): webbrowser.open("http://www.baidu.com") text.tag_bind("link","<Enter>",show_arrow_cursor) text.tag_bind("link","<Leave>",show_xterm_curror) text.tag_bind("link","<Button-1>",click) mainloop()
6)检查文本是否发生了变动
from tkinter import * import hashlib root = Tk() text = Text(root,width=30,height=5) text.pack() text.insert(INSERT,"I love FishC.com!") contents = text.get("1.0",END) def getSig(contents): m = hashlib.md5(contents.encode()) return m.digest() sig = getSig(contents) def check(): contents = text.get("1.0", END) if sig != getSig(contents): print("警报:内容发生变动") else: print("风平浪静") Button(root,text="检查",command=check).pack() mainloop()
7)对文本进行全局收索
from tkinter import * import hashlib root = Tk() text = Text(root,width=30,height=5) text.pack() text.insert(INSERT,"I love FishC.com!") def getIndex(start,index): return tuple(map(int,str.split(text.index(index),"."))) start = "1.0" while True: pos = text.search("o",start,stopindex=END) if not pos: break print("找到啦,位置是:",getIndex(text,pos)) start = pos + "+1c" mainloop()
8)撤销操作,自动插入分隔符
from tkinter import * root = Tk() text = Text(root,width=30,height=5,undo=True) text.pack() text.insert(INSERT,"I love FishC.com!") def show(): text.edit_undo() Button(root,text="撤销",command=show).pack() mainloop()
9)撤销,一个字符一个字符的删除
from tkinter import * root = Tk() text = Text(root,width=30,height=5,undo=True,autoseparators=False) # autoseparators 去销自动插入分隔符 text.pack() text.insert(INSERT,"I love FishC.com!") def callback(event): # 绑定事件需要加参数 text.edit_separator() # 人为的插入分割符 text.bind('<Key>',callback) def show(): text.edit_undo() Button(root,text="撤销",command=show).pack() mainloop()
原文链接:http://bbs.fishc.com/thread-59443-1-1.html