tkinter 是python 自带的可编辑的GUI界面
标签和按钮
定义 window 窗口 和 window的一些属性, 然后书写窗口内容, 最后执行window.mainloop让窗口活起来。
import Tkinter as tk
window = tk.Tk()
window.title(‘my window’)
window.geometry(‘200x100’)
window.mainloop()
建立一个用来描述的标签 tk.Label, 比如
l = tk.Label(window,
text='OMG! this is TK!', # 标签的文字
bg='green', # 背景颜色
font=('Arial', 12), # 字体和字体大小
width=15, height=2 # 标签长宽
)
l.pack() # 固定窗口位置
引入按钮 tk.Button 的概念, 每点一次按钮, 标签变化一次. 用以下内容替换上面的标签. 并把需要变化的文字存成变量 var
var = tk.StringVar() # 这时文字变量储存器
l = tk.Label(window,
textvariable=var, # 使用 textvariable 替换 text, 因为这个可以变化
bg='green', font=('Arial', 12), width=15, height=2)
l.pack()
接着我们来做 按钮 tk.Button:
b = tk.Button(window,
text='hit me', # 显示在按钮上的文字
width=15, height=2,
command=hit_me) # 点击按钮式执行的命令
b.pack() # 按钮位置
点击是的命令用 if else 语句来判断. 用 on_hit 来判断当前状态。
on_hit = False # 默认初始状态为 False
var = tk.StringVar() # 这时文字变量储存器
def hit_me():
global on_hit
if on_hit == False: # 从 False 状态变成 True 状态
on_hit = True
var.set('you hit me') # 设置标签的文字为 'you hit me'
else: # 从 True 状态变成 False 状态
on_hit = False
var.set('') # 设置 文字为空
完整代码:
import Tkinter as tk
window = tk.Tk()
window.title('my window')
window.geometry('200x100')
on_hit = False # 默认初始状态为 False
var = tk.StringVar() # 这时文字变量储存器
def hit_me():
global on_hit
if on_hit == False: # 从 False 状态变成 True 状态
on_hit = True
var.set('you hit me') # 设置标签的文字为 'you hit me'
else: # 从 True 状态变成 False 状态
on_hit = False
var.set('') # 设置 文字为空
l = tk.Label(window,
textvariable=var, # 使用 textvariable 替换 text, 因为这个可以变化
bg='green', font=('Arial', 12), width=15, height=2)
l.pack()
b = tk.Button(window,
text='hit me', # 显示在按钮上的文字
width=15, height=2,
command=hit_me) # 点击按钮式执行的命令
b.pack() # 按钮位置
window.mainloop()
Entry & Text
实例
插入文本测试
import Tkinter as tk
window = tk.Tk()
window.title(‘my window’)
window.geometry(‘500x500’)
#因为Python的执行顺序是从上往下,所以函数一定要放在按钮的上面
def insert_point():
var = e.get()
t.insert(‘insert’,var)
def insert_end():
var = e.get()
t.insert('end',var)
#创建输入框entry,用户输入任何内容都显示为*
e = tk.Entry(window,show='*')
e.pack()
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()
listbox
import Tkinter as tk
window = tk.Tk()
window.title('my window')
window.geometry('500x500')
var1 = tk.StringVar()
l = tk.Label(window, bg='yellow', width=4, textvariable=var1)
l.pack()
def print_selection():
value = lb.get(lb.curselection())
var1.set(value)
b1 = tk.Button(window, text='print selection', width=15,
height=2, command=print_selection)
b1.pack()
var2 = tk.StringVar()
var2.set((11,22,33,44))
lb = tk.Listbox(window, listvariable=var2)
list_items = [1,2,3,4]
for item in list_items:
lb.insert('end', item)
lb.insert(1, 'first')
lb.insert(2, 'second')
lb.delete(2)
lb.pack()
window.mainloop()
选择按钮
#-*-coding:utf-8 -*-
import Tkinter as tk
window = tk.Tk()
window.title('my window')
window.geometry('500x500')
var = tk.StringVar()
l = tk.Label(window, bg='yellow', width=20, text='empty')
l.pack()
def print_selection():
l.config(text='you have selected ' + var.get())
r1 = tk.Radiobutton(window, text='Option A',
variable=var, value='A',
command=print_selection)
r1.pack()
r2 = tk.Radiobutton(window, text='Option B',
variable=var, value='B',
command=print_selection)
r2.pack()
r3 = tk.Radiobutton(window, text='Option C',
variable=var, value='C',
command=print_selection)
r3.pack()
window.mainloop()
尺度
会返回一个具体的数字
#-*-coding:utf-8 -*-
import Tkinter as tk
window = tk.Tk()
window.title('my window')
window.geometry('500x500')
l = tk.Label(window, bg='yellow', width=20, text='empty')
l.pack()
def print_selection(v):
l.config(text='you have selected ' + v)
s = tk.Scale(window, label='try me', from_=1, to=11, orient=tk.HORIZONTAL,
length=200, showvalue=0, tickinterval=2, resolution=0.01, command=print_selection)
s.pack()
window.mainloop()
勾选项 多选
#-*-coding:utf-8 -*-
import Tkinter as tk
window = tk.Tk()
window.title('my window')
window.geometry('500x500')
l = tk.Label(window, bg='yellow', width=20, text='empty')
l.pack()
def print_selection():
if (var1.get() == 1) & (var2.get() == 0):
l.config(text='I love only Python ')
elif (var1.get() == 0) & (var2.get() == 1):
l.config(text='I love only C++')
elif (var1.get() == 0) & (var2.get() == 0):
l.config(text='I do not love either')
else:
l.config(text='I love both')
var1 = tk.IntVar()
var2 = tk.IntVar()
c1 = tk.Checkbutton(window, text='Python', variable=var1, onvalue=1, offvalue=0,
command=print_selection)
c2 = tk.Checkbutton(window, text='C++', variable=var2, onvalue=1, offvalue=0,
command=print_selection)
c1.pack()
c2.pack()
window.mainloop()
Canvas 画布
#-*-coding:utf-8 -*-
import Tkinter as tk
window = tk.Tk()
window.title('my window')
window.geometry('500x500')
canvas = tk.Canvas(window, bg='blue', height=400, width=400)
image_file = tk.PhotoImage(file='opk.gif')
image = canvas.create_image(10, 10, 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()
Menubar 菜单
#-*-coding:utf-8 -*-
import Tkinter as tk
window = tk.Tk()
window.title('my window')
window.geometry('500x500')
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)
filemenu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label='File', menu=filemenu)
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="Submenu1", command=do_job)
window.config(menu=menubar)
window.mainloop()
Frame 框架
#-*-coding:utf-8 -*-
import Tkinter as tk
window = tk.Tk()
window.title('my window')
window.geometry('500x500')
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')
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()
messagebox 弹窗
#-*-coding:utf-8 -*-
import Tkinter as tk
window = tk.Tk()
window.title('my window')
window.geometry('500x500')
def hit_me():
tk.messagebox.showinfo(title='Hi', message='hahahaha')
tk.messagebox.showwarning(title='Hi', message='nononono')
tk.messagebox.showerror(title='Hi', message='No!! never')
print(tk.messagebox.askquestion(title='Hi', message='hahahaha')) # return 'yes' , 'no'
print(tk.messagebox.askyesno(title='Hi', message='hahahaha')) # return True, False
tk.Button(window, text='hit me', command=hit_me).pack()
window.mainloop()
pack grid place 放置位置
主要是3种方法
- grid
- pack
place
#-*-coding:utf-8 -*- import Tkinter as tk window = tk.Tk() window.title('my window') window.geometry('500x500') canvas = tk.Canvas(window, height=150, width=500) canvas.grid(row=1, column=1) image_file = tk.PhotoImage(file='opk.gif') image = canvas.create_image(0, 0, anchor='nw', image=image_file) #1 #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') #2 for i in range(4): for j in range(3): tk.Label(window, text=1).grid(row=i, column=j, padx=10, pady=10) #3 # tk.Label(window, text=1).place(x=20, y=10, anchor='nw') window.mainloop()
登录窗口
#-*-coding:utf-8 -*-
import Tkinter as tk
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='opk.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:
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 sign up yet. Sign up today?')
if is_sign_up:
usr_sign_up()
def usr_sign_up():
pass
# 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()