一、实验内容
1、登录界面
2、制作菜单栏
3、实现聊天窗口
4、访问本地一张照片并展示
二、实验过程
1、
import tkinter as tk
import tkinter.messagebox
import pickleroot = tkinter.Tk()
root.geometry('400x300')
root.title("武理工欢迎你!")# 画布
canvas = tkinter.Canvas(root, width=400, height=300)
pic = tkinter.PhotoImage(file='C:\\Users\\admin\\Desktop\\a.gif')
image = canvas.create_image(0, 0, anchor='nw', image=pic)
canvas.pack(side='top')# 登录界面,用户、密码
label1 = tkinter.Label(root, text='账号:')
label1.place(x=80, y=80)
label2 = tkinter.Label(root, text='密码:')
label2.place(x=80, y=120)var_usr_name = tkinter.StringVar()
entry_usr_name = tkinter.Entry(root, textvariable=var_usr_name)
entry_usr_name.place(x=130, y=80)var_usr_pwd = tkinter.StringVar()
entry_usr_pwd = tkinter.Entry(root, textvariable=var_usr_pwd, show='*')
entry_usr_pwd.place(x=130, y=120)def usr_log_in():usr_name = var_usr_name.get()user_pwd = var_usr_pwd.get()# 从本地字典获取用户信息,如果没有则新建本地数据库try:with open('usr_info.pickle', 'rb') as usr_file:usrs_info = pickle.load(usr_file)except FileNotFoundError:with open('usr_info.pickle', 'wb') as usr_file:usrs_info = {'admin': 'admin'}pickle.dump(usrs_info, usr_file)if usr_name in usrs_info:if user_pwd in usrs_info[usr_name]:tkinter.messagebox.showinfo(title='welcome', message=usr_name + '欢迎登录')else:tkinter.messagebox.showerror(title='tip', message='密码错误,请重新输入!')elif usr_name == '' or user_pwd == '':tkinter.messagebox.showerror(title='tip', message='用户名或密码为空!')else:go_signup = tkinter.messagebox.askyesno('欢迎', '你还没注册,是否现在去注册?')if go_signup:usr_sign_up()def usr_sign_up():# 确认注册时的相应函数def signtowcg():# 获取输入框内的内容nn = new_name.get()np = new_pwd.get()npf = new_pwd_confirm.get()# 本地加载已有用户信息,如果没有则已有用户信息为空try:with open('usr_info.pickle', 'rb') as usr_file:exist_usr_info = pickle.load(usr_file)except FileNotFoundError:exist_usr_info = {}# 检查用户名存在、密码为空、密码前后不一致if nn in exist_usr_info:tk.messagebox.showerror('错误', '用户名已存在')elif np == '' or nn == '':tk.messagebox.showerror('错误', '用户名或密码为空')elif np != npf:tk.messagebox.showerror('错误', '密码前后不一致')# 注册信息没有问题则将用户名密码写入数据库else:exist_usr_info[nn] = npwith open('usr_info.pickle', 'wb') as usr_file:pickle.dump(exist_usr_info, usr_file)tk.messagebox.showinfo('欢迎', '注册成功')# 注册成功关闭注册框window_sign_up.destroy()# 新建注册界面window_sign_up = tk.Toplevel(root)window_sign_up.geometry('350x200')window_sign_up.title('注册')# 用户名变量及标签、输入框new_name = tk.StringVar()tk.Label(window_sign_up, text='用户名:').place(x=10, y=10)tk.Entry(window_sign_up, textvariable=new_name).place(x=150, y=10)# 密码变量及标签、输入框new_pwd = tk.StringVar()tk.Label(window_sign_up, text='请输入密码:').place(x=10, y=50)tk.Entry(window_sign_up, textvariable=new_pwd, show='*').place(x=150, y=50)# 重复密码变量及标签、输入框new_pwd_confirm = tk.StringVar()tk.Label(window_sign_up, text='请再次输入密码:').place(x=10, y=90)tk.Entry(window_sign_up, textvariable=new_pwd_confirm, show='*').place(x=150, y=90)# 确认注册按钮及位置bt_confirm_sign_up = tk.Button(window_sign_up, text='确认注册',command=signtowcg)bt_confirm_sign_up.place(x=150, y=130)def usr_sign_quit():root.destroy()# 按钮,登录、注册、退出
bt_login = tkinter.Button(root, text="登录", command=usr_log_in)
bt_login.place(x=80, y=220)
bt_sign_up = tkinter.Button(root, text="注册", command=usr_sign_up)
bt_sign_up.place(x=160, y=220)
bt_sign_quit = tkinter.Button(root, text="退出", command=usr_sign_quit)
bt_sign_quit.place(x=240, y=220)root.mainloop()2、
from tkinter import *top = Tk()
top.wm_title("菜单")
top.geometry("400x300+800+200")# 创建一个菜单项,类似于导航栏
menubar = Menu(top)# 创建菜单项
fmenu1 = Menu(top)
for item in ['新建', '打开', '保存', '另存为']:# 如果该菜单时顶层菜单的一个菜单项,则它添加的是下拉菜单的菜单项。fmenu1.add_command(label=item)fmenu2 = Menu(top)
for item in ['复制', '粘贴', '剪切']:fmenu2.add_command(label=item)fmenu3 = Menu(top)
for item in ['默认视图', '新式视图']:fmenu3.add_command(label=item)fmenu4 = Menu(top)
for item in ["版权信息", "其他说明"]:fmenu4.add_command(label=item)# add_cascade 的一个很重要的属性就是 menu 属性,它指明了要把那个菜单级联到该菜单项上,
# 当然,还必不可少的就是 label 属性,用于指定该菜单项的名称
menubar.add_cascade(label="文件", menu=fmenu1)
menubar.add_cascade(label="编辑", menu=fmenu2)
menubar.add_cascade(label="视图", menu=fmenu3)
menubar.add_cascade(label="关于", menu=fmenu4)# 最后可以用窗口的 menu 属性指定我们使用哪一个作为它的顶层菜单
top['menu'] = menubar
top.mainloop()3、
import os
from PIL import Image
import tkinter
import tkinter.filedialog
import tkinter.messageboxclass Window():def __init__(self):self.root = root = tkinter.Tk()self.menu = tkinter.Menu(root)self.submenu = tkinter.Menu(self.menu, tearoff=0)self.submenu.add_command(label='作者: 王小五同學')root.config(menu=self.submenu)self.Image = tkinter.StringVar()self.Image.set('.bmp')self.mstatus = tkinter.IntVar()self.fstatus = tkinter.IntVar()self.mstatus.set(0)self.fstatus.set(0)self.status = tkinter.StringVar()self.label = tkinter.Label(root, text='输入百分比')self.label.place(x=5, y=5)self.entryNew = tkinter.Entry(root)self.entryNew.place(x=70, y=5)self.checkM = tkinter.Checkbutton(self.root, text='批量转换', command=self.OnCheckM, variable=self.mstatus,onvalue=1, offvalue=0)self.checkM.place(x=5, y=30)self.label = tkinter.Label(root, text='选择文件')self.label.place(x=5, y=55)self.entryFile = tkinter.Entry(root)self.entryFile.place(x=70, y=55)self.BrowserFileButton = tkinter.Button(root, text='浏览', command=self.BrowserFile)self.BrowserFileButton.place(x=220, y=55)self.label = tkinter.Label(root, text='选择目录')self.label.place(x=5, y=90)self.entryDir = tkinter.Entry(root, state=tkinter.DISABLED)self.entryDir.place(x=70, y=90)self.BrowserDirButton = tkinter.Button(root, text='浏览', command=self.BrowserDir, state=tkinter.DISABLED)self.BrowserDirButton.place(x=220, y=90)self.checkF = tkinter.Checkbutton(root, text='改变文件格式', onvalue=1, offvalue=0, variable=self.fstatus,command=self.OnCheckF)self.checkF.place(x=5, y=120)frame = tkinter.Frame(root, )frame.place(x=10, y=150)self.rBmp = tkinter.Radiobutton(frame, variable=self.Image, value='.bmp', text='BMP', state=tkinter.DISABLED)self.rBmp.pack(anchor='w')self.rJpg = tkinter.Radiobutton(frame, variable=self.Image, value='.jpg', text='JPG', state=tkinter.DISABLED)self.rJpg.pack(anchor='w')self.rPng = tkinter.Radiobutton(frame, variable=self.Image, value='.png', text='PNG', state=tkinter.DISABLED)self.rPng.pack(anchor='w')self.rGif = tkinter.Radiobutton(frame, variable=self.Image, value='.gif', text='GIF', state=tkinter.DISABLED)self.rGif.pack(anchor='w')self.ButtonCov = tkinter.Button(root, text='转换格式', command=self.Conv, )self.ButtonCov.place(x=120, y=180)self.statusLabel = tkinter.Label(root, textvariable=self.status, fg='red')self.statusLabel.place(x=80, y=220)def OnCheckM(self):if not self.mstatus.get():self.entryDir.config(state=tkinter.DISABLED)self.entryFile.config(state=tkinter.NORMAL)self.BrowserFileButton.config(state=tkinter.NORMAL)self.BrowserDirButton.config(state=tkinter.DISABLED)else:self.entryDir.config(state=tkinter.NORMAL)self.entryFile.config(state=tkinter.DISABLED)self.BrowserFileButton.config(state=tkinter.DISABLED)self.BrowserDirButton.config(state=tkinter.NORMAL)def OnCheckF(self):if not self.fstatus.get():self.rBmp.config(state=tkinter.DISABLED)self.rPng.config(state=tkinter.DISABLED)self.rJpg.config(state=tkinter.DISABLED)self.rGif.config(state=tkinter.DISABLED)else:self.rBmp.config(state=tkinter.NORMAL)self.rPng.config(state=tkinter.NORMAL)self.rJpg.config(state=tkinter.NORMAL)self.rGif.config(state=tkinter.NORMAL)def BrowserFile(self):file = tkinter.filedialog.askopenfilename(title='Python player',filetypes=[('JPG', '*.jpg'), ('BMP', '*.bmp'), ('GIF', '*.gif'),('PNG', '*.png')])if file:self.entryFile.delete(0, tkinter.END)self.entryFile.insert(tkinter.END, file)def BrowserDir(self):directory = tkinter.filedialog.askdirectory(title='Python')if directory:self.entryDir.delete(0, tkinter.END)self.entryDir.insert(tkinter.END, directory)def make(self, file, format=None):im = Image.open(file)mode = im.modeif mode not in ('L', 'RGB'):im = im.convert('RGB')width, height = im.sizes = self.entryNew.get()if s == '':tkinter.messagebox.showerror('出错啦', '请输入百分比')returnelse:n = int(s)nwidth = int(width * n / 100)nheight = int(height * n / 100)thumb = im.resize((nwidth, nheight), Image.ANTIALIAS)if format:thumb.save(file[:(len(file) - 4)] + '_thumb' + format)else:thumb.save(file[:(len(file) - 4)] + '_thumb' + file[-4:])def Conv(self):n = 0if self.mstatus.get():path = self.entryDir.get()if path == "":tkinter.messagebox.showerror('出错啦', '请选择路径')returnfilenames = os.listdir(path)if self.fstatus.get():f = self.Image.get()print(f)for filename in filenames:if filename[-3:] in ('bmp', 'jpg', 'gif', 'png'):self.make(path + '/' + filename, f)n += 1else:for filename in filenames:if filename[-3:] in ('bmp', 'jpg', 'gif', 'png'):self.make(path + '/' + filename)n += 1else:file = self.entryFile.get()if file == '':tkinter.messagebox.showerror('出错啦', '请选择文件')returnif self.fstatus.get():f = self.Image.get()self.make(file, f)n += 1else:self.make(file)n += 1self.status.set('成功转换 %d 张图片' % n)def mainloop(self):self.root.minsize(280, 270)self.root.maxsize(280, 250)self.root.title('图片转换')self.root.mainloop()if __name__ == "__main__":window = Window()window.mainloop()4、
import tkinter
from tkinter import *
import timeroot = Tk()
root.title("ergou")# root.geometry("650x750")# 定义函数
def msgsend():msg = '我' + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + '\n'msg_list.insert(END, msg, 'green') # 添加时间msg_list.insert(END, sen_msg.get('0.0', END)) # 获取发送消息,添加文本到消息列表sen_msg.delete('0.0', END) # 清空发送消息'''定义取消发送 消息 函数'''def cancel():msg_list.delete('0.0', END) # 取消发送消息,即清空发送消息# 定义大框架
f_msg = tkinter.Frame(width=300, height=300)
msg_sen = tkinter.Frame(width=300, height=300)
f_bottom = tkinter.Frame(width=300, height=100)
f_img = tkinter.Frame(width=100, height=700)# 给框架里添加标签
msg_list = tkinter.Text(f_msg)
msg_list.tag_config('green', foreground='blue')sen_msg = tkinter.Text(msg_sen)
bt_send = tkinter.Button(f_bottom, text='send', command=msgsend)
bt_cancel = tkinter.Button(f_bottom, text='cancel', command=cancel)pic = PhotoImage(file=r'C:\\Users\\admin\\Desktop\\a.gif')
img = tkinter.Label(f_img, image=pic)
# img.image = pic
pic2 = PhotoImage(file=r'C:\\Users\\admin\\Desktop\\a.gif')
img2 = tkinter.Label(f_img, image=pic2)msg_list.grid()
sen_msg.grid()
bt_send.grid(row=0, column=0)
bt_cancel.grid(row=0, column=1)
img.grid()
img2.grid(ipady=8)5、
import tkinter
import tkinter.filedialog
top = tkinter.Tk()
top.title = 'new'
top.geometry('640x480')def choose_fiel():selectFileName = tkinter.filedialog.askopenfilename(title='选择文件') # 选择文件e.set(selectFileName)e = tkinter.StringVar()
e_entry = tkinter.Entry(top, width=68, textvariable=e)
e_entry.pack()submit_button = tkinter.Button(top, text ="选择文件", command = choose_fiel)
submit_button.pack()from PIL import Image, ImageTk
def showImg(img1):load = Image.open(img1)render = ImageTk.PhotoImage(load)img = tkinter.Label(image=render)img.image = renderimg.pack()submit_button = tkinter.Button(top, text ="显示图片", command = lambda :showImg(showImg(e_entry.get())))
submit_button.pack()
top.mainloop()
三、实验结果
1、
2、
3、
4、