题
-
Tkinter实现用户登录界面。建立一个文本文件users.txt,其中每一行存储一个用户的名字和密码,二者之间使用冒号分割,例如“admin:123456”。用户输入名字和密码后,单击“Login”按钮,根据文件users.txt中存储的信息判断用户输入是否正确。如果不正确就提示“用户名或者密码不正确”,如果正确就提示“登录成功”。请将界面中的文字全部改为中文。
-
编写带有图形化界面的猜数字游戏,数字为100以内整数。用户输入猜测值,如果正确,弹出“您猜对了!”消息框,否则提示“猜小了”或者“猜大了”消息框。
代码
第一题
思路:首先利用tkinter的Lable来构建主要的功能,然后在按题目给定的文件名来打开文件因为这里题目给定的条件是每一行所一定使用到readlines()来把每一行的转化为列表,然后在利用split(‘:’)来用分开这样做的就是为了然后就可以赋给两个变量了,然后在利用该两个变量与用户输入的姓名与密码分别进行比较然后在利用Button创建按钮,用command来调用方法即可,还厚就是quit退出。
import tkinter
denglu=tkinter.Tk()
denglu['height']=200
denglu['width']=280
denglu.title("用户登录")
Name=tkinter.Label(denglu,text='用户姓名',
justify=tkinter.RIGHT,anchor='e'
,width=100)
Name.place(x=10,y=5,width=90,height=30)
UserName=tkinter.Entry(denglu,width=100)
UserName.place(x=120,y=5,width=120,height=30)
Name=tkinter.Label(denglu,text='用户密码',
justify=tkinter.RIGHT,anchor='e'
,width=100)
Name.place(x=10,y=60,width=90,height=30)
Possword=tkinter.Entry(denglu,width=100,show='*')
Possword.place(x=120,y=60,width=120,height=30)
filepath='C:/Users/22231/Desktop/users.txt'
def file():
with open(filepath,'r') as f:
for line in f.readlines():
name,pwd=line.strip().split(':')
if UserName.get()==name and Possword.get()==pwd:
tkinter.messagebox.showinfo(title='成功',message="登录成功")
return
tkinter.messagebox.showinfo(title='失败',message="密码或用户名有误")
return
Button1=tkinter.Button(denglu,text="登录",width=100
,command=file)
Button1.place(x=20,y=130,width=100,height=30)
def Quit():
denglu.quit()
Button2=tkinter.Button(denglu,text="退出",width=100,command=Quit)
Button2.place(x=150,y=130,width=100,height=30)
denglu.mainloop()
运行结果截图:
第二题
思路:也是首先创建一个适应的窗口,然后就是创建一个文本框,然后在利用get()来获取文本框内输入的内容然后在比较随机形成的数NUM与entry.get()来比较输出对应的提示,后面就使用一个按钮来判断是否猜对即可。
import tkinter
import random
caishuzi=tkinter.Tk()
caishuzi.title("猜数字")
caishuzi['width']=280
caishuzi['height']=100
Name=tkinter.Label(caishuzi,text='请输入数字:',width=80)
Name.place(x=5,y=10,width=80,height=20)
entry=tkinter.Entry(caishuzi,width=80)
entry.place(x=100,y=10,width=130,height=20)
NUM=random.randint(1,100)
def caishu():
try:
if NUM>int(entry.get()):
tkinter.messagebox.showinfo(title="差一点成功"
,message="猜小了")
return
elif NUM<int(entry.get()):
tkinter.messagebox.showinfo(title="差一点成功"
,message="猜大了")
return
elif NUM==int(entry.get()):
tkinter.messagebox.showinfo(title="成功"
,message="恭喜你猜对了")
return
except ValueError:
tkinter.messagebox.showinfo(title="输入有误"
,message="输入中有字符!")
return
judge=tkinter.Button(caishuzi,text="开始判断",width=80,command=caishu)
judge.place(x=100,y=40,width=130,height=20)
caishuzi.mainloop()
运行结果截图:
用到的方法:
1.tkinter.Label()
2.tkinter.Button()
3.tkinter.Entry()