tkinter python(图形开发界面)

tkinter  python(图形开发界面)

  Tkinter模块("Tk 接口")是Python的标准Tk GUI工具包的接口.Tk和Tkinter可以在大多数的Unix平台下使用,同样可以应用在Windows和Macintosh系统里.Tk8.0的后续版本可以实现本地窗口风格,并良好地运行在绝大多数平台中。

tkinter  python(图形开发界面)

1、简单实例

  下面的代码是创建出一个窗口,其他的操作就在这个平台上进行。执行之后会在桌面弹出一个窗口,窗口的标题就是代码中设置的win.title。这里说一下,我使用的版本是python3.6。后面的内容尽量按顺序看,后面的控件也许用到前面写到的东西。

 #!/usr/bin/env python
# -*- coding:utf-8 -*- import tkinter # 创建主窗口
win = tkinter.Tk()
# 设置标题
win.title("yudanqu")
# 设置大小和位置
win.geometry("400x400+200+50") # 进入消息循环,可以写控件 win.mainloop()

2、Label控件

 #!/usr/bin/env python
# -*- coding:utf-8 -*- import tkinter win = tkinter.Tk()
win.title("yudanqu")
win.geometry("400x400+200+50") '''
Label:标签控件,可以显示文本
'''
# win:父窗体
# text:显示的文本内容
# bg:背景色
# fg:字体颜色
# font:字体
# wraplength:指定text文本中多宽之后换行
# justify:设置换行后的对齐方式
# anchor:位置 n北,e东,w西,s南,center居中;还可以写在一起:ne东北方向
label = tkinter.Label(win,
text="this is a word",
bg="pink", fg="red",
font=("黑体", 20),
width=20,
height=10,
wraplength=100,
justify="left",
anchor="ne") # 显示出来
label.pack() win.mainloop()

3、Button控件

 #!/usr/bin/env python
# -*- coding:utf-8 -*- import tkinter def func():
print("aaaaaaaaaaaaaaaaaaaaaaa") win = tkinter.Tk()
win.title("yudanqu")
win.geometry("400x400+200+50") # 创建按钮
button1 = tkinter.Button(win, text="按钮", command=func, width=10, height=10)
button1.pack() button2 = tkinter.Button(win, text="按钮", command=lambda: print("bbbbbbbbbbbb"))
button2.pack() button3 = tkinter.Button(win, text="退出", command=win.quit)
button3.pack() win.mainloop()

4、Entry控件

 #!/usr/bin/env python
# -*- coding:utf-8 -*- import tkinter win = tkinter.Tk()
win.title("yudanqu")
win.geometry("400x400+200+50") '''
Entry:输入控件,用于显示简单的文本内容
''' # 密文显示
entry1 = tkinter.Entry(win, show="*") # show="*" 可以表示输入密码
entry1.pack() # 绑定变量
e = tkinter.Variable() entry2 = tkinter.Entry(win, textvariable=e)
entry2.pack() # e就代表输入框这个对象
# 设置值
e.set("wewewewewewe")
# 取值
print(e.get())
print(entry2.get()) win.mainloop()

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

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
import tkinter win = tkinter.Tk()
win.title("yudanqu")
win.geometry("400x400+200+50") def showinfo():
# 获取输入的内容
print(entry.get()) entry = tkinter.Entry(win)
entry.pack() button = tkinter.Button(win, text="按钮", command=showinfo)
button.pack() win.mainloop()

6、Text控件

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
import tkinter win = tkinter.Tk()
win.title("yudanqu")
win.geometry("400x400+200+50") '''
文本控件:用于显示多行文本
''' # height表示的是显示的行数
text = tkinter.Text(win, width=30, height=10)
text.pack() str = '''盖闻天地之数,有十二万九千六百岁为一元。将一元分为十二会,乃子、丑、寅、卯、辰、巳、午、未、申、酉、戌、亥之十二支也。每会该一万八百岁。且就一日而论:子时得阳气,而丑则鸡鸣;寅不通光,而卯则日出;辰时食后,而巳则挨排;日午天中,而未则西蹉;申时晡而日落酉;戌黄昏而人定亥。譬于大数,若到戌会之终,则天地昏蒙而万物否矣。再去五千四百岁,交亥会之初,则当黑暗,而两间人物俱无矣,故曰混沌。又五千四百岁,亥会将终,贞下起元,近子之会,而复逐渐开明。邵康节曰:“冬至子之半,天心无改移。一阳初动处,万物未生时。”到此,天始有根。再五千四百岁,正当子会,轻清上腾,有日,有月,有星,有辰。日、月、星、辰,谓之四象。故曰,天开于子。又经五千四百岁,子会将终,近丑之会,而逐渐坚实。易曰:“大哉乾元!至哉坤元!万物资生,乃顺承天。”至此,地始凝结。再五千四百岁,正当丑会,重浊下凝,有水,有火,有山,有石,有土。水、火、山、石、土谓之五形。故曰,地辟于丑。又经五千四百岁,丑会终而寅会之初,发生万物。''' text.insert(tkinter.INSERT, str) win.mainloop()

7、带滚动条的Text

 #!/usr/bin/env python
# -*- coding:utf-8 -*- import tkinter win = tkinter.Tk()
win.title("yudanqu")
# win.geometry("400x400+200+50") '''
文本控件:用于显示多行文本
''' # 创建滚动条
scroll = tkinter.Scrollbar() text = tkinter.Text(win, width=30, height=10)
# side放到窗体的哪一侧, fill填充
scroll.pack(side=tkinter.RIGHT, fill=tkinter.Y)
text.pack(side=tkinter.LEFT, fill=tkinter.Y)
# 关联
scroll.config(command=text.yview)
text.config(yscrollcommand=scroll.set) text.pack() str = '''盖闻天地之数,有十二万九千六百岁为一元。将一元分为十二会,乃子、丑、寅、卯、辰、巳、午、未、申、酉、戌、亥之十二支也。每会该一万八百岁。且就一日而论:子时得阳气,而丑则鸡鸣;寅不通光,而卯则日出;辰时食后,而巳则挨排;日午天中,而未则西蹉;申时晡而日落酉;戌黄昏而人定亥。譬于大数,若到戌会之终,则天地昏蒙而万物否矣。再去五千四百岁,交亥会之初,则当黑暗,而两间人物俱无矣,故曰混沌。又五千四百岁,亥会将终,贞下起元,近子之会,而复逐渐开明。邵康节曰:“冬至子之半,天心无改移。一阳初动处,万物未生时。”到此,天始有根。再五千四百岁,正当子会,轻清上腾,有日,有月,有星,有辰。日、月、星、辰,谓之四象。故曰,天开于子。又经五千四百岁,子会将终,近丑之会,而逐渐坚实。易曰:“大哉乾元!至哉坤元!万物资生,乃顺承天。”至此,地始凝结。再五千四百岁,正当丑会,重浊下凝,有水,有火,有山,有石,有土。水、火、山、石、土谓之五形。故曰,地辟于丑。又经五千四百岁,丑会终而寅会之初,发生万物。''' text.insert(tkinter.INSERT, str) win.mainloop()

8、Checkbutton多选框控件

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
import tkinter win = tkinter.Tk()
win.title("yudanqu")
win.geometry("400x400+200+50") 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("yudanqu")
win.geometry("400x400+200+50") def updata():
print(r.get()) # 绑定变量,一组单选框要绑定同一个变量,就能区分出单选框了
r = tkinter.IntVar() radio1 = tkinter.Radiobutton(win, text="one", value=1, variable=r, command=updata)
radio1.pack()
radio2 = tkinter.Radiobutton(win, text="two", value=2, variable=r, command=updata)
radio2.pack() win.mainloop()

10、Listbox控件一

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
import tkinter win = tkinter.Tk()
win.title("yudanqu")
win.geometry("400x400+200+50") '''
列表框控件:可以包含一个或多个文本框
作用:在listbox控件的小窗口显示一个字符串
''' # 创建一个listbox,添加几个元素
lb = tkinter.Listbox(win, selectmode=tkinter.BROWSE)
lb.pack() for item in ["good", "nice", "handsome", "aaa", "bbb", "ccc", "ddd"]:
# 按顺序添加
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) # 选中:参数1为开始的索引,参数2为结束的索引,如果不指定参数2,只选中第一个索引处的内容
lb.select_set(2,3) # 取消选中:参数1为开始的索引,参数2为结束的索引,如果不指定参数2,只取消第一个索引处的内容
lb.select_clear(2) # 获取到列表中的元素个数
print(lb.size())
# 获取值
print(lb.get(2,3)) # 返回当前的索引项,不是item元素
print(lb.curselection()) # 判断:一个选项是否被选中
print(lb.selection_includes(3)) win.mainloop()

11、Listbox控件二

 import tkinter

 win = tkinter.Tk()
win.title("yudanqu")
win.geometry("400x400+200+50") # 绑定变量
lbv = tkinter.StringVar() # 与BORWSE相似,但是不支持鼠标按下后移动选中位置
lb = tkinter.Listbox(win, selectmode=tkinter.SINGLE, listvariable=lbv)
lb.pack() for item in ["good", "nice", "handsome", "aaa", "bbb", "ccc", "ddd"]:
# 按顺序添加
lb.insert(tkinter.END, item) # 打印当前列表中的选型
print(lbv.get()) # 设置选项
# lbv.set(("1","2","3")) # 绑定事件
def myprint(event):
# print(lb.curselection()) # 返回下标
print(lb.get(lb.curselection())) # 返回值
lb.bind("<Double-Button-1>", myprint) win.mainloop()

12、Listbox控件三

 import tkinter

 win = tkinter.Tk()
win.title("yudanqu")
# win.geometry("400x400+200+50") # EXTENDED:可以使listbox支持shift和Ctrl
lb = tkinter.Listbox(win, selectmode=tkinter.EXTENDED)
lb.pack() for item in ["good", "nice", "handsome", "aaa", "bbb", "ccc", "ddd", "good", "nice", "handsome", "aaa", "bbb", "ccc", "ddd", "good", "nice", "handsome", "aaa", "bbb", "ccc", "ddd", "good", "nice", "handsome", "aaa", "bbb", "ccc", "ddd", "good", "nice", "handsome", "aaa", "bbb", "ccc", "ddd"]:
# 按顺序添加
lb.insert(tkinter.END, item) # 滚动条
sc = tkinter.Scrollbar(win)
sc.pack(side=tkinter.RIGHT, fill=tkinter.Y)
# 配置
lb.configure(yscrollcommand=sc.set)
lb.pack(side=tkinter.LEFT, fill=tkinter.BOTH)
# 额外给属性赋值
sc["command"] = lb.yview win.mainloop()

13、Listbox四

 import tkinter

 win = tkinter.Tk()
win.title("yudanqu")
win.geometry("400x400+200+50") # MULTIPLE支持多选
lb = tkinter.Listbox(win, selectmode=tkinter.MULTIPLE)
lb.pack() for item in ["good", "nice", "handsome", "aaa", "bbb", "ccc", "ddd"]:
# 按顺序添加
lb.insert(tkinter.END, item) win.mainloop()

14、Scale控件

 import tkinter

 win = tkinter.Tk()
win.title("yudanqu")
win.geometry("400x400+200+50") '''
供用户通过拖拽指示器来改变变量的值,可以水平,也可以竖直
''' # tkinter.HORIZONTAL水平
# tkinter.VERTICAL 竖直(默认)
# length:水平时表示宽度,竖直时表示高度
# tickintervar :选择值将会为该值得倍数 scale1 = tkinter.Scale(win, from_=0, to=100, orient=tkinter.HORIZONTAL, tickinterval=10, length=200)
scale1.pack() # 设置值
scale1.set(20) # 取值
# print(scale1.get()) def showNum():
print(scale1.get())
tkinter.Button(win, text="按钮", command=showNum).pack() win.mainloop()

15、Spinbox控件

 import tkinter

 win = tkinter.Tk()
win.title("yudanqu")
win.geometry("400x400+200+50") '''
数值范围控件
''' # 绑定变量
v = tkinter.StringVar() def updata():
print(v.get()) # increment:步长,默认为1
# values要输入一个元组 最好不要和from和to同时使用,而且步长也没用
# command 只要值改变就会执行updata方法
sp = tkinter.Spinbox(win, from_=0, to=100, increment=5,
textvariable=v, command=updata)
# sp = tkinter.Spinbox(win, values=(0,2,4,6,8))
sp.pack() # 赋值
v.set(20)
# 取值
print(v.get()) win.mainloop()

16、Menu顶层菜单

 import tkinter

 win = tkinter.Tk()
win.title("yudanqu")
win.geometry("400x400+200+50") # 菜单条
menubar = tkinter.Menu(win)
win.config(menu=menubar) def func():
print("**********") # 创建一个菜单选项
menu1 = tkinter.Menu(menubar, tearoff=False) # 给菜单选项添加内容
for item in ['python','c','java','c++', 'c#','php','B','退出']:
if item == '退出':
# 添加分割线
menu1.add_separator()
menu1.add_command(label=item, command=win.quit)
else:
menu1.add_command(label=item, command=func) # 向菜单条上添加菜单选项
menubar.add_cascade(label='语言', menu=menu1) win.mainloop()

17、Menu鼠标右键菜单

 import tkinter

 win = tkinter.Tk()
win.title("yudanqu")
win.geometry("400x400+200+50") # 菜单条
menubar = tkinter.Menu(win) def func():
print("**********") # 菜单
menu = tkinter.Menu(menubar, tearoff=False)
# 给菜单选项添加内容
for item in ['python','c','java','c++', 'c#','php','B','退出']:
if item == '退出':
# 添加分割线
menu.add_separator()
menu.add_command(label=item, command=win.quit)
else:
menu.add_command(label=item, command=func) 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("yudanqu")
win.geometry("400x400+200+50") # 绑定变量
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())
com.bind("<<ComboboxSelected>>", func) win.mainloop()

19、Frame控件

 import tkinter

 win = tkinter.Tk()
win.title("yudanqu")
win.geometry("400x400+200+50") '''
框架控件:在桌面上显示一个矩形区域,多作为一个容器控件
''' 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="green").pack(side=tkinter.TOP)
tkinter.Label(frm_r, text="右下", bg="red").pack(side=tkinter.TOP)
frm_r.pack(side=tkinter.RIGHT) win.mainloop()

20、表格数据

 import tkinter
from tkinter import ttk win = tkinter.Tk()
win.title("yudanqu")
win.geometry("600x400+200+50") # 表格
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="身高-height")
tree.heading("体重", text="体重-weight") # 添加数据
tree.insert("", 0, text="line1", values=("小郑","","177cm","70kg"))
tree.insert("", 1, text="line2", values=("小张","","188cm","90kg")) win.mainloop()

21、树状数据

 import tkinter
from tkinter import ttk win = tkinter.Tk()
win.title("yudanqu")
win.geometry("400x400+200+50") tree = ttk.Treeview(win)
tree.pack() # 添加一级树枝
treeF1 = tree.insert("",0,"中国",text= "中国Chi", values=("F1"))
treeF2 = tree.insert("",1,"美国",text= "美国USA", values=("F1"))
treeF3 = tree.insert("",2,"英国",text= "英国UK", values=("F1")) # 二级树枝
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,"aaa",text="aaaa",values=("F2_1"))
treeF2_2 = tree.insert(treeF2,1,"bbb",text="bbbb",values=("F2_2"))
treeF2_3 = tree.insert(treeF2,2,"ccc",text="cccc",values=("F2_3")) # 三级树枝
treeF1_1_1 = tree.insert(treeF1_1,0,"哈尔滨",text="黑龙江哈尔滨")
treeF1_1_2 = tree.insert(treeF1_1,1,"五常",text="黑龙江五常") win.mainloop()

22、绝对布局

 import tkinter

 win = tkinter.Tk()
win.title("yudanqu")
win.geometry("400x400+200+50") label1 = tkinter.Label(win, text="good", bg="blue")
label2 = tkinter.Label(win, text="nice", bg="red")
label3 = tkinter.Label(win, text="cool", bg="green") # 绝对布局,窗口的变化对位置没有影响
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("yudanqu")
win.geometry("400x400+200+50") label1 = tkinter.Label(win, text="good", bg="blue")
label2 = tkinter.Label(win, text="nice", bg="red")
label3 = tkinter.Label(win, text="cool", bg="green") # 相对布局,窗体改变对控件有影响
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("yudanqu")
win.geometry("400x400+200+50") label1 = tkinter.Label(win, text="good", bg="blue")
label2 = tkinter.Label(win, text="nice", bg="red")
label3 = tkinter.Label(win, text="cool", bg="green")
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("yudanqu")
win.geometry("400x400+200+50") def func(event):
print(event.x, event.y) # <Button-1> 鼠标左键
# <Button-2> 鼠标滚轮
# <Button-1> 鼠标右键
# <Double-Button-1> 鼠标双击左键
# <Triple-Button-1> 鼠标三击左键 button1 = tkinter.Button(win, text="leftmouse button")
# bind 给控件绑定数据(参数一是绑定的事件,参数二是触发事件的函数)
button1.bind("<Button-1>", func)
button1.pack() win.mainloop()

26、鼠标移动事件

 import tkinter

 win = tkinter.Tk()
win.title("yudanqu")
win.geometry("400x400+200+50") # <B1-Motion> 左键移动
# <B2-Motion> 中键移动
# <B3-Motion> 右键移动 label = tkinter.Label(win, text="*********")
label.pack() def func(event):
print(event.x, event.y) label.bind("<B1-Motion>", func) win.mainloop()

27、鼠标释放事件

 import tkinter

 win = tkinter.Tk()
win.title("yudanqu")
win.geometry("400x400+200+50") # <ButtonRelease-1> 释放鼠标左键
# <ButtonRelease-2> 释放鼠标中键
# <ButtonRelease-3> 释放鼠标右键 label = tkinter.Label(win, text="*********", bg="red")
label.pack() def func(event):
print(event.x, event.y) label.bind("<ButtonRelease-1>", func) win.mainloop()

28、进入和离开事件

 import tkinter

 win = tkinter.Tk()
win.title("yudanqu")
win.geometry("400x400+200+50") # <Enter> 当鼠标进入控件时触发事件
# <Leave> 当鼠标离开控件时触发事件 label = tkinter.Label(win, text="*********", bg="red")
label.pack() def func(event):
print(event.x, event.y) label.bind("<Enter>", func)
label.bind("<Leave>", func) win.mainloop()

29、响应所有按键的事件

 import tkinter

 win = tkinter.Tk()
win.title("yudanqu")
win.geometry("400x400+200+50") # <Key> 响应所有的按键(要有焦点) label = tkinter.Label(win, text="*********", bg="red")
# 设置焦点
label.focus_set()
label.pack() 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("yudanqu")
win.geometry("400x400+200+50") # <Shift_L> 只响应左侧的shift键
# <Shift_R>
# <F5>
# <Return> 也就是回车键
# <BackSpace> 返回,也就是退格键 label = tkinter.Label(win, text="*********", bg="red")
# 设置焦点
label.focus_set()
label.pack() 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("yudanqu")
win.geometry("400x400+200+50") label = tkinter.Label(win, text="*********", bg="red")
# 设置焦点
label.focus_set()
label.pack() def func(event):
print("event.char=", event.char)
print("event.keycode=", event.keycode) win.bind("a", func) # 注意前面改成了win,只需要写出按键名即可 win.mainloop()

32、组合按键事件

 import tkinter

 win = tkinter.Tk()
win.title("yudanqu")
win.geometry("400x400+200+50") # <Control-Alt-a>
# <Shift-Up>
# 只是control+alt不行 label = tkinter.Label(win, text="*********", bg="red")
# 设置焦点
label.focus_set()
label.pack() def func(event):
print("event.char=", event.char)
print("event.keycode=", event.keycode) win.bind("<Control-Alt-a>", func) # 注意前面改成了win,只需要写出按键名即可 win.mainloop()
上一篇:IO -阻塞,非阻塞, 同步,异步


下一篇:hibernate映射对象三种状态的分析