#示例1:主窗口及标题
import tkinter as tk
app = tk.Tk() #根窗口的实例(root窗口)
app.title('Tkinter root window') #根窗口标题
theLabel = tk.Label(app, text='我的第1个窗口程序!') #label组件及文字内容
theLabel.pack() #pack()用于自动调节组件的尺寸
app.mainloop() #窗口的主事件循环,必须的。
#示例2:按钮
import tkinter as tk
class APP:
def __init__(self, master): #root 传参赋值给master
frame = tk.Frame(master) #frame 组件
frame.pack(side=tk.LEFT, padx=10, pady=10)
self.hi_there = tk.Button(frame, text='打招呼', bg='black', fg='white', command=self.say_hi) #Button按钮, command中调用定义的方法
self.hi_there.pack()
def say_hi(self):
print('卧槽,居然打了个招呼!~')
root = tk.Tk()
app = APP(root)
root.mainloop()
#示例3:图片
from tkinter import *
root = Tk()
textLabel = Label(root,
text='请重试!\n您的操作不被允许!', #文字支持换行
justify=LEFT, #左对齐
padx=10, #左边距10px
pady=10) #右边距10px
textLabel.pack(side=LEFT)
#显示图片
photo = PhotoImage(file='tk_image.png')
imageLabel = Label(root, image=photo)
imageLabel.pack(side=RIGHT)
mainloop()
#示例4:背景
from tkinter import *
root = Tk()
photo = PhotoImage(file='tk4_bg.png')
theLabel = Label(root,
text='生存还是毁灭\n这是一个问题',
justify=LEFT,
image=photo,
compound=CENTER,
font=('华文隶书', 20),
fg='blue')
theLabel.pack()
mainloop()
#示例5:按钮交互
from tkinter import *
def callback():
var.set('吹吧你,我才不信呢!')
root = Tk()
frame1 = Frame(root)
frame2 = Frame(root)
var = StringVar()
var.set('请重试!\n您的操作不被允许!')
textLabel = Label(frame1,
textvariable=var,
justify=LEFT) #左对齐
textLabel.pack(side=LEFT)
#显示图片
photo = PhotoImage(file='tk_image.png')
imageLabel = Label(root, image=photo)
imageLabel.pack(side=RIGHT)
theButton = Button(frame2, text='我是超级管理员', command=callback)
theButton.pack()
frame1.pack(padx=10, pady=10)
frame2.pack(padx=10, pady=10)
mainloop()
#示例6:选项按钮
from tkinter import *
root = Tk()
v = IntVar()
c = Checkbutton(root, text='测试一下', variable=v) #v用来存放选中状态
c.pack()
l = Label(root, textvariable=v)
l.pack() #未选中显示为0,选中显示1
mainloop()
#示例7:多个方框选项
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) #设置对齐方位,东E南S西W北N
mainloop()
#示例8:多个圆点选项 Radiobutton
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='three', variable=v, value=3).pack(anchor=W)
Radiobutton(root, text='four', variable=v, value=4).pack(anchor=W)
mainloop()
#示例9:内陷填充按钮选项 Radiobutton indicatoron
from tkinter import *
root = Tk()
LANGS = [
('C', 1),
('C++', 2),
('shell', 3),
('python', 4)]
v = IntVar()
v.set(1)
for lang, num in LANGS: #对应列表中包含元组同时执行多个循环
b = Radiobutton(root, text=lang, variable=v, value=num, indicatoron=False)
b.pack(fill=X)
mainloop()
#示例10:附带标题的圆点选项 LabelFrame
from tkinter import *
root = Tk()
group = LabelFrame(root, text='最好的开发语言是?', padx=5, pady=5)
group.pack(padx=10, pady=10)
LANGS = [
('C', 1),
('C++', 2),
('shell', 3),
('python', 4)]
v = IntVar()
v.set(1)
for lang, num in LANGS: #对应列表中包含元组同时执行多个循环
b = Radiobutton(group, text=lang, variable=v, value=num)
b.pack(anchor=W)
mainloop()
#示例11:输入框 Entry
from tkinter import *
root = Tk()
e = Entry(root)
e.pack(padx=20, pady=20)
e.delete(0, END)
e.insert(0, '默认文本...')
mainloop()
#示例12:按钮和输入框交互
from tkinter import *
root = Tk()
root.title('输入框与按钮程序')
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)
#退出按钮必须是双击打开.py文件才可以,而不是在IDLE下调试运行时
mainloop()
#示例12:登陆框程序
from tkinter import *
root = Tk()
root.title('登陆程序')
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)
#退出按钮必须是双击打开.py文件才可以,而不是在IDLE下调试运行时
mainloop()
#示例13:输入对错验证程序
from tkinter import *
root = Tk()
root.title('输入对错验证')
def test():
if e1.get() == '张三':
print('正确!')
return True
else:
print('错误!')
e1.delete(0, END)
return False
v = StringVar()
#focusout指定在当前输入框失去焦点时,代表输入完,会去调用test校验
e1 = Entry(root, textvariable=v, validate='focusout', validatecommand=test)
e2 = Entry(root)
e1.pack(padx=10, pady=10)
e2.pack(padx=10, pady=10)
mainloop()
#示例13:简单计算器程序
from tkinter import *
root = Tk()
root.title('计算器程序')
frame = Frame(root)
frame.pack(padx=10, pady=10)
v1 = StringVar()
v2 = StringVar()
v3 = StringVar()
def test(content):
return content.isdigit()
testCMD = frame.register(test)
#focusout指定在当前输入框失去焦点时,代表输入完,会去调用test校验
e1 = Entry(frame, width=10, textvariable=v1, validate='key', \
validatecommand=(testCMD, '%P')).grid(row=0, column=0) #width的单位是字符数
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()
#示例14:按钮删除列表中的选项
from tkinter import *
master= Tk()
theLB = Listbox(master, selectmode=SINGLE, height=15) #SINGLE单选,MULTIPLE多选,height设置显示项数
theLB.pack()
for item in ['笔', '墨', '纸', '砚']:
theLB.insert(END, item) #END表示最后一个
for item in range(11):
theLB.insert(END, item)
theButton = Button(master, text='删除', \
command=lambda x=theLB:x.delete(ACTIVE) ) #ACTIVE表示当前选中的值
theButton.pack()
mainloop()
#示例15:为列表组件添加滚动条
#安装垂直滚动条步骤:
#1) 设置该组件的yscrollbarcommand选项为Scrollbar组件的set方法;
#2) 设置Scrollbar组件的command选项为该组件的yview()方法。
from tkinter import *
root = Tk()
root.title('滚动条程序')
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()
#示例16:滑块滚动条 Scale
from tkinter import *
root = Tk()
root.title('滑块程序')
s1 = Scale(root, from_=0, to=100, tickinterval=5, resolution=5, length=200) #默认是垂直, tickinterval精度刻度, length单位是像素
s1.pack()
s2 = Scale(root, from_=0, to=100, tickinterval=5, orient=HORIZONTAL, length=400)
s2.pack()
def show():
print(s1.get(), s2.get())
#获取滑块的当前位置,点击后才有效
Button(root, text='音量:', command=show).pack()
mainloop()
#示例17:文本组件 Text (插入按钮)
from tkinter import *
root = Tk()
root.title('Text')
text = Text(root, width=30, height=20)
text.pack()
#窗口中的文本可编辑
text.insert(INSERT, '这里是显示的文本信息内容。\n') #INSERT表示输入光标插入的位置
text.insert(END, '对比一下效果。')
def show():
print('提交中...') #此行内容显示在IDLE中
#插入一个Button组件
b1 = Button(text, text='提交', command=show)
text.window_create(INSERT, window=b1) #将b1插入
mainloop()
#示例18:文本组件 Text (插入图片)
from tkinter import *
root = Tk()
root.title('Text')
text = Text(root, width=50, height=15)
text.pack()
photo = PhotoImage(file="tk_image.png")
def show_img():
text.image_create(END, image=photo)
#插入一个图片
b1 = Button(text, text='插入图片', command=show_img)
text.window_create(INSERT, window=b1) #将b1插入
mainloop()
#示例19:文本组件 Text (Indexes:索引定位)
from tkinter import *
root = Tk()
root.title('Text')
text = Text(root, width=30, height=10)
text.pack()
text.insert(INSERT, 'I love baidu.com!')
text.tag_add('tag1', '1.7', '1.12', '1.14') #1.7~1.12 baidu 1.14 o
text.tag_add('tag2', '1.7', '1.12', '1.14')
text.tag_config('tag1', background='blue', foreground='yellow')
text.tag_config('tag2', foreground='red') #文字会以red为准
mainloop()
#示例20:文本组件中可点击连接
from tkinter import *
import webbrowser as wb
root = Tk()
root.title('GUI link show')
text = Text(root, width=30, height=5)
text.pack()
text.insert(INSERT, 'I love baidu.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):
wb.open('http://www.baidu.com')
#绑定事件
text.tag_bind('link', '
text.tag_bind('link', '
text.tag_bind('link', '
mainloop()
#示例21:文本组件之MD5
from tkinter import *
import hashlib #用于获取文件的MD5值,检查内容是否有修改
root = Tk()
root.title('link click')
text = Text(root, width=50, height=10)
text.pack()
text.insert(INSERT, 'I love www.baidu.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()
#示例22:文本组件之全文搜索
from tkinter import *
root = Tk()
root.title('link click')
text = Text(root, width=50, height=10)
text.pack()
text.insert(INSERT, 'I love www.baidu.com')
def getIndex(text, index):
return tuple(map(int, str.split(text.index(index), '.')))
start = '1.0' #开头的位置,第1行的第0个下标位置
while True:
pos = text.search('o', start, stopindex=END) #查找文本中字符o的位置
if not pos:
break
print('找到啦,位置是:', getIndex(text, pos))
start = pos + '+1c' #'+1c'指向下一个字符
mainloop()
#示例23:文本组件之撤销操作
from tkinter import *
root = Tk()
root.title('link click')
text = Text(root, width=50, height=10, undo=True) #undo模式开启
text.pack()
text.insert(INSERT, 'I love www.baidu.com')
def show():
text.edit_undo()
Button(root, text='撤销', command=show).pack() #多次撤销会删除文本组件内的内容
mainloop()
#示例24:绘制组件 Canvas
from tkinter import *
root = Tk()
root.title('Canvas')
w = Canvas(root, width=500, height=300) #background='black' 改变背景色
w.pack()
#黄色的矩形
w.create_rectangle(50, 50, 450, 250, fill='yellow') #参数:左边距, 上边距, 宽, 高
#红色的横线
w.create_line(0, 300//2, 500, 300//2, fill='red')
#蓝色的竖虚线
w.create_line(500//2, 0, 500//2, 300, fill='blue', dash=(4, 4)) #dash 虚线
mainloop()
#示例25:绘制组件 Canvas (修改和删除图形)
from tkinter import *
root = Tk()
root.title('Canvas')
w = Canvas(root, width=500, height=300) #background='black' 改变背景色
w.pack()
rect1 = w.create_rectangle(50, 50, 450, 250, fill='yellow') #参数:左边距, 上边距, 宽, 高
line1 = w.create_line(0, 300//2, 500, 300//2, fill='red')
line2 = w.create_line(500//2, 0, 500//2, 300, fill='blue', dash=(4, 4)) #dash 虚线
w.coords(line1, 0, 25, 500, 25) #移动位置
w.itemconfig(rect1, fill='red')
w.delete(line2)
Button(root, text='删除全部', command=(lambda x=ALL:w.delete(x))).pack()
mainloop()
#示例26:绘制组件 Canvas (图形正中心)
from tkinter import *
root = Tk()
root.title('Canvas')
w = Canvas(root, width=600, height=300)
w.pack()
line1 = w.create_line(0, 0, 600, 300, fill='green', width=3)
line1 = w.create_line(600, 0, 0, 300, fill='green', width=3)
rect1 = w.create_rectangle(60, 30, 540, 270, fill='green')
rect2 = w.create_rectangle(120, 60, 480, 240, fill='yellow')
w.create_text(300, 150, text='Hello, python!')
mainloop()
#示例27:绘制组件 Canvas (椭圆和圆形)
from tkinter import *
root = Tk()
root.title('Canvas')
w = Canvas(root, width=600, height=300)
w.pack()
w.create_rectangle(60, 30, 540, 270, dash=(4, 4))
w.create_oval(60, 30, 540, 270, fill='pink') #椭圆是通过限定矩形的方式画出来,圆形通过正方形
#w.create_oval(60, 30, 300, 270, fill='pink') #正方形对应正圆(60-300=30-270)
w.create_text(300, 150, text='wow~')
mainloop()
#示例28:绘制组件 Canvas (五角星)
from tkinter import *
import math as m #用到sin和cos数学函数
root = Tk()
root.title('Canvas')
w = Canvas(root, width=600, height=300, background='red')
w.pack()
center_x = 300
center_y = 150
r = 150
points = [
#左上点
center_x - int(r * m.sin(2 * m.pi / 5)),
center_y - int(r * m.cos(2 * m.pi / 5)),
#右上点
center_x + int(r * m.sin(2 * m.pi / 5)),
center_y - int(r * m.cos(2 * m.pi / 5)),
#左下点
center_x - int(r * m.sin(m.pi / 5)),
center_y + int(r * m.cos(m.pi / 5)),
#顶点
center_x,
center_y - r,
#右下点
center_x + int(r * m.sin(m.pi / 5)),
center_y + int(r * m.cos(m.pi / 5)),
]
w.create_polygon(points, outline='yellow', fill='yellow') #polygon多边形
mainloop()
#示例29:绘制组件 Canvas (自定义画板)
#绘制一个极小的圆来代表一个点(tkinter本身不支持画点)
from tkinter import *
root = Tk()
root.title('Canvas draw tool')
w = Canvas(root, width=400, height=200, background='white')
w.pack()
def paint(event):
x1, y1 = (event.x - 1), (event.y - 1)
x2, y2 = (event.x + 1), (event.y + 1)
w.create_oval(x1, y1, x2, y2, fill='red')
w.bind('
Label(root, text='按住鼠标左键并移动,开始绘制吧!~~').pack(side=BOTTOM)
mainloop()
#示例30:菜单组件框架 Menu (主菜单/下拉菜单/右键菜单/单多选菜单/按钮菜单/选项菜单(列表))
from tkinter import *
root = Tk()
root.title('Main Menu Show')
def callback():
print('你好~')
menubar = Menu(root)
#注册菜单:文件(下拉菜单)
filemenu = Menu(menubar, tearoff=False) #来自主菜单,tearoff参数可让菜单窗口分离
filemenu.add_command(label='新建', command=callback)
filemenu.add_command(label='打开...', command=callback)
filemenu.add_separator() #分割线
filemenu.add_command(label='保存', command=callback)
filemenu.add_separator() #分割线
filemenu.add_command(label='退出', command=root.quit)
menubar.add_cascade(label='文件(W)', menu=filemenu)
#主菜单:编辑(下拉菜单)
editmenu = Menu(menubar, tearoff=False) #来自主菜单
editmenu.add_command(label='撤销', command=callback)
editmenu.add_command(label='重做', command=callback)
editmenu.add_separator() #分割线
editmenu.add_command(label='剪切', command=callback)
editmenu.add_command(label='复制', command=callback)
editmenu.add_command(label='粘贴', command=callback)
editmenu.add_separator() #分割线
editmenu.add_command(label='全选', command=callback)
editmenu.add_separator() #分割线
editmenu.add_command(label='查找...', command=callback)
menubar.add_cascade(label='编辑(B)', menu=editmenu)
#主菜单:多选√ checkbutton(下拉菜单)
openVar = IntVar()
saveVar = IntVar()
quitVar = IntVar()
optionmenu = Menu(menubar, tearoff=False)
optionmenu.add_checkbutton(label='多选项1', command=callback, variable=openVar)
optionmenu.add_checkbutton(label='多选项2', command=callback, variable=saveVar)
optionmenu.add_checkbutton(label='多选项3', command=callback, variable=quitVar)
menubar.add_cascade(label='选项(C)', menu=optionmenu)
#主菜单:单选√ radiobutton(下拉菜单)
otherVar = IntVar()
othermenu = Menu(menubar, tearoff=False)
othermenu.add_radiobutton(label='单选项1', command=callback, variable=otherVar, value=1)
othermenu.add_radiobutton(label='单选项2', command=callback, variable=otherVar, value=2)
othermenu.add_radiobutton(label='单选项3', command=callback, variable=otherVar, value=3)
menubar.add_cascade(label='其他(C)', menu=othermenu)
#内部菜单:按钮菜单 Menubutton
mb = Menubutton(root, text='按钮菜单...', relief=RAISED)
mb.pack()
openVar = IntVar()
saveVar = IntVar()
quitVar = IntVar()
optionmenu = Menu(mb, tearoff=False)
optionmenu.add_checkbutton(label='test', command=callback, variable=openVar)
optionmenu.add_checkbutton(label='test', command=callback, variable=saveVar)
optionmenu.add_checkbutton(label='test', command=callback, variable=quitVar)
mb.config(menu=optionmenu)
#内部菜单:选项菜单 OptionMenu
variable = StringVar()
variable.set('one') #默认显示one
w = OptionMenu(root, variable, 'one', 'two', 'three')
w.pack()
#将列表添加到选项菜单 OptionMenu
OPTIONS = [
'表项1',
'对比2',
'选项3',
'其他4',
'退出5'
]
var = StringVar()
var.set(OPTIONS[0])
o = OptionMenu(root, var, *OPTIONS) #*星号解包可变参数列表为逐个元素
o.pack()
#主菜单:帮助
helpmenu = Menu(menubar, tearoff=False)
helpmenu.add_separator() #分割线
helpmenu.add_command(label='关于...', command=callback)
helpmenu.add_separator() #分割线
menubar.add_cascade(label='帮助(F1)', menu=helpmenu)
#弹出菜单(暂用编辑菜单作为右键)
frame = Frame(root, width=500, height=200)
frame.pack()
def popup(event):
editmenu.post(event.x_root, event.y_root)
frame.bind('
root.config(menu=menubar) #menu参数会将菜单设置添加到root根窗口
mainloop()
#示例31:事件绑定 bind (鼠标/按键/按键组合)
from tkinter import *
root = Tk()
root.title('Event bind')
frame = Frame(root, width=200, height=200)
#鼠标响应事件
def callback1(event): #event形参获取事件描述,必备参数
print('点击位置:', event.x, event.y)
frame.bind('
frame.pack()
#键盘响应事件
def callback2(event):
print(event.keysym) #打印信息在IDLE, keysym指键盘所有按键
frame.bind('
frame.focus_set()
frame.pack()
#鼠标即时响应事件
def callback3(event):
print('点击位置:', event.x, event.y)
frame.bind('
frame.pack()
#事件序列(按键组合),语法:
#点击鼠标左键:
#点击H字母按键:
#同时点击Ctrl+Shift+H:
mainloop()
#示例32:消息组件 Message | 输入组件 Spinbox
from tkinter import *
root = Tk()
root.title('Module')
#消息组件:Message
m1 = Message(root, text='这是一个消息:', width=100)
m1.pack()
m2 = Message(root, text='这是一\n则骇人听闻的长长长长长长长消息!', width=100)
m2.pack()
#输入组件:Spinbox (可指定输入范围)
s1 = Spinbox(root, from_=0, to=5)
s1.pack()
s2 = Spinbox(root, values=('zero', 'one', 'two', 'three', 'four', 'five'))
s2.pack()
mainloop()
#示例33:窗口布局管理器 PanedWindow
from tkinter import *
root = Tk()
root.title('Module')
#二窗格
'''
p = PanedWindow(orient=VERTICAL)
p.pack(fill=BOTH, expand=1)
top = Label(p, text='top pane')
p.add(top)
bottom = Label(p, text='bottom pane')
p.add(bottom)
'''
#三窗格,同时显示隐藏布局线(showhandle=True, sashrelief=SUNKEN)
p = PanedWindow(showhandle=True, sashrelief=SUNKEN)
p.pack(fill=BOTH, expand=1)
left = Label(p, text='left pane')
p.add(left)
q = PanedWindow(orient=VERTICAL, showhandle=True, sashrelief=SUNKEN)
p.add(q)
top = Label(q, text='top pane')
q.add(top)
bottom = Label(q, text='bottom pane')
q.add(bottom)
mainloop()
#示例34:容器组件 Toplevel (创建顶级窗口,即弹出窗口)
from tkinter import *
root = Tk()
root.title('Toplevel')
def create():
top = Toplevel()
#top.attributes('-alpha', 0.5) 设置弹出的顶级窗口透明度:50%
top.title('Toplevel demo...')
msg = Message(top, text='I love python...')
msg.pack()
Button(root, text='创建顶级窗口', command=create).pack() #点击出现顶级窗口
mainloop()
#示例35:几何管理类,包pack(),网格grid(),位置place()
#pack() 注意pack和grid不要混合使用
from tkinter import *
root = Tk()
root.title('pack')
#Listbox完全填充测试
listbox = Listbox(root)
listbox.pack(fill=BOTH, expand=True) #fill=BOTH将窗口填满
for i in range(10):
listbox.insert(END, str(i))
#Label纵向填充
Label(root, text='red', bg='red', fg='white').pack(fill=X)
Label(root, text='green', bg='green', fg='black').pack(fill=X)
Label(root, text='blue', bg='blue', fg='white').pack(fill=X)
#Label横向填充
Label(root, text='red', bg='red', fg='white').pack(side=LEFT)
Label(root, text='green', bg='green', fg='black').pack(side=LEFT)
Label(root, text='blue', bg='blue', fg='white').pack(side=LEFT)
mainloop()
#示例35:几何管理类,包pack(),网格grid(),位置place()
#grid() 注意pack和grid不要混合使用
from tkinter import *
root = Tk()
root.title('grid')
#两个sticky=W实现第一列左对齐
Label(root, text='用户名').grid(row=0, sticky=W)
Label(root, text='密码').grid(row=1, sticky=W)
#rowspan=2可以让图片横跨2行
photo = PhotoImage(file='tk_image.png')
Label(root, image=photo).grid(row=0, column=2, rowspan=2, padx=5, pady=5)
Entry(root).grid(row=0, column=1)
Entry(root, show='*').grid(row=1, column=1)
def callback():
print('登陆中...')
#columnspan=3可以让按钮横跨3列
Button(text='提交', width=10, command=callback).grid(row=2, columnspan=3, pady=5)
mainloop()
#示例35:几何管理类,包pack(),网格grid(),位置place()
#place() 可以实现一些pack和grid实现不了的布局
from tkinter import *
root = Tk()
root.title('place')
#place位置布局测试
'''
photo = PhotoImage(file='tk_image.png')
Label(root, image=photo).pack() #按钮就会出现在图片的组件上,实现组件叠加显示
def callback():
print('正中靶心!!!')
#relx,rely相对父组件root的位置,0.5正中间,1最右边,0最左边,anchor=CENTER居中显示
Button(root, text='射击', command=callback).place(relx=0.5, rely=0.5, anchor=CENTER)
'''
Label(root, bg='red').place(relx=0.5, rely=0.5, relheight=0.75, relwidth=0.75, anchor=CENTER)
Label(root, bg='yellow').place(relx=0.5, rely=0.5, relheight=0.5, relwidth=0.5, anchor=CENTER)
Label(root, bg='blue').place(relx=0.5, rely=0.5, relheight=0.25, relwidth=0.25, anchor=CENTER)
mainloop()
#示例35:对话框 (警告 showinfo | 消息 messagebox | 文件 filedialog | 颜色 colorchooser)
from tkinter import *
from tkinter import messagebox #messagebox()需要单独导入
from tkinter import filedialog #filedialog()需要单独导入
from tkinter import colorchooser #colorchooser()需要单独导入
from tkinter.messagebox import * #用户使用showinfo()
#警告对话框
showinfo(title='test', message='警告')
#消息对话框
result = messagebox.askokcancel('demo', '发射核弹?') #返回值是True或False
print(result) #根据用户按下了确定还是取消做进一步的操作
#文件对话框
root = Tk()
def callback1():
filename = filedialog.askopenfilename(defaultextension='.py') #指定文件后缀
print(filename) #返回的是文件的完整路径
Button(root, text='打开文件', command=callback1).pack()
#颜色选择对话框
def callback2():
color_data = colorchooser.askcolor() #调用windows的颜色选择器
print(color_data) #选择红色打印:((255.99609375, 0.0, 0.0), '#ff0000')
Button(root, text='选择颜色', command=callback2).pack()
mainloop()