Python tkinter2021-08-27

本文详细介绍了Python的tkinter库中包括label、button、entry、text、checkbutton、radiobutton、listbox、scale、sprinbox、menu、combobox、frame等GUI控件的使用,涵盖了各种交互事件及布局管理方法。
摘要由CSDN通过智能技术生成

1、简单示例

import tkinter
#创建主窗口
win = tkinter.Tk()
#设置标题
win.title("fanfan")
#设置大小和位置
win.geometry("400x400+200+0")
#进入消息循环

win.mainloop()

2、label空间

import tkinter
win = tkinter.Tk()
win.title("sunck")
win.geometry("400x400+200+0")
'''
label:标签控件可以显示文本
'''
#参数1:win父窗体
#text:显示文本内容
#bg:背景色
#fg:字体颜色
#font 字体及大小
#width
#height
# wrapLength指定text文本中多宽进行换行
#justify 设置换行后的对齐方式
# anochor 位置n北   e东   s南    w西   center居中 ne  se   sw  nw
label = tkinter.Label(win,
                      text="fanfan",
                      bg="blue",
                      fg = "red",
                      font=("黑体", 20),
                      width=10,
                      height=4,
                      wraplength=100,
                      justify="left",
                      anchor="center")
#显示出来
label.pack()

win.mainloop()

3、button控件

import tkinter
win = tkinter.Tk()
win.title("fanfan")
win.geometry("400x400+200+0")
def func():
    print("fanfan is a good man")
#创建按钮
button1 = tkinter.Button(win, text="按钮", command=func, width=10, height=10)
button1.pack()

button2 = tkinter.Button(win, text="按钮", command=lambda:print("fanfan is a good man"), width=10, height=10)
button2.pack()

button3 = tkinter.Button(win, text="按钮", command=win.quit, width=10, height=10)
button3.pack()

win.mainloop()

4、entry控件

import tkinter
win = tkinter.Tk()
win.title("fanfan")
win.geometry("400x400+200+0")
'''
输入控件
用于显示简单的文本内容
'''
#绑定变量
e = tkinter.Variable()
# show密文显示   show="*"
entry = tkinter.Entry(win, textvariable=e)
entry.pack()

#e就代表输入框这个对象
#设置值
e.set("fanfan is a good man")
#取值
print(e.get())
print(entry.get())

win.mainloop()

5、点击按钮输出输入框中的内容

import tkinter
win = tkinter.Tk()
win.title("fanfan")
win.geometry("400x400+200+0")
def showInfo():
    print(entry.get())
entry = tkinter.Entry(win)
entry.pack()

button = tkinter.Button(win, text="按钮", command=showInfo)
button.pack()

win.mainloop()

6、text控件

import tkinter
win = tkinter.Tk()
win.title("fanfan")
win.geometry("400x400+200+0")
'''
文本控件,用于显示多行文本
'''
# height显示的行数
text = tkinter.Text(win, width=30, height=4)
text.pack()

str = """That we are in the midst of crisis is now well understood. Our nation is at war, against a far-reaching network of violence and hatred. Our economy is badly weakened, a consequence of greed and irresponsibility on the part of some, but also our collective failure to make hard choices and prepare the nation for a new age. Homes have been lost; jobs shed; businesses shuttered. Our health care is too costly; our schools fail too many; and each day brings further evidence that the ways we use energy strengthen our adversaries and threaten our planet."""
text.insert(tkinter.INSERT, str)

win.mainloop()

7、带滚动条的text

import tkinter
win = tkinter.Tk()
win.title("fanfan")
# win.geometry("400x400+200+0")
'''
文本控件,用于显示多行文本
'''
#创建滚动条
scroll = tkinter.Scrollbar()

text = tkinter.Text(win, width=50, height=8)
#side放到窗体的右侧
# fill填充
scroll.pack(side=tkinter.RIGHT, fill=tkinter.Y)
text.pack(side=tkinter.LEFT, fill=tkinter.Y)

str = """That we are in the midst of crisis is now well understood. Our nation is at war, against a far-reaching network of violence and hatred. Our economy is badly weakened, a consequence of greed and irresponsibility on the part of some, but also our collective failure to make hard choices and prepare the nation for a new age. Homes have been lost; jobs shed; businesses shuttered. Our health care is too costly; our schools fail too many; and each day brings further evidence that the ways we use energy strengthen our adversaries and threaten our planet.That we are in the midst of crisis is now well understood. Our nation is at war, against a far-reaching network of violence and hatred. Our economy is badly weakened, a consequence of greed and irresponsibility on the part of some, but also our collective failure to make hard choices and prepare the nation for a new age. Homes have been lost; jobs shed; businesses shuttered. Our health care is too costly; our schools fail too many; and each day brings further evidence that the ways we use energy strengthen our adversaries and threaten our planet."""
text.insert(tkinter.INSERT, str)
#关联
scroll.config(command=text.yview)
text.config(yscrollcommand=scroll.set)


win.mainloop()

8、checkbutton多选框控件

import tkinter
win = tkinter.Tk()
win.title("fanfan")
win.geometry("400x400+200+0")
def updata():
    message = ""
    if hobby1.get() == True:
        message += "money\n"
    if hobby2.get() == True:
        message += "power\n"
    if hobby3.get() == True:
        message += "people\n"
    #清除text中的所有内容
    text.delete(0.0,tkinter.END)
    text.insert(tkinter.INSERT, message)
#绑定的变量
hobby1 = tkinter.BooleanVar()
#多选框
check1 = tkinter.Checkbutton(win, text="money", variable=hobby1, command=updata)
check1.pack()
hobby2 = tkinter.BooleanVar()
check2 = tkinter.Checkbutton(win, text="power", variable=hobby2, command=updata)
check2.pack()
hobby3 = tkinter.BooleanVar()
check3 = tkinter.Checkbutton(win, text="people", variable=hobby3, command=updata)
check3.pack()
text = tkinter.Text(win,width=50,height=5)
text.pack()

win.mainloop()

9、radiobutton单选框控件

import tkinter
win = tkinter.Tk()
win.title("fanfan")
win.geometry("400x400+200+0")
def updata():
    print(r.get())
#一组单选框绑定同一个变量
# r = tkinter.IntVar()
r = tkinter.StringVar()
radio1 = tkinter.Radiobutton(win, text="one", value="good", variable=r, command=updata)
radio1.pack()
radio2 = tkinter.Radiobutton(win, text="two", value="nice", variable=r, command=updata)
radio2.pack()
radio3 = tkinter.Radiobutton(win, text="two", value="cool", variable=r, command=updata)
radio3.pack()

win.mainloop()

10、listbox控件1

import tkinter
win = tkinter.Tk()
win.title("fanfan")
win.geometry("400x400+200+0")
'''
列表框控件,可以包含一个或多个文本框
作用:可以在listbox的小窗口显示一个字符串
'''
#1、创建一个listbox,添加几个元素
#tkinter.BROWSE
lb = tkinter.Listbox(win, selectmode= tkinter.BROWSE)
lb.pack()
for item in ["good", "nice", "handsome", "vg", "vn"]:
    #按顺序添加
    lb.insert(tkinter.END, item)
#在开始添加
lb.insert(tkinter.ACTIVE, "cool")
#将列表当成一个元素添加
# lb.insert(tkinter.END,["very good", "very nice"])
#删除
#参数1为开始的索引,参数2位结束的索引,如果不指定参数2只删除第一个索引的内容
# lb.delete(1, 3)
# lb.delete(1)
#选中
#参数1为开始的索引,参数2位结束的索引,如果不指定参数2只选中参数1索引处的内容
lb.select_set(2, 5)
#取消选中
#参数1为开始的索引,参数2位结束的索引,如果不指定参数2,参数1索引的位置不选中
# lb.select_clear(3)
#获取列表中元素的个数
# print(lb.size())

#获取值
#从列表中取值
# print(lb.get(2, 4))
# 参数1为开始的索引,参数2位结束的索引,如果不指定参数2,只获取第一个索引处的内容
# print(lb.get(1))

#返回当前的索引项,不是item元素
print(lb.curselection())

#判断一个选项是否被选中
print(lb.selection_includes(3))

win.mainloop()

11、listbox控件2

import tkinter
win = tkinter.Tk()
win.title("fanfan")
win.geometry("400x400+200+0")
#绑定变量
lbv = tkinter.StringVar()
#与BORWSE相似,但不支持鼠标按下后移动选中
lb = tkinter.Listbox(win, selectmode=tkinter.SINGLE, listvariable=lbv)
lb.pack()
for item in ["good", "nice", "handsome", "vg", "vn"]:
    #按顺序添加
    lb.insert(tkinter.END, item)
#打印当前列表的选项
print(lbv.get())
#设置选项
# lbv.set(("1", "2", "3"))

#绑定事件
def myPrint(event):
    print(lb.get(lb.curselection()))
lb.bind('<Double-Button-1>', myPrint)

win.mainloop()

12、listbox控件3

import tkinter
win = tkinter.Tk()
win.title("fanfan")
win.geometry("400x400+200+0")
#绑定变量
lbv = tkinter.StringVar()
#与BORWSE相似,但不支持鼠标按下后移动选中
lb = tkinter.Listbox(win, selectmode=tkinter.SINGLE, listvariable=lbv)
lb.pack()
for item in ["good", "nice", "handsome", "vg", "vn"]:
    #按顺序添加
    lb.insert(tkinter.END, item)
#打印当前列表的选项
print(lbv.get())
#设置选项
# lbv.set(("1", "2", "3"))

#绑定事件
def myPrint(event):
    print(lb.get(lb.curselection()))
lb.bind('<Double-Button-1>', myPrint)

win.mainloop()

13、listbox控件4

import tkinter
win = tkinter.Tk()
win.title("fanfan")
win.geometry("400x400+200+0")
#MULTIPLE支持多选
lb = tkinter.Listbox(win, selectmode= tkinter.MULTIPLE)
lb.pack()
for item in ["good", "nice", "handsome", "vg", "vn"]:
    lb.insert(tkinter.END, item)

win.mainloop()

14、scale控件

import tkinter
win = tkinter.Tk()
win.title("fanfan")
win.geometry("400x400+200+0")
'''
供用户拖拽指示器,改变变量的值,可以水平,
tkinter.HORIZONTAL  水平
tkinter.VERTICAL  竖直
length 水平时表示宽度,竖直时表示高度
tickinterval表示值将会是该值的倍数
'''
scale = tkinter.Scale(win, from_=0, to=100, orient=tkinter.VERTICAL, tickinterval=10, length=200)
scale.pack()
# 设置值
scale.set(20)
#获取值
# print(scale.get())
def showNum():
    print(scale.get())
tkinter.Button(win, text="按钮", command=showNum).pack()

win.mainloop()

15、sprinbox数值范围控件

import tkinter
win = tkinter.Tk()
win.title("fanfan")
win.geometry("400x400+200+0")
'''
数值范围控件
increment 步长,默认为1
values  最好不要和from_=0, to=100, increment=1,同时使用
values=(0,2,4,6,8)
'''
def updata():
    print(v.get())
#绑定变量
# command只要值改变就会执行对应的方法
v = tkinter.StringVar()
sp = tkinter.Spinbox(win, from_=0, to=100, increment=1, textvariable=v, command=updata)
sp.pack()
#设置值
v.set(20)
print(v.get())

win.mainloop()

16、menu顶层菜单

import tkinter
win = tkinter.Tk()
win.title("fanfan")
win.geometry("400x400+200+0")
#菜单条
menbar = tkinter.Menu(win)
win.config(menu=menbar)
def func():
    print("fanfan is a good man")

#创建菜单选项
menu1 = tkinter.Menu(menbar, tearoff=False)
#给菜单选项添加内容
for item in ["Python", "C", "C++", "OC", "Swift", "C#", "shell", "Java", "JS", "PHP", "汇编", "NodeJS", "退出"]:
    if item == "退出":
        #添加分割线
        menu1.add_separator()
        menu1.add_command(label=item, command=win.quit)
    else:
        menu1.add_command(label=item, command=func)
#菜单条上添加菜单菜单选项
menbar.add_cascade(label="语言", menu = menu1)

menu2 = tkinter.Menu(menbar, tearoff=False)
menu2.add_command(label="red")
menu2.add_command(label="blue")
menbar.add_cascade(label="颜色", menu = menu2)

win.mainloop()

17、Menu鼠标右键菜单

import tkinter
win = tkinter.Tk()
win.title("fanfan")
win.geometry("400x400+200+0")
#菜单条
menubar = tkinter.Menu(win)
#菜单
menu = tkinter.Menu(menubar, tearoff=False)
for item in ["Python", "C", "C++", "OC", "Swift", "C#", "shell", "Java", "JS", "PHP", "汇编", "NodeJS", "退出"]:
    menu.add_command(label=item)
menubar.add_cascade(label="语言", menu=menu)
def showMenu(event):
    menubar.post(event.x_root, event.y_root)
win.bind("<Button-3>", showMenu)

win.mainloop()

18、Combobox下拉控件

import tkinter
from tkinter import ttk
win = tkinter.Tk()
win.title("fanfan")
win.geometry("400x400+200+0")
#绑定变量
cv = tkinter.StringVar()
com = ttk.Combobox(win, textvariable=cv)
com.pack()
#设置下拉数据
com["value"] = ["黑龙江", "吉林", "辽宁"]
#设置默认值
com.current(0)
#绑定事件
def func(event):
    print(com.get())
    print(cv.get())
    print("sunck is a good man")
com.bind("<<ComboboxSelected>>", func)

win.mainloop()

19、Frame控件

import tkinter
win = tkinter.Tk()
win.title("fanfan")
win.geometry("400x400+200+0")
'''
框架控件
在屏幕上显示一个矩形区域,多作为一个容器
'''
frm = tkinter.Frame(win)
frm.pack()
#left
frm_l = tkinter.Frame(frm)
tkinter.Label(frm_l, text="左上", bg="pink").pack(side=tkinter.TOP)
tkinter.Label(frm_l, text="左下", bg="blue").pack(side=tkinter.TOP)
frm_l.pack(side=tkinter.LEFT)
#right
frm_r = tkinter.Frame(frm)
tkinter.Label(frm_r, text="右上", bg="red").pack(side=tkinter.TOP)
tkinter.Label(frm_r, text="右下", bg="yellow").pack(side=tkinter.TOP)
frm_r.pack(side=tkinter.RIGHT)

win.mainloop()

20、数据显示–表格数据

import tkinter
from tkinter import ttk
win = tkinter.Tk()
win.title("fanfan")
win.geometry("600x400+200+0")
#定义列
tree = ttk.Treeview(win)
tree.pack()
tree["columns"] = ("姓名","年龄", "身高", "体重")
#设置列, 列不显示
tree.column("姓名", width=100)
tree.column("年龄", width=100)
tree.column("体重", width=100)
tree.column("身高", width=100)

#设置表头
tree.heading("姓名", text="姓名-name")
tree.heading("年龄", text="姓名-age")
tree.heading("体重", text="姓名-weight")
tree.heading("身高", text="姓名-height")

#添加数据
tree.insert("", 0, text="line1", values=("卢彦旭", "28", "165", "80"))
tree.insert("", 1, text="line2", values=("范玉斌", "29", "167", "70"))
win.mainloop()

21、数据显示–树状数据

import tkinter
from tkinter import ttk
win = tkinter.Tk()
win.title("fanfan")
win.geometry("400x400+200+0")

tree = ttk.Treeview(win)
tree.pack()

#添加一级树枝
treeF1 = tree.insert("", 0, "中国", text="中国CHI", values=("F1"))
treeF2 = tree.insert("", 1, "美国", text="美国USA", values=("F2"))
treeF3 = tree.insert("", 2, "英国", text="英国ENG", values=("F3"))

#添加二级树枝
treeF1_1 = tree.insert(treeF1, 0, "黑龙江", text="中国黑龙江", values=("F1_1"))
treeF1_2 = tree.insert(treeF1, 1, "吉林", text="中国吉林", values=("F1_2"))
treeF1_3 = tree.insert(treeF1, 2, "辽宁", text="中国辽宁", values=("F1_3"))

treeF2_1 = tree.insert(treeF2, 0, "德克萨斯州", text="美国德克萨斯州", values=("F2_1"))
treeF2_2 = tree.insert(treeF2, 1, "底特律", text="美国底特律", values=("F2_2"))
treeF2_3 = tree.insert(treeF2, 2, "旧金山", text="美国旧金山", values=("F2_3"))

#添加三级树枝
treeF1_1_1 = tree.insert(treeF1_1, 0, "哈尔滨", text="黑龙江哈尔滨")
treeF1_1_2 = tree.insert(treeF1_1, 0, "五常", text="黑龙江五常")

win.mainloop()

22、绝对布局

import tkinter
win = tkinter.Tk()
win.title("fanfan")
win.geometry("400x400+200+0")
label1 = tkinter.Label(win, text="good", bg="blue")
label2 = tkinter.Label(win, text="nice", bg="red")
label3 = tkinter.Label(win, text="cool", bg="pink")

#绝对布局,窗口的变化对位置没有影响
label1.place(x=10, y=10)
label2.place(x=50, y=50)
label3.place(x=100, y=100)

win.mainloop()

23、相对布局

import tkinter
win = tkinter.Tk()
win.title("fanfan")
win.geometry("400x400+200+0")
label1 = tkinter.Label(win, text="good", bg="blue")
label2 = tkinter.Label(win, text="nice", bg="red")
label3 = tkinter.Label(win, text="cool", bg="pink")

#相对布局,修改窗体大小对控件有影响
# tkinter.Both
label1.pack(fill=tkinter.Y, side=tkinter.LEFT)
label2.pack(fill=tkinter.X, side=tkinter.TOP)
label3.pack()

win.mainloop()

24、表格布局

import tkinter
win = tkinter.Tk()
win.title("fanfan")
win.geometry("400x400+200+0")

label1 = tkinter.Label(win, text="good", bg="blue")
label2 = tkinter.Label(win, text="nice", bg="red")
label3 = tkinter.Label(win, text="cool", bg="pink")
label4 = tkinter.Label(win, text="handsome", bg="yellow")

#表格布局
label1.grid(row=0, column=0)
label2.grid(row=0, column=1)
label3.grid(row=1, column=0)
label4.grid(row=1, column=1)

win.mainloop()

25、鼠标点击事件

import tkinter
win = tkinter.Tk()
win.title("fanfan")
win.geometry("400x400+200+0")
button1 = tkinter.Button(win, text="leftmouse button")
#<Button-1>鼠标左键
#<Button-3>鼠标右键
#<Button-2>鼠标滑轮
# <Double Button-1>鼠标左键双击
# <Double Button-3>鼠标右键双击
# <Double Button-2>鼠标滑轮双击
# <Triple Button-1>鼠标左键三击
# <Triple Button-3>鼠标右键三击
# <Triple Button-2>鼠标滑轮三击
def func(event):
    print(event.x, event.y)
button1.bind("<Triple Button-1>", func)
#bind  给控件绑定事件
button1.pack()

win.mainloop()

26、鼠标移动事件

import tkinter
win = tkinter.Tk()
win.title("fanfan")
win.geometry("400x400+200+0")
label = tkinter.Label(win, text="fanfan is a good man")
label.pack()
#<B1-Motion>鼠标左键移动
#<B3-Motion>鼠标右键键移动
#<B2-Motion>鼠标滑轮移动
def func(event):
    print(event.x, event.y)
label.bind("<B1-Motion>", func)


win.mainloop()

27、鼠标释放事件

import tkinter
win = tkinter.Tk()
win.title("fanfan")
win.geometry("400x400+200+0")
label = tkinter.Label(win, text="fanfan is a good man", bg="red")
label.pack()
#<ButtonRelease-1>释放鼠标左键
#<ButtonRelease-3>释放鼠标右键
#<ButtonRelease-2>释放鼠标滑轮

def func(event):
    print(event.x, event.y)
label.bind("<ButtonRelease-1>", func)

win.mainloop()

28、进入离开事件

import tkinter
win = tkinter.Tk()
win.title("fanfan")
win.geometry("400x400+200+0")
label = tkinter.Label(win, text="fanfan is a good man", bg="red")
label.pack()
#<Enter>鼠标光标进入控件时发生
#<Leave>鼠标光标离开控件时发生
#
def func(event):
    print(event.x, event.y)
label.bind("<Leave>", func)

win.mainloop()

29、响应所有按键的事件

import tkinter
win = tkinter.Tk()
win.title("fanfan")
win.geometry("400x400+200+0")


label = tkinter.Label(win, text="fanfan is a good man", bg="red")
#设置焦点
label.focus_set()
label.pack()
#<Key>响应所有按键
def func(event):
    print("event.char=", event.char)
    print("event.keycode=", event.keycode)

label.bind("<Key>", func)

win.mainloop()

30、响应特殊按键事件

import tkinter
win = tkinter.Tk()
win.title("fanfan")
win.geometry("400x400+200+0")
label = tkinter.Label(win, text="fanfan is a good man", bg="red")
# 设置焦点
label.focus_set()
label.pack()

# <Shift_L>响应左侧shit
# <Shift_R>响右侧shit
# <Key>响应所有按键
#<F5>
#"<Return>
#<BackSpace>
def func(event):
    print("event.char=", event.char)
    print("event.keycode=", event.keycode)


label.bind("<Shift_L>", func)

win.mainloop()

31、指定按键事件

import tkinter
win = tkinter.Tk()
win.title("fanfan")
win.geometry("400x400+200+0")
label = tkinter.Label(win, text="fanfan is a good man", bg="red")
#设置焦点
label.focus_set()
label.pack()
#<Key>响应所有按键
def func(event):
    print("event.char=", event.char)
    print("event.keycode=", event.keycode)

label.bind("a", func)

win.mainloop()

32、组合按键事件

import tkinter
win = tkinter.Tk()
win.title("fanfan")
win.geometry("400x400+200+0")

label = tkinter.Label(win, text="sunck is a good man", bg="red")
#设置焦点
label.focus_set()
label.pack()
#<Key>响应所有按键
def func(event):
    print("event.char=", event.char)
    print("event.keycode=", event.keycode)

label.bind("<Shift-Up>", func)

win.mainloop()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值