python3 tkinter模块

一.tkinter

1.tkinter--tool kit interface工具包接口,用于GUI(Graphical User Interface)用户图形界面,

2.python3.x把Tkinter改写成tkinter

3.tkinter中有较多的部件:Canvas画布,PhotoImage加载图片,Label标签,messagebox消息弹窗,Entry输入,Button按钮,Frame框架,Checkbutton勾选,Radiobutton选择按钮,Menu菜单,等。

4.每个部件可以设置多种属性

二.基本

 import tkinter as tk

 #1.创建一个窗口对象,表现为一个窗口形式的图形用户界面
window = tk.Tk()
window.title('Graphical User Interface') # 窗口称谓
window.geometry('800x800') # 窗口的几何大小,长宽 #2.各种组件,注意对应的master
#2.1画布:在屏幕上显示一个矩形区域,多用来作为容器,可以添加图片,画线,画圆,正方形等
canvas = tk.Canvas(window, bg='blue', height=200, width=500)
#2.1.1加载图片,把图片的定点(‘nw’)放到画布的某个位置(10,10),anchor定点‘nw’
image_file = tk.PhotoImage(file='ins.gif')#加载图片
image = canvas.create_image(10, 100, anchor='nw', image=image_file)
#2.1.2,画其他图形
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)#扇形从角度0到角度180
rect = canvas.create_rectangle(100, 30, 100+20, 30+20)#正方形
canvas.pack(side='top') ###############################################################################
#2.2标签控件;可以显示文本和位图,[主体,文本,字体,背景,标签大小(相对于一个字符而言)等]
tk.Label(window, text='label: ',bg='green', font=('Arial', 12), width=15,height=2).place(x=200, y=150) ###############################################################################
#2.3输入控件;用于显示简单的文本内容
var_usr_name = tk.StringVar()#设定字符串变量
var_usr_name.set('example@python.com')#设定变量值
entry_usr_name = tk.Entry(window, textvariable=var_usr_name, show='*').place(x=250, y=220)#textvariable文本变量,show显示方式 ###############################################################################
#2.4弹窗,用于显示你应用程序的消息框
import tkinter.messagebox
def but():
tk.messagebox.showinfo(title='Hi', message='hahahaha') # return 'ok'#提示信息对话窗
# #tk.messagebox.showwarning(title='Hi', message='nononono') # return 'ok'#提出警告对话窗
# #tk.messagebox.showerror(title='Hi', message='No!! never') # return 'ok'#提出错误对话窗
# #print(tk.messagebox.askquestion(title='Hi', message='hahahaha')) # return 'yes' , 'no'#询问选择对话窗
# #print(tk.messagebox.askyesno(title='Hi', message='hahahaha')) # return True, False
# print(tk.messagebox.askretrycancel(title='Hi', message='hahahaha')) # return True, False
# print(tk.messagebox.askokcancel(title='Hi', message='hahahaha')) # return True, False
# print(tk.messagebox.askyesnocancel(title="Hi", message="haha")) # return, True, False, None ###############################################################################
#2.5按钮控件;在程序中显示按钮。设计一个按钮,command执行命令
bt = tk.Button(window, text='Button', command=but).place(x=200, y=300) ###############################################################################
#2.6框架
frm = tk.Frame(window,bg='blue').pack(side='bottom')#窗口主框架
frm_l = tk.Frame(frm, ).pack(side='left')#左框架
frm_r = tk.Frame(frm).pack(side='right')#右框架 ###############################################################################
#2.7勾选checkbutton用于在程序中提供多项选择框
def print_selection():
pass
var1 = tk.IntVar()#整数变量
#参数onvalue和前面讲的部件radiobutton中的value相似, 当我们选中了这个checkbutton,
# onvalue的值1就会放入到var1中, 然后var1将其赋值给参数variable,offvalue用法相似,
# 但是offvalue是在没有选中这个checkbutton时,offvalue的值1放入var1,然后赋值给参数variable 这是创建一个checkbutton部件,
# 以此类推,可以创建多个checkbutton
c1 = tk.Checkbutton(frm_l, text='A', variable=var1, onvalue=1, offvalue=0,
command=print_selection).pack(side='left') ###############################################################################
#2.8范围控件;显示一个数值刻度,为输出限定范围的数字区间
def print_selection(v):
pass
#SCALE尺度对象,从(5)到(10),orient方向(横向),在屏幕上的显示(像素的宽度高度),showvalue是否显示值
#tickinterval标签的单位长度,resolution保留位数(0.01,0.1,1.。。)
s = tk.Scale(frm_l, label='try me', from_=5, to=11, orient=tk.HORIZONTAL,
length=200, showvalue=1, tickinterval=2, resolution=0.01, command=print_selection).pack(side='left') ##########################################################################
#2.9选择按钮
var = tk.StringVar()
l4 = tk.Label(frm_r, bg='yellow', width=20, text='empty')
def print_selection():
l4.config(text='you have selected ' + var.get())#配置参数
l4.pack(side='top')
#我们鼠标选中了其中一个选项,把value的值A放到变量var中,然后赋值给variable
r1 = tk.Radiobutton(frm_r, text='Option A',variable=var, value='A',command=print_selection).pack()
r2 = tk.Radiobutton(frm_r, text='Option B',variable=var, value='B',command=print_selection).pack()
r3 = tk.Radiobutton(frm_r, text='Option C',variable=var, value='C',command=print_selection).pack() ################################################################
#2.10列表框控件;在Listbox窗口小部件是用来显示一个字符串列表给用户
var3 = tk.StringVar()#字符变量
l2 = tk.Label(window, bg='yellow', width=4, textvariable=var3).pack()
def print_selection():
value = lb.get(lb.curselection()) # 获取listbox中的值(lb中光标选定的值)
var3.set(value)
b1 = tk.Button(window, text='print selection', width=15,
height=2, command=print_selection).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() #################################################################
#3菜单:显示菜单栏,下拉菜单和弹出菜单
l6 = tk.Label(window, text='', bg='yellow').pack()
counter = 0#计数
def do_job():
global counter
l6.config(text='do '+ str(counter))#把label的text改
counter+=1
menubar = tk.Menu(window)#菜单对象
filemenu = tk.Menu(menubar, tearoff=0)#子菜单,tearoff能否分开
menubar.add_cascade(label='File', menu=filemenu)#添加子菜单,label命名
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对象的子菜单对象,不分开
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的子菜单
filemenu.add_cascade(label='Import', menu=submenu, underline=0)#
submenu.add_command(label="Submenu1", command=do_job)
window.config(menu=menubar)#改变参数 window.mainloop()#不断刷新循环(相当于while)

tkinter

python3 tkinter模块

三.pack,grid,place

1.pack自动放置,参数side可选‘top’,‘bottom’,‘right’,‘left’

2.grid以表格形式切分master,参数row和column表示行列,单元格左右间距padx,pady单元格上下间距,ipadx内部扩展

3.place以精确坐标来定位,参数anchor设定锚定点

四.登录窗口

 import tkinter as tk
from tkinter import messagebox # import this to fix messagebox error
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:
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()

登录

五.

上一篇:Tkinter添加图片


下一篇:Python3 tkinter基础 Text image 文本框中插入图片