python自带的 import tkinter as tk
1.控件
控件 | 描述 |
---|---|
Button | 按钮控件;在程序中显示按钮。 |
Canvas | 画布控件;显示图形元素如线条或文本 |
Checkbutton | 多选框控件;用于在程序中提供多项选择框 |
Entry | 输入控件;用于显示简单的文本内容 |
Frame | 框架控件;在屏幕上显示一个矩形区域,多用来作为容器 |
Label | 标签控件;可以显示文本和位图 |
Listbox | 列表框控件;在Listbox窗口小部件是用来显示一个字符串列表给用户 |
Menubutton | 菜单按钮控件,用于显示菜单项。 |
Menu | 菜单控件;显示菜单栏,下拉菜单和弹出菜单 |
Message | 消息控件;用来显示多行文本,与label比较类似 |
Radiobutton | 单选按钮控件;显示一个单选的按钮状态 |
Scale | 范围控件;显示一个数值刻度,为输出限定范围的数字区间 |
Scrollbar | 滚动条控件,当内容超过可视化区域时使用,如列表框。. |
Text | 文本控件;用于显示多行文本 |
Toplevel | 容器控件;用来提供一个单独的对话框,和Frame比较类似 |
Spinbox | 输入控件;与Entry类似,但是可以指定输入范围值 |
PanedWindow | PanedWindow是一个窗口布局管理的插件,可以包含一个或者多个子控件。 |
LabelFrame | labelframe 是一个简单的容器控件。常用与复杂的窗口布局。 |
tkMessageBox | 用于显示你应用程序的消息框。 |
2.标准属性
属性 | 描述 |
---|---|
Dimension | 控件大小; |
Color | 控件颜色; |
Font | 控件字体; |
Anchor | 锚点; |
Relief | 控件样式; |
Bitmap | 位图; |
Cursor | 光标; |
3.几何管理
几何方法 | 描述 |
---|---|
pack() | 包装; |
grid() | 网格; |
place() | 位置; |
4.学习
1.固定格式
# 导入tkinter,取别名tk
import tkinter as tk
# 创建窗口
window = tk.Tk()
# 窗口名字
window.title('my window')
# 窗口大小,字符串
window.geometry('200x100')
# 调用组件的mainloop()方法,进入事件循环
window.mainloop()
2.Label/Button
import tkinter as tk
window = tk.Tk()
window.title('my window')
window.geometry('200x100') # 窗口大小,字符串
var = tk.StringVar() # tk里面的字符串变量
# 标签(文本)
# label放置的窗口 窗口上的文本 背景颜色 字体,大小 标签的宽和高
l = tk.Label(window, textvariable=var, bg='pink', font=('Arial', 12), width=15, height=2)
# pack把控件放在正确的地方,对于之后的每个空间,会去寻找剩下的空间进行填充
l.pack()
on_hit = False
def hit_me():
global on_hit
if not on_hit:
on_hit = True
# 显示内容
var.set('you hit me!')
else:
on_hit = False
var.set('')
# 按键 效果(方法)
b = tk.Button(window, text='hit me', width=15, height=2, command=hit_me)
b.pack()
window.mainloop() # window会不断刷新
3.Entry/Text
import tkinter as tk
window = tk.Tk()
window.title('my window')
window.geometry('200x200') # 窗口大小,字符串
# 输入框
e = tk.Entry(window, show=None)
e.pack()
def insert_point():
# 获取当前文本内容
var = e.get()
# 在光标处插入
t.insert('insert', var)
def insert_end():
# 获取当前文本内容
var = e.get()
#也可以插入固定位置 insert(1.1,var) 插入第一行第一位
t.insert('end', var)
# 按键 效果
b1 = tk.Button(window, text='insert point', width=15, height=2, command=insert_point)
b1.pack()
b2 = tk.Button(window, text='insert end', command=insert_end)
b2.pack()
# 文本框
t = tk.Text(window, height=2)
t.pack()
window.mainloop() # window会不断刷新
4.Listbox(列表框)
结果如下图
import tkinter as tk
window = tk.Tk()
window.title('my window')
window.geometry('200x300') # 窗口大小,字符串
var1 = tk.StringVar()
l = tk.Label(window, bg='yellow', width=4, textvariable=var1)
l.pack()
def print_selection():
# 光标
value = lb.get(lb.curselection())
# 显示value
var1.set(value)
# 按键 效果
b = tk.Button(window, text='print selection', width=15, height=2, command=print_selection)
b.pack()
var2 = tk.StringVar()
var2.set((11, 22, 33, 44))
lb = tk.Listbox(window, listvariable=var2)
list_items = [1, 2, 3, 4]
# for循环插入
for item in list_items:
lb.insert('end', item)
# 在固定位置插入
lb.insert(1, 'first')
lb.insert(2, 'second')
# 删除
lb.delete(2)
lb.pack()
window.mainloop() # window会不断刷新
5.Radiobutton(选择)
运行结果:
import tkinter as tk
window = tk.Tk()
window.title('my window')
window.geometry('200x200')
var = tk.StringVar()
l = tk.Label(window, bg='yellow', width=20, text='empty')
l.pack()
def print_selection():
# config能对所有的参数进行更改
l.config(text='you have selected ' + var.get())
r1 = tk.Radiobutton(window, text='OptionA', variable=var, value='A', command=print_selection)
r1.pack()
r2 = tk.Radiobutton(window, text='OptionB', variable=var, value='B', command=print_selection)
r2.pack()
r3 = tk.Radiobutton(window, text='OptionC', variable=var, value='C', command=print_selection)
r3.pack()
window.mainloop()
6.Scale(尺度)
可以被拉动的一个条,Scale返回的是一个数字。
import tkinter as tk
window = tk.Tk()
window.title('my window')
window.geometry('200x200')
l = tk.Label(window, bg='yellow', width=20, text='empty')
l.pack()
# v是变量,用于存储scala拉倒某一刻度返回的值,从而传给label
def print_selection(v):
l.config(text='you have selected ' + v)
# from_=,to=,横向进度条 ;length:像素宽度; resolution:精度;tickinterval:两个左边间隔的数
# 纵向:VERTICAL
s = tk.Scale(window, label='try me', from_=5, to=10, orient=tk.HORIZONTAL,
length=200, showvalue=0, tickinterval=2, resolution=0.01, command=print_selection)
s.pack()
window.mainloop()
7.Checkbutton(勾选项)
与Radiobutton类似,但是Radiobutton选中一个后其他默认为不选中,但是Checkbutton类似于多选,可以选中多个。
import tkinter as tk
window = tk.Tk()
window.title('my window')
window.geometry('200x200')
l = tk.Label(window, bg='yellow', width=20, text='empty')
l.pack()
# v是变量,用于存储scala拉倒某一刻度返回的值,从而传给label
def print_selection(v):
l.config(text='you have selected ' + v)
# from_=,to=,横向进度条 ;length:像素宽度; resolution:精度;tickinterval:两个左边间隔的数
# 纵向:VERTICAL
s = tk.Scale(window, label='try me', from_=5, to=10, orient=tk.HORIZONTAL,
length=200, showvalue=0, tickinterval=2, resolution=0.01, command=print_selection)
s.pack()
window.mainloop()
8.Canvas(画布控件)
效果就是正方形图案可以自己控制移动位置
import tkinter as tk
window = tk.Tk()
window.title('my window')
window.geometry('300x300')
# 画布控件
canvas = tk.Canvas(window, bg='blue', height=150, width=300)
image_file = tk.PhotoImage(file='life.png')
# nw 英文字母缩写左上角 0,0位置
image = canvas.create_image(0, 0, anchor='nw', image=image_file)
x0, y0, x1, y1 = 50, 50, 80, 80
line = canvas.create_line(x0, y0, x1, y1)
oval = canvas.create_oval(x0, y0, x1, y1, fill='red')
arc = canvas.create_arc(x0 + 30, y0 + 30, x1 + 30, y1 + 30, start=0, extent=180)
rect = canvas.create_rectangle(100, 30, 100 + 20, 30 + 20)
canvas.pack()
def moveit():
canvas.move(rect, 0, 2)
b = tk.Button(window, text='move', command=moveit).pack()
window.mainloop()
9.Menubar
效果:会出现类似于此界面左上角文件那一行的样式
import tkinter as tk
window = tk.Tk()
window.title('my window')
window.geometry('300x300')
# 标签控件
l = tk.Label(window, text='', bg='yellow')
l.pack()
counter = 0
def do_job():
global counter
l.config(text='do' + str(counter))
counter += 1
menubar = tk.Menu(window) # menubar在window上显示
filemenu = tk.Menu(menubar, tearoff=0) # filemenu在manubar上显示
menubar.add_cascade(label='File', menu=filemenu) # 在menubar上显示
filemenu.add_command(label='New', command=do_job)
filemenu.add_command(label='Open', command=do_job)
filemenu.add_command(label='Save', command=do_job)
filemenu.add_separator() # 分割线(上边和下边)
filemenu.add_command(label='Exit', command=window.quit) # 退出程序
editmenu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label='Edit', menu=editmenu)
editmenu.add_command(label='Cut', command=do_job)
editmenu.add_command(label='Copy', command=do_job)
editmenu.add_command(label='Paste', command=do_job)
submenu = tk.Menu(filemenu)
filemenu.add_cascade(label='Import', menu=submenu, underline=0)
submenu.add_command(label='Submenul', command=do_job)
window.config(menu=menubar) # menu栏
window.mainloop()
10.Frame(框架)
可以决定控件放置的位置
效果:
import tkinter as tk
window=tk.Tk()
window.title('my window')
window.geometry('200x200')
tk.Label(window,text='on the window').pack()
frm=tk.Frame(window)
frm.pack()
frm_l=tk.Frame(frm)
frm_r=tk.Frame(frm)
frm_l.pack(side='left')
frm_r.pack(side='right')
# 基于label的左右
tk.Label(frm_l,text='on the frm_l1').pack()
tk.Label(frm_l,text='on the frm_l2').pack()
tk.Label(frm_r,text='on the frm_r1').pack()
window.mainloop()
11.messagebox
会出现各种各样的弹窗
import tkinter as tk
from tkinter import messagebox #需要导入messagebox
window = tk.Tk()
window.title('my window')
window.geometry('200x200')
def hit_me():
# tk.messagebox.showinfo(title='Hi', message='hahahahaha') #弹窗
# tk.messagebox.showwarning(title='Hi', message='nonononono') #警告
# tk.messagebox.showerror(title='Hi', message='error') #报错
# print(tk.messagebox.askquestion(title='Hi', message='chose it') )#return yes or no
# print(tk.messagebox.askyesno(title='Hi', message='chose it')) # return True or False
# print(tk.messagebox.askretrycancel(title='Hi', message='chose it')) # return yes or no
print(tk.messagebox.askokcancel(title='Hi', message='chose it')) # return yes or no
tk.Button(window, text='hit me!', command=hit_me).pack()
window.mainloop()
12.location(位置)
可以自己决定按键的放置位置
有三种方式:1.使用pack,只能决定放在上下左右;2.grid可以进行内部扩展;3.place(最常用的一种)可以放在任意位置
import tkinter as tk
window = tk.Tk()
window.title('my window')
window.geometry('200x200')
# 上下左右
# tk.Label(window,text=1).pack(side='top')
# tk.Label(window,text=1).pack(side='bottom')
# tk.Label(window,text=1).pack(side='left')
# tk.Label(window,text=1).pack(side='right')
# for i in range(4):
# for j in range(3):
# tk.Label(window,text=1).grid(row=i,column=j,padx=10,pady=10) #内部扩展
tk.Label(window, text=1).place(x=10, y=10,anchor='nw')
window.mainloop()
13.一个测试用例
效果:一个登陆界面:可以输入账号,也可以进行注册新的账号
import tkinter as tk
from tkinter import messagebox # 导入messagebox
import pickle
window = tk.Tk()
window.title('Welcome to Mofan Python')
window.geometry('450x300')
# welcome image
canvas = tk.Canvas(window, height=200, width=500)
image_file = tk.PhotoImage(file='welcome.gif') # 导入图片
image = canvas.create_image(0, 0, anchor='nw', image=image_file)
canvas.pack(side='top') # 放在最上边
# user information 标签控件
tk.Label(window, text='User name: ').place(x=50, y=150)
tk.Label(window, text='Password: ').place(x=50, y=190)
var_usr_name = tk.StringVar()
var_usr_name.set('example@python.com')
entry_usr_name = tk.Entry(window, textvariable=var_usr_name)
entry_usr_name.place(x=160, y=150)
var_usr_pwd = tk.StringVar()
entry_usr_pwd = tk.Entry(window, textvariable=var_usr_pwd, show='*')
entry_usr_pwd.place(x=160, y=190)
def usr_login():
usr_name = var_usr_name.get()
usr_pwd = var_usr_pwd.get()
try: # pickle
with open('usrs_info.pickle', 'rb') as usr_file:
usrs_info = pickle.load(usr_file)
except FileNotFoundError:
with open('usrs_info.pickle', 'wb') as usr_file:
usrs_info = {'admin': 'admin'}
pickle.dump(usrs_info, usr_file)
if usr_name in usrs_info:
if usr_pwd == usrs_info[usr_name]:
tk.messagebox.showinfo(title='Welcome', message='How are you? ' + usr_name)
else:
tk.messagebox.showerror(message='Error, your password is wrong, try again.')
else:
is_sign_up = tk.messagebox.askyesno('Welcome',
'You have not signed up yet. Sign up today?')
if is_sign_up:
usr_sign_up()
def usr_sign_up():
def sign_to_Mofan_Python():
np = new_pwd.get()
npf = new_pwd_confirm.get()
nn = new_name.get()
with open('usrs_info.pickle', 'rb') as usr_file:
exist_usr_info = pickle.load(usr_file)
if np != npf:
tk.messagebox.showerror('Error', 'Password and confirm password must be the same!')
elif nn in exist_usr_info:
tk.messagebox.showerror('Error', 'The user has already signed up!')
else:
exist_usr_info[nn] = np
with open('usrs_info.pickle', 'wb') as usr_file:
pickle.dump(exist_usr_info, usr_file)
tk.messagebox.showinfo('Welcome', 'You have successfully signed up!')
window_sign_up.destroy()
window_sign_up = tk.Toplevel(window)
window_sign_up.geometry('350x200')
window_sign_up.title('Sign up window')
new_name = tk.StringVar()
new_name.set('example@python.com')
tk.Label(window_sign_up, text='User name: ').place(x=10, y=10)
entry_new_name = tk.Entry(window_sign_up, textvariable=new_name)
entry_new_name.place(x=150, y=10)
new_pwd = tk.StringVar()
tk.Label(window_sign_up, text='Password: ').place(x=10, y=50)
entry_usr_pwd = tk.Entry(window_sign_up, textvariable=new_pwd, show='*')
entry_usr_pwd.place(x=150, y=50)
new_pwd_confirm = tk.StringVar()
tk.Label(window_sign_up, text='Confirm password: ').place(x=10, y=90)
entry_usr_pwd_confirm = tk.Entry(window_sign_up, textvariable=new_pwd_confirm, show='*')
entry_usr_pwd_confirm.place(x=150, y=90)
btn_comfirm_sign_up = tk.Button(window_sign_up, text='Sign up', command=sign_to_Mofan_Python)
btn_comfirm_sign_up.place(x=150, y=130)
# login and sign up button
btn_login = tk.Button(window, text='Login', command=usr_login)
btn_login.place(x=170, y=230)
btn_sign_up = tk.Button(window, text='Sign up', command=usr_sign_up)
btn_sign_up.place(x=270, y=230)
window.mainloop()
(大家感兴趣可以去B站找莫烦)