python-tkinter模块

  1. tkinter介绍
#Tkinter是GUI默认库
import tkinter as tk

#生成一个top level顶级窗口
app = tk.Tk()#root窗口 实例化一个窗口
app.title('bat fei')

theLabel = tk.Label(app, text = '第二个窗口程序')#最常用的主键之一,用于显示文本或图标
theLabel.pack()#自动调节主键的尺寸

app.mainloop()#进入主事件循环


滚动条
1. 设置该组件的yscrollbarcommand选项为Scrollbar组件的set()方法
2. 设置Scrollbar组件的command选项为该组件的yview()方法

Canvas组件支持的对象
	arc(弧形,弦或扇形)
	bitmap(内建的位图文件或XBM格式的文件)
	image(BitmapImage或PhotoImage的实例对象)
	line(线)
	oval(圆或椭圆)
	polygon(多边形)
	rectangle(矩形)
	text(文件)
	window(组件)
	

事件序列 <modifier-type-detail>
	用户需要使用bind()方法将具体序列与自定义的方法相绑定,事件序列是以字符串形式
	表示,可以表示一个或多个相关联的事件(如果是多个事件,那么对应的方法只有在满足所有事件的前提下才会被调用)

	事件序列是包含在尖括号(<...>)中
	type部分内容最重要,是事件类型
	modifier可选,通常用于描述组合键
	detail可选,描述具体的按键
	
	<Button-1> 用户点击鼠标左键
	<KeyPress-H> 用户点击H键
	<Control-Shift-KeyPress-H> 用户同时点击Ctrl+Shift+H
	
Message组件

Spinbox组件
	
#Tkinter是GUI默认库
import tkinter as tk

#生成一个top level顶级窗口
app = tk.Tk()#root窗口 实例化一个窗口
app.title('bat fei')

theLabel = tk.Label(app, text = '第二个窗口程序')#最常用的主键之一,用于显示文本或图标
theLabel.pack()#自动调节主键的尺寸

app.mainloop()#进入主事件循环
  1. 加载图片
#加载图片
from tkinter import *

root = Tk()

photo = PhotoImage(file = 'bg.gif')#gif格式
theLabel = Label(root,
                 text='学 Pyhon\n由嵌入神',
                 justify=LEFT,
                 image = photo,
                 compound=CENTER,
                 font=('华康少女字体',20),
                 fg='white')
theLabel.pack()

def callback():
    var.set('hihi hi hello')

frame1 = Frame(root)
frame2 = Frame(root)


var = StringVar()
var.set('hello world')

textLabel = Label(frame1,
                  textvariable = var,
                  justify=LEFT)
textLabel.pack()


theButton = Button(frame2,text='hi',command = callback)
theButton.pack()
frame1.pack(padx=10,pady=20)
frame2.pack(padx=10,pady=20)
mainloop()

  1. 多选框
from tkinter import *
##
root = Tk()
##
##v = IntVar()
##
##c = Checkbutton(root,text='test',variable=v)
##c.pack()
##
##l = Label(root,textvariable=v)#默认为0选中为1
##l.pack()


#选牌子
##GIRLS=['xishi','diaochan','wanghzaojun','yangyuhuan']
##
##v = []
##
##for girl in GIRLS:
##    v.append(IntVar())
##    b = Checkbutton(root,text=girl,variable = v[-1])#每一次拿到最后一个元素
##    b.pack(anchor ='w')#位置左对齐 n sw
##    
##    l = Label(root,textvariable=v[-1])#默认为0选中为1
##    l.pack()
##

#单选
##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')

#列表单选
##LANGS=[('python',1),('java',2),('ruby',3),('lua',4),('php',5)]
##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(anchor='w')
##    b.pack(fill=X)#变成按钮横向填充


#放到问题框中

##group = LabelFrame(root,text='最好的脚本语言是?',padx=10,pady=10)
##group.pack(padx=10,pady=10)
##
##LANGS=[('python',1),('java',2),('ruby',3),('lua',4),('php',5)]
##v = IntVar()
##
##for lang,num in LANGS:
##    b = Radiobutton(group,text=lang,variable = v,value=num)
##    b.pack(anchor='w')


#输入框

##e = Entry(root)
##e.pack(padx=20,pady=20)
##
##e.delete(0,END)#清空文本
##e.insert(0,'默认文本...')


#例子

##Label(root,text='作品:').grid(row=0,column=0)
##Label(root,text='作者:').grid(row=1,column=0)
##
##
##e1 = Entry(root)
##e2 = Entry(root)#可以以密码形式显示 ,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)#quit和idle冲突,运行.py文件即可

#验证函数

##def test():
##    if e1.get() == '小陈':
##        print("正确")
##        return True
##    else:
##        print("错误")
##        e1.delete(0,END)
##        return False
##
##v = StringVar()




mainloop()



  1. listbox
#listbox
from tkinter import *

master = Tk()

#该组件,可以多选SINGLE;MULTIPLE;EXTENDED,默认有10行,可以添加滚动条
theLS = Listbox(master,selectmode=EXTENDED)
theLS.pack()

##theLS.insert(0,"01zhaoyun")
##theLS.insert(END,"02zhangfei")
#迭代加入
items = ['---01---','---02---','---03---','---04---','---05---']
for item in items:
    theLS.insert(END,item)

#删除用户选中的
theButton = Button(master,text='删除该项',command=lambda x=theLS:x.delete(ACTIVE))
theButton.pack()


mainloop()

  1. 滚动条Scrollbar
##06滚动条Scrollbar()
from tkinter import *

root = Tk()

#Scrollbar

##sb = Scrollbar(root)
##sb.pack(side=RIGHT,fill=Y)
##
##lb = Listbox(root,yscrollcommand=sb.set)
##
##for i in range(200):
##    lb.insert(END,i)
##
##lb.pack(side=LEFT,fill=BOTH)
##
##sb.config(command=lb.yview)

#Scale

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()
#控制精度 步长 tickinterval=5,resolution=5,length=200
#resolution:步长固定一次走一个步长
def show():
    print(s1.get(),s2.get())

Button(root,text='获取位置',command=show).pack()

mainloop()

  1. 文本text
#Text组件 显示多行文本
from tkinter import *
import hashlib

root = Tk()

##text = Text(root,width = 30, height = 5)
##text.pack()

##text.insert(INSERT, 'hello\n')
##text.insert(END,'world')

##def show():
##    print("被点!")
##
##b1 = Button(text, text='点我',command=show)
##b1.pack()
##text.window_create(INSERT,window=b1)


#点一次插入图片

##photo = PhotoImage(file='bg.gif')
##
##def show():
##    text.image_create(END,image=photo)
##
##b1 = Button(text, text='点我',command=show)
##b1.pack()
##text.window_create(INSERT,window=b1)

#检查文本变化

##text.insert(INSERT,'i love bat.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()


#search

##text = Text(root,width=30,height=5)
##text.pack()
##
##text.insert(INSERT,'I love bat.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('找到,位置是:',getIndex(text,pos))
##    start = pos + "+1c"#下一个字符
    

#撤销 恢复

##text = Text(root,width=30,height=5,undo=True)#打开撤销功能##text.pack()
##
##text.insert(INSERT,'I love bat.com')
##
##def show():
##    text.edit_undo()
##
##Button(root,text='撤销',command=show).pack()

#一次性撤销关闭自定义autoseparators

text = Text(root,width=30,height=5,undo=True,autoseparators=False)#打开撤销功能,
text.pack()

text.insert(INSERT,'I love bat.com')

def callback(event):
    text.edit_separator()

text.bind('<Key>',callback)#每当有按键插入的时候就插入一个分隔符

def show():
    text.edit_undo()

Button(root,text='撤销',command=show).pack()

mainloop()

  1. 画布Canvas
#创建画布Canvas
from tkinter import *
import math as m

root = Tk()

w = Canvas(root, width=200,height = 100)#,backgroud='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')

#进行修改
##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()

#画布上加文本
##w.create_line(0,0,200,100,fill='green',width=3)
##w.create_line(200,0,0,100,fill='red',width=3)
##w.create_rectangle(40,20,150,75,fill='green')
##w.create_rectangle(50,25,150,75,fill='yellow')
##
##w.create_text(100,50,text='love')

#椭圆#⚪就是特殊的椭圆
##w.create_rectangle(40,20,160,80,fill='green',dash=(4,4))
##w.create_oval(40,20,160,80,fill='pink')
##
##w.create_text(100,50,text='love')


#创建五角星
##center_x = 100
##center_y = 50
##r = 50
##
##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))
##    #左下点
##    #顶点
##    #右下点
##    ]
##w.create_polygon(points,outline='green',fill='yellow')

#实现画笔
##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('<B1-Motion>',paint)
##
##Label(root,text='按住鼠标左键并移动,实现画笔').pack(side=BOTTOM)

mainloop()

  1. 菜单Menu
#菜单 menu
from tkinter import *

root = Tk()


#顶级菜单
def callback():
    print('hello')
menubar = Menu(root)

##menubar.add_command(label='hello',command = callback)
##menubar.add_command(label = 'quit',command=root.quit)
##root.config(menu=menubar)


#创建file菜单,edit菜单

##filemenu = Menu(menubar,tearoff=False)#tearoff默认位true撕开新的
##filemenu.add_command(label='打开',command=callback)
##filemenu.add_command(label='保存',command = callback)
##filemenu.add_separator()
##filemenu.add_command(label='退出',command=root.quit)
##menubar.add_cascade(label='文件',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=root.quit)
##menubar.add_cascade(label='编辑',menu=editmenu)
##
##root.config(menu=menubar)

#弹出菜单

##menubar.add_command(label='撤销',command = callback)
##menubar.add_command(label = '重做',command=root.quit)
##
##frame = Frame(root,width=512,height=512)
##frame.pack()
##
##def popup(event):
##    menubar.post(event.x_root,event.y_root)
##
##frame.bind("<Button-3>",popup)


#checkButton单选多选复合
##openVar = IntVar()
##saveVar = IntVar()
##quitVar = IntVar()
##
##filemenu = Menu(menubar,tearoff=True)#tearoff默认位true撕开新的
##filemenu.add_checkbutton(label='打开',command=callback,variable=openVar)
##filemenu.add_checkbutton(label='保存',command = callback,variable=saveVar)
##filemenu.add_separator()
##filemenu.add_checkbutton(label='退出',command=root.quit,variable=quitVar)
##menubar.add_cascade(label='文件',menu=filemenu)
##
##editVar = IntVar()
##
##editmenu = Menu(menubar,tearoff=False)
##editmenu.add_radiobutton(label='剪切',command=callback,variable=editVar,value=1)
##editmenu.add_radiobutton(label='拷贝',command = callback,variable=editVar,value=2)
##editmenu.add_separator()
##editmenu.add_radiobutton(label='粘贴',command=root.quit,variable=editVar,value=3)
##menubar.add_cascade(label='编辑',menu=editmenu)


#在按钮上添加菜单
##mb = Menubutton(root,text='dianwo',relief = RAISED)
##mb.pack()
##
##filemenu = Menu(mb,tearoff=False)
##filemenu.add_command(label='打开',command=callback)
##filemenu.add_command(label='保存',command = callback)
##filemenu.add_separator()
##filemenu.add_command(label='退出',command=root.quit)
##mb.config(menu=filemenu)

#可变菜单
##variable = StringVar()
##variable.set("one")
##w = OptionMenu(root,variable,'one','two','three')
##w.pack()

#传入
##OPTIONS=['one','two','three']
##
##variable = StringVar()
##variable.set(OPTIONS[0])
###*可以把列表打包为元组 **打包为字典,入参时*可以解为元组,**解为字典
##w = OptionMenu(root,variable, *OPTIONS)
##w.pack()

root.config(menu=menubar)


mainloop()

  1. 事件
#事件序列
from tkinter import *

root = Tk()

#鼠标事件
##def callback(event):
##    print("点击位置:",event.x,event.y)
##
##frame = Frame(root,width=200,height=200)
##frame.bind('<Button-1>',callback)#事件Button鼠标 1左键,点击鼠标会有个鼠标事件,形参回调函数
##frame.pack()

#键盘事件
##def callback(event):
##    print(event.char)
##
##frame = Frame(root,width=200,height=200)
##frame.bind('<Key>',callback)
##frame.focus_set()
##frame.pack()

#鼠标实时位置
##def callback(event):
##    print("当前位置:",event.x,event.y)
##
##frame = Frame(root,width=200,height=200)
##frame.bind('<Motion>',callback)
##frame.pack()


#keysym 输入键盘打印键盘字母
def callback(event):
    print(event.keysym)

frame = Frame(root,width=200,height=200)
frame.bind('<Key>',callback)
frame.focus_set()
frame.pack()

mainloop()

  1. 组件message、Spingbox、
#Message组件
from tkinter import *

root = Tk()

##w1 = Message(root,text = '一条消息',width=100)
##w1.pack()
##
##w2 = Message(root,text='一条长消息',width = 100)//自动会换行
##w2.pack()


#Spinbox组件
##w = Spinbox(root, values=('one','two','three'))
##w.pack()

#PanedWindow组件
##m = PanedWindow(orient=VERTICAL)
##m.pack(fill=BOTH,expand=1)
##
##top = Label(m,text='top pane')
##m.add(top)
##
##bottom = Label(m,text = 'bottom pane')
##m.add(bottom)

#显示手柄
##m1 = PanedWindow(showhandle=True,sashrelief=SUNKEN)#显示手柄,显示分割线默认和背景重叠
##m1.pack(fill=BOTH,expand=1)
##
##left = Label(m1,text='left pane')
##m1.add(left)
##
##m2 = PanedWindow(orient=VERTICAL,showhandle=True,sashrelief=SUNKEN)
##m1.add(m2)
##
##top = Label(m2,text='top pane')
##m2.add(top)
##
##bottom = Label(m2,text='bottom pane')
##m2.add(bottom)


#创建独立窗口Toplevel组件
def create():
    top = Toplevel()
    top.title('bat.com')

    msg = Message(top,text='I love bat')
    msg.pack()

Button(root,text='创建窗口',command=create).pack()

mainloop()
  1. 标准对话框
#标准对话框

from tkinter import *
from tkinter import filedialog
from tkinter import colorchooser

##messagebox.askokcancel('titlle','发射?')#返回值为True/False




#打开文件
##root = Tk()
##
##def callback():
####    fileName=filedialog.askopenfilename()#defaultextension='.py'指定类型,自动添加后缀的作用
##    fileName=filedialog.askopenfilename(filetypes=[('PNG','png'),('JPG','jpg')])
##    print(fileName)
##
##Button(root,text='打开文件',command=callback).pack()


#颜色对话框 colorchooser

root = Tk()
def callback():
    fileName=colorchooser.askcolor()
    print(fileName)

Button(root, text='选择颜色',command=callback).pack()

mainloop()
posted @ 2021-07-15 21:23  白玉神驹  阅读(275)  评论(0编辑  收藏  举报