一.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.每个部件可以设置多种属性
二.基本
1 import tkinter as tk 2 3 #1.创建一个窗口对象,表现为一个窗口形式的图形用户界面 4 window = tk.Tk() 5 window.title('Graphical User Interface') # 窗口称谓 6 window.geometry('800x800') # 窗口的几何大小,长宽 7 8 #2.各种组件,注意对应的master 9 #2.1画布:在屏幕上显示一个矩形区域,多用来作为容器,可以添加图片,画线,画圆,正方形等 10 canvas = tk.Canvas(window, bg='blue', height=200, width=500) 11 #2.1.1加载图片,把图片的定点(‘nw’)放到画布的某个位置(10,10),anchor定点‘nw’ 12 image_file = tk.PhotoImage(file='ins.gif')#加载图片 13 image = canvas.create_image(10, 100, anchor='nw', image=image_file) 14 #2.1.2,画其他图形 15 x0, y0, x1, y1= 50, 50, 80, 80 16 line = canvas.create_line(x0, y0, x1, y1)#画线 17 oval = canvas.create_oval(x0, y0, x1, y1, fill='red')#填满红色,画圆 18 arc = canvas.create_arc(x0+30, y0+30, x1+30, y1+30, start=0, extent=180)#扇形从角度0到角度180 19 rect = canvas.create_rectangle(100, 30, 100+20, 30+20)#正方形 20 canvas.pack(side='top') 21 22 ############################################################################### 23 #2.2标签控件;可以显示文本和位图,[主体,文本,字体,背景,标签大小(相对于一个字符而言)等] 24 tk.Label(window, text='label: ',bg='green', font=('Arial', 12), width=15,height=2).place(x=200, y=150) 25 26 ############################################################################### 27 #2.3输入控件;用于显示简单的文本内容 28 var_usr_name = tk.StringVar()#设定字符串变量 29 var_usr_name.set('example@python.com')#设定变量值 30 entry_usr_name = tk.Entry(window, textvariable=var_usr_name, show='*').place(x=250, y=220)#textvariable文本变量,show显示方式 31 32 ############################################################################### 33 #2.4弹窗,用于显示你应用程序的消息框 34 import tkinter.messagebox 35 def but(): 36 tk.messagebox.showinfo(title='Hi', message='hahahaha') # return 'ok'#提示信息对话窗 37 # #tk.messagebox.showwarning(title='Hi', message='nononono') # return 'ok'#提出警告对话窗 38 # #tk.messagebox.showerror(title='Hi', message='No!! never') # return 'ok'#提出错误对话窗 39 # #print(tk.messagebox.askquestion(title='Hi', message='hahahaha')) # return 'yes' , 'no'#询问选择对话窗 40 # #print(tk.messagebox.askyesno(title='Hi', message='hahahaha')) # return True, False 41 # print(tk.messagebox.askretrycancel(title='Hi', message='hahahaha')) # return True, False 42 # print(tk.messagebox.askokcancel(title='Hi', message='hahahaha')) # return True, False 43 # print(tk.messagebox.askyesnocancel(title="Hi", message="haha")) # return, True, False, None 44 45 ############################################################################### 46 #2.5按钮控件;在程序中显示按钮。设计一个按钮,command执行命令 47 bt = tk.Button(window, text='Button', command=but).place(x=200, y=300) 48 49 ############################################################################### 50 #2.6框架 51 frm = tk.Frame(window,bg='blue').pack(side='bottom')#窗口主框架 52 frm_l = tk.Frame(frm, ).pack(side='left')#左框架 53 frm_r = tk.Frame(frm).pack(side='right')#右框架 54 55 ############################################################################### 56 #2.7勾选checkbutton用于在程序中提供多项选择框 57 def print_selection(): 58 pass 59 var1 = tk.IntVar()#整数变量 60 #参数onvalue和前面讲的部件radiobutton中的value相似, 当我们选中了这个checkbutton, 61 # onvalue的值1就会放入到var1中, 然后var1将其赋值给参数variable,offvalue用法相似, 62 # 但是offvalue是在没有选中这个checkbutton时,offvalue的值1放入var1,然后赋值给参数variable 这是创建一个checkbutton部件, 63 # 以此类推,可以创建多个checkbutton 64 c1 = tk.Checkbutton(frm_l, text='A', variable=var1, onvalue=1, offvalue=0, 65 command=print_selection).pack(side='left') 66 67 ############################################################################### 68 #2.8范围控件;显示一个数值刻度,为输出限定范围的数字区间 69 def print_selection(v): 70 pass 71 #SCALE尺度对象,从(5)到(10),orient方向(横向),在屏幕上的显示(像素的宽度高度),showvalue是否显示值 72 #tickinterval标签的单位长度,resolution保留位数(0.01,0.1,1.。。) 73 s = tk.Scale(frm_l, label='try me', from_=5, to=11, orient=tk.HORIZONTAL, 74 length=200, showvalue=1, tickinterval=2, resolution=0.01, command=print_selection).pack(side='left') 75 76 ########################################################################## 77 #2.9选择按钮 78 var = tk.StringVar() 79 l4 = tk.Label(frm_r, bg='yellow', width=20, text='empty') 80 def print_selection(): 81 l4.config(text='you have selected ' + var.get())#配置参数 82 l4.pack(side='top') 83 #我们鼠标选中了其中一个选项,把value的值A放到变量var中,然后赋值给variable 84 r1 = tk.Radiobutton(frm_r, text='Option A',variable=var, value='A',command=print_selection).pack() 85 r2 = tk.Radiobutton(frm_r, text='Option B',variable=var, value='B',command=print_selection).pack() 86 r3 = tk.Radiobutton(frm_r, text='Option C',variable=var, value='C',command=print_selection).pack() 87 88 ################################################################ 89 #2.10列表框控件;在Listbox窗口小部件是用来显示一个字符串列表给用户 90 var3 = tk.StringVar()#字符变量 91 l2 = tk.Label(window, bg='yellow', width=4, textvariable=var3).pack() 92 def print_selection(): 93 value = lb.get(lb.curselection()) # 获取listbox中的值(lb中光标选定的值) 94 var3.set(value) 95 b1 = tk.Button(window, text='print selection', width=15, 96 height=2, command=print_selection).pack() 97 var2 = tk.StringVar() 98 var2.set((11,22,33,44))#设定变量值 99 lb = tk.Listbox(window, listvariable=var2)#列表盒子对象,列表变量 100 list_items = [1,2,3,4] 101 for item in list_items: 102 lb.insert('end', item)#列表插入(相当于文本插入) 103 lb.insert(1, 'first')#索引插入 104 lb.insert(2, 'second') 105 lb.delete(2)#索引删除 106 lb.pack() 107 108 ################################################################# 109 #3菜单:显示菜单栏,下拉菜单和弹出菜单 110 l6 = tk.Label(window, text='', bg='yellow').pack() 111 counter = 0#计数 112 def do_job(): 113 global counter 114 l6.config(text='do '+ str(counter))#把label的text改 115 counter+=1 116 menubar = tk.Menu(window)#菜单对象 117 filemenu = tk.Menu(menubar, tearoff=0)#子菜单,tearoff能否分开 118 menubar.add_cascade(label='File', menu=filemenu)#添加子菜单,label命名 119 filemenu.add_command(label='New', command=do_job)#子菜单添加功能 120 filemenu.add_command(label='Open', command=do_job) 121 filemenu.add_command(label='Save', command=do_job) 122 filemenu.add_separator()#分开的隔间(添加一条线) 123 filemenu.add_command(label='Exit', command=window.quit)#退出窗口 124 editmenu = tk.Menu(menubar, tearoff=0)#menubar对象的子菜单对象,不分开 125 menubar.add_cascade(label='Edit', menu=editmenu) 126 editmenu.add_command(label='Cut', command=do_job) 127 editmenu.add_command(label='Copy', command=do_job) 128 editmenu.add_command(label='Paste', command=do_job) 129 submenu = tk.Menu(filemenu)#filemenu的子菜单 130 filemenu.add_cascade(label='Import', menu=submenu, underline=0)# 131 submenu.add_command(label="Submenu1", command=do_job) 132 window.config(menu=menubar)#改变参数 133 134 135 window.mainloop()#不断刷新循环(相当于while)
三.pack,grid,place
1.pack自动放置,参数side可选‘top’,‘bottom’,‘right’,‘left’
2.grid以表格形式切分master,参数row和column表示行列,单元格左右间距padx,pady单元格上下间距,ipadx内部扩展
3.place以精确坐标来定位,参数anchor设定
锚定点
四.登录窗口
1 import tkinter as tk 2 from tkinter import messagebox # import this to fix messagebox error 3 import pickle 4 5 window = tk.Tk() 6 window.title('Welcome to Mofan Python') 7 window.geometry('450x300') 8 9 # welcome image 10 canvas = tk.Canvas(window, height=200, width=500) 11 image_file = tk.PhotoImage(file='welcome.gif') 12 image = canvas.create_image(0,0, anchor='nw', image=image_file) 13 canvas.pack(side='top') 14 15 # user information 16 tk.Label(window, text='User name: ').place(x=50, y= 150) 17 tk.Label(window, text='Password: ').place(x=50, y= 190) 18 19 var_usr_name = tk.StringVar() 20 var_usr_name.set('example@python.com') 21 entry_usr_name = tk.Entry(window, textvariable=var_usr_name) 22 entry_usr_name.place(x=160, y=150) 23 var_usr_pwd = tk.StringVar() 24 entry_usr_pwd = tk.Entry(window, textvariable=var_usr_pwd, show='*') 25 entry_usr_pwd.place(x=160, y=190) 26 27 def usr_login(): 28 usr_name = var_usr_name.get() 29 usr_pwd = var_usr_pwd.get() 30 try: 31 with open('usrs_info.pickle', 'rb') as usr_file: 32 usrs_info = pickle.load(usr_file) 33 except FileNotFoundError: 34 with open('usrs_info.pickle', 'wb') as usr_file: 35 usrs_info = {'admin': 'admin'} 36 pickle.dump(usrs_info, usr_file) 37 if usr_name in usrs_info: 38 if usr_pwd == usrs_info[usr_name]: 39 tk.messagebox.showinfo(title='Welcome', message='How are you? ' + usr_name) 40 else: 41 tk.messagebox.showerror(message='Error, your password is wrong, try again.') 42 else: 43 is_sign_up = tk.messagebox.askyesno('Welcome', 44 'You have not signed up yet. Sign up today?') 45 if is_sign_up: 46 usr_sign_up() 47 48 def usr_sign_up(): 49 def sign_to_Mofan_Python(): 50 np = new_pwd.get() 51 npf = new_pwd_confirm.get() 52 nn = new_name.get() 53 with open('usrs_info.pickle', 'rb') as usr_file: 54 exist_usr_info = pickle.load(usr_file) 55 if np != npf: 56 tk.messagebox.showerror('Error', 'Password and confirm password must be the same!') 57 elif nn in exist_usr_info: 58 tk.messagebox.showerror('Error', 'The user has already signed up!') 59 else: 60 exist_usr_info[nn] = np 61 with open('usrs_info.pickle', 'wb') as usr_file: 62 pickle.dump(exist_usr_info, usr_file) 63 tk.messagebox.showinfo('Welcome', 'You have successfully signed up!') 64 window_sign_up.destroy() 65 window_sign_up = tk.Toplevel(window) 66 window_sign_up.geometry('350x200') 67 window_sign_up.title('Sign up window') 68 69 new_name = tk.StringVar() 70 new_name.set('example@python.com') 71 tk.Label(window_sign_up, text='User name: ').place(x=10, y= 10) 72 entry_new_name = tk.Entry(window_sign_up, textvariable=new_name) 73 entry_new_name.place(x=150, y=10) 74 75 new_pwd = tk.StringVar() 76 tk.Label(window_sign_up, text='Password: ').place(x=10, y=50) 77 entry_usr_pwd = tk.Entry(window_sign_up, textvariable=new_pwd, show='*') 78 entry_usr_pwd.place(x=150, y=50) 79 80 new_pwd_confirm = tk.StringVar() 81 tk.Label(window_sign_up, text='Confirm password: ').place(x=10, y= 90) 82 entry_usr_pwd_confirm = tk.Entry(window_sign_up, textvariable=new_pwd_confirm, show='*') 83 entry_usr_pwd_confirm.place(x=150, y=90) 84 85 btn_comfirm_sign_up = tk.Button(window_sign_up, text='Sign up', command=sign_to_Mofan_Python) 86 btn_comfirm_sign_up.place(x=150, y=130) 87 88 # login and sign up button 89 btn_login = tk.Button(window, text='Login', command=usr_login) 90 btn_login.place(x=170, y=230) 91 btn_sign_up = tk.Button(window, text='Sign up', command=usr_sign_up) 92 btn_sign_up.place(x=270, y=230) 93 94 window.mainloop()
五.