界面
from tkinter import *
import random
#获取文本里的数字
def get_sz():
mye=en1.get()
try:
myn=int(mye)
except ValueError:
la1.config(text='需要输入数字哦!')
en1.delete(0,END)
en1.focus()
return False
except:
la1.config(text= '请输入一个1-100之间的数字!')
en1.delete(0,END)
en1.focus()
return False
if myn<1 or myn>100:
la1.config(text= '需要输入1-100之间的数字,超出范围错误!')
en1.delete(0,END)
en1.focus()
else:
return myn
#我猜按钮功能
def wocai():
global tn
if bu1['text']=='重来':
tn = random.randint(1, 100)
myn=get_sz()
if myn:
if myn==tn:
la1.config(text='恭喜你猜对了!')
en1.delete(0,END)
en1.focus()
bu1.config(text='重来')
elif myn> tn:
la1.config(text='你猜的是%s你猜大了!'%myn)
en1.delete(0,END)
bu1.config(text='再猜')
en1.focus()
else:
la1.config(text='你猜的是%s你猜小了!'%myn)
en1.delete(0,END)
bu1.config(text='再猜')
en1.focus()
tn=random.randint(1,100)
root=Tk()
root.title('猜数字游戏')
root.geometry('500x200')
myfont=("宋体",24)
la1=Label(root,text='请猜1-100之间的数字',font=myfont,bg='#a0a0a0')
la1.pack(pady=20,fill=X)
fr1=Frame(root)
fr1.pack(pady=20)
en1=Entry(fr1,font=myfont,width=10)
bu1=Button(fr1,font=("宋体",16),width=10,text='我猜',command=wocai)
en1.pack(side=LEFT,anchor=CENTER)
en1.focus()
bu1.pack(side=LEFT,anchor=CENTER)
root.mainloop()
|