1.最简单的程序
# -*- coding: utf-8 -*-
import Tkinter as tk
app = tk.Tk()
app.title("FishC Demo")
theLabel = tk.Label(app,text = "窗口测试程序!")
theLabel.pack()
app.mainloop()
2.窗口中增加处理函数
# -*- coding: utf-8 -*-
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 = "black",fg = "white",command=self.say_hi)
self.hi_there.pack()
def say_hi(self):
print "大家好,我是antenna!"
root = tk.Tk()
app = App(root)
root.mainloop()
3.窗口中增加图片
# -*- coding: utf-8 -*-
#import Tkinter as tk
from Tkinter import *
root = Tk()
textLabel = Label(root,
text = "您所下载的影片含有未成年人限制内容,\n请满18周岁后再点击观看。",
justify = LEFT,
padx = 10)
textLabel.pack(side = LEFT)
photo = PhotoImage(file="18.gif")
imgLabel = Label(root,image=photo)
imgLabel.pack()
mainloop()
4.字体设置,图文混排
# -*- coding: utf-8 -*-
from Tkinter import *
root = Tk()
photo = PhotoImage(file="18.gif")
textLabel = Label(root,
text = "学python到fishC",
justify = LEFT,
image = photo,
compound = CENTER,
font = ("楷体",20),
fg = "black")
textLabel.pack()
mainloop()
5.交互变化
# -*- coding: utf-8 -*-
#import Tkinter as tk
from Tkinter import *
def callback():
var.set("吹吧你,我才不信呢~")
root = Tk()
frame1 = Frame(root)
frame2 = Frame(root)
var = StringVar()
var.set("您所下载的影片含有未成年人限制内容,\n请满18周岁后再点击观看。")
textLabel = Label(frame1,
textvariable = var,
justify = LEFT,
padx = 10)
textLabel.pack(side = LEFT)
photo = PhotoImage(file="18.gif")
imgLabel = Label(frame1,image=photo)
imgLabel.pack(side = RIGHT)
theButton = Button(frame2,text="我已满18周岁",command=callback)
theButton.pack()
frame1.pack(padx=10,pady=10)
frame2.pack(padx=10,pady=10)
mainloop()
6.check控件
# -*- coding: utf-8 -*-
from Tkinter import *
root = Tk()
v = IntVar()
c = Checkbutton(root,text="测试",variable=v)
c.pack()
l = Label(root,textvariable=v)
l.pack()
mainloop()
7.通过列表加入checkbutton
# -*- coding: utf-8 -*-
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()
8.Radiobutton
# -*- coding: utf-8 -*-
from Tkinter import *
root = Tk()
GIRLS = ["西施","貂蝉","王昭君","杨玉环"]
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="Three",variable=v,value=3).pack(anchor=W)
mainloop()
9.Radiobutton按钮填充
# -*- coding: utf-8 -*-
from Tkinter import *
root = Tk()
LANGS = [
("Python",1),
("Perl",2),
("Ruby",3),
("Lua",4)]
v = IntVar()
v.set(1)
for lang,num in LANGS:
#1. b = Radiobutton(root,text=lang,variable=v,value=num)
b = Radiobutton(root,text=lang,variable=v,value=num,indicatoron=False)
#1. b.pack(anchor=W)
b.pack(fill=X)
mainloop()
10.加LabelFrame
# -*- coding: utf-8 -*-
from Tkinter import *
root = Tk()
group = LabelFrame(root,text="最好的脚本语言是?",padx=5,pady=5)
group.pack(padx=10,pady=10)
LANGS = [
("Python",1),
("Perl",2),
("Ruby",3),
("Lua",4)]
v = IntVar()
for lang,num in LANGS:
b = Radiobutton(group,text=lang,variable=v,value=num)
b.pack(anchor=W)
mainloop()
11.文本输入框
# -*- coding: utf-8 -*-
from Tkinter import *
root = Tk()
e = Entry(root)
e.pack(padx=20,pady=20)
e.delete(0,END)
e.insert(0,"默认文本。。。")
mainloop()
12.交互文本输入
# -*- coding: utf-8 -*-
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 u"作品:《%s》" % e1.get()
print u"作者:%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()
13.账号密码登陆框
# -*- coding: utf-8 -*-
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 u"账号:%s" % e1.get()
print u"密码:%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()
14.输入后焦点改变判断输入内容
# -*- coding: utf-8 -*-
from Tkinter import *
master = Tk()
def test():
if e1.get()==u"小甲鱼":
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()
15.判断输入内容并调用函数
# -*- coding: utf-8 -*-
from Tkinter import *
master = Tk()
v = StringVar()
def test1():
if v.get()==u"小甲鱼":
print "正确!"
return True
else:
print "错误!"
e1.delete(0,END)
return False
def test2():
print "我被调用了。。。"
return True
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()
16.判断输入内容调用函数,显示参数
# -*- coding: utf-8 -*-
from Tkinter import *
master = Tk()
v = StringVar()
def test(content,reason,name):
if content==u"小甲鱼":
print "正确!"
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()
17.计算器
# -*- coding: utf-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,textvariable=v1,validate="key",validatecommand=(testCMD,"%P")).grid(row=0,column=0)
Label(frame,text="+").grid(row=0,column=1)
e2 = Entry(frame,textvariable=v2,validate="key",validatecommand=(testCMD,"%P")).grid(row=0,column=2)
Label(frame,text="=").grid(row=0,column=3)
e3 = Entry(frame,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()
18.listbox
# -*- coding: utf-8 -*-
from Tkinter import *
master = Tk()
theLB = Listbox(master,selectmode=EXTENDED)
theLB.pack()
for item in ["鸡蛋","鸭蛋","鹅蛋","李狗蛋"]:
theLB.insert(END,item)
theButton = Button(master,text="删除它",\
command=lambda x=theLB:x.delete(ACTIVE))
theButton.pack()
mainloop()
19.listbox中加滚动条
# -*- coding: utf-8 -*-
from Tkinter import *
root = Tk()
sb = Scrollbar(root)
sb.pack(side = RIGHT,fill=Y)
lb = Listbox(root,yscrollcommand=sb.set)
for i in range(1000):
lb.insert(END,i)
lb.pack(side=LEFT,fill=BOTH)
sb.config(command=lb.yview)
mainloop()
20.加scale条
# -*- coding: utf-8 -*-
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()
21.scale条加参数
# -*- coding: utf-8 -*-
from Tkinter import *
root = Tk()
Scale(root,from_=0,to=42,tickinterval=5,resolution=5,length=200).pack()
Scale(root,from_=0,to=200,tickinterval=10,orient=HORIZONTAL,length=600).pack()
mainloop()
22.text框
# -*- coding: utf-8 -*-
from Tkinter import *
root = Tk()
text = Text(root,width=30,height=2)
text.pack()
text.insert(INSERT,"I love\n")
text.insert(END,"FishC.com!")
mainloop()
23.text控件中加button
# -*- coding: utf-8 -*-
from Tkinter import *
root = Tk()
text = Text(root,width=30,height=5)
text.pack()
text.insert(INSERT,"I love\n")
text.insert(END,"FishC.com!")
def show():
print("呦,我被点了一下~")
b1 = Button(text,text="点我点我",command=show)
text.window_create(INSERT,window=b1)
mainloop()
24.文本框控件中增加图片
# -*- coding: utf-8 -*-
from Tkinter import *
root = Tk()
text = Text(root,width=30,height=5)
text.pack()
photo = PhotoImage(file="fishc.gif")
def show():
text.image_create(END,image=photo)
b1 = Button(text,text="点我点我",command=show)
text.window_create(INSERT,window=b1)
mainloop()
25.tag
# -*- coding: utf-8 -*-
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.7","1.12","1.14")
text.tag_config("tag1",background="yellow",foreground="red")
text.tag_config("tag2",foreground="blue")
mainloop()
26.tag2
# -*- coding: utf-8 -*-
from Tkinter import *
root = Tk()
text = Text(root,width=30,height=5)
text.pack()
text.tag_config("tag1",background="yellow",foreground="red")
text.tag_config("tag2",foreground="blue")
text.tag_lower("tag2")
text.insert(INSERT,"I love FishC.com",("tag2","tag1"))
mainloop()
27.绑定事件
# -*- coding: utf-8 -*-
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_cursor(event):
text.config(cursor="xterm")
def click(event):
webbrowser.open("http://www.fishc.com")
text.tag_bind("link","",show_arrow_cursor)
text.tag_bind("link","",show_xterm_cursor)
text.tag_bind("link","",click)
mainloop()
28.检查文本内容是否改变
# -*- coding: utf-8 -*-
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()
29.文本框控件内查找
# -*- coding: utf-8 -*-
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(text,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 "找到啦,位置是:" + str(getIndex(text,pos))
start = pos + "+1c"
mainloop()
30.撤销操作
# -*- coding: utf-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()
31.逐个字母撤销
# -*- coding: utf-8 -*-
from Tkinter import *
root = Tk()
text = Text(root,width=30,height=5,undo=True,autoseparators=False)
text.pack()
text.insert(INSERT,"I love FishC.com!")
def callback(event):
text.edit_separator()
text.bind('',callback)
def show():
text.edit_undo()
Button(root,text="撤销",command=show).pack()
mainloop()
32.canvas画线和矩形
# -*- coding: utf-8 -*-
from Tkinter import *
root = Tk()
w = Canvas(root,width=200,height=100,background="white")
w.pack()
w.create_line(0,50,200,50,fill="yellow")
w.create_line(100,0,100,100,fill="red",dash=(4,4))
w.create_rectangle(50,25,150,75,fill="blue")
mainloop()
33.canvas动态处理
# -*- coding: utf-8 -*-
from Tkinter import *
root = Tk()
w = Canvas(root,width=200,height=100,background="white")
w.pack()
line1 = w.create_line(0,50,200,50,fill="yellow")
line2 = w.create_line(100,0,100,100,fill="red",dash=(4,4))
rect1 = w.create_rectangle(50,25,150,75,fill="blue")
w.coords(line1,0,25,200,25)
w.itemconfig(rect1,fill = "red")
w.delete(line2)
Button(root,text="删除全部",command=(lambda x=ALL:w.delete(x))).pack()
mainloop()
34.线条、矩形、文本混排
# -*- coding: utf-8 -*-
from Tkinter import *
root = Tk()
w = Canvas(root,width=200,height=100)
w.pack()
w.create_line(0,0,200,100,fill="green",width=3)
w.create_line(200,0,0,100,fill="green",width=3)
w.create_rectangle(40,20,160,80,fill="green")
w.create_rectangle(65,35,135,65,fill="yellow")
w.create_text(100,50,text="FishC")
mainloop()
35.椭圆
# -*- coding: utf-8 -*-
from Tkinter import *
root = Tk()
w = Canvas(root,width=200,height=100)
w.pack()
w.create_rectangle(40,20,160,80,dash=(4,4))
w.create_oval(40,20,160,80,fill="pink")
w.create_text(100,50,text="FishC")
mainloop()