python学习4

来源:互联网 发布:excel怎么拆分数据 编辑:程序博客网 时间:2024/05/27 06:13

Tkinter库的学习
案例:输入一个密码,对的话显示correct,错的显示incrrect

#编写一个产生随机句子的窗口函数python代码#导入模块,并定义一个窗口import Tkinter as tkimport randomwindow=tk.Tk()#定义函数#定义随机的动词函数def randVerb():    verbs=['eats','likes','hates','has']    verbs=random.choice(verbs)    return verbs#定义随机的名词函数def randNoun():    Nouns=['cats','hippos','cakes']    nouns=random.choice(Nouns)    return nouns#定义随机生成句子函数def randSentence():    name=nameEntry.get()    verb=randVerb()    noun=randNoun()    sentence=name+" "+verb+" "+noun    resultEntry.delete(0,tk.END)    resultEntry.insert(0,sentence)#定义窗口,条目entry和标签labelnameLabel= tk.Label(window,text='Name:')nameEntry= tk.Entry(window)button = tk.Button(window,text='Generate',command=randSentence)#result=tk.Entry(window)resultEntry = tk.Entry(window)resultLabel= tk.Label(window,text='resulte')#根据上述代码,一个个显示出来,用pack()函数来实现,mainloop()函数是吧这些gui控件显示到窗口上nameLabel.pack()nameEntry.pack()button.pack()resultEntry.pack()resultLabel.pack()window.mainloop()

猜数字的游戏:
猜中了得一分,猜不中不得分

import randomimport Tkinter as tkwindow=tk.Tk()maxNum=10score=0rounds=0def guessGame():    global score    global rounds    try:        guessNum=int(guessBox.get())        if 0<guessNum<=maxNum:            result=random.randrange(1,maxNum+1)            if guessNum==result:                score=score+1            rounds=rounds+1        else:            result="entry not valid!!!"    except:        result="entry not valid!!!"    resultLabel.config(text=result)    scoreLabel.config(text=str(score)+"/"+str(rounds))    guessBox.delete(0,tk.END)#定义entry和labelguessLabel = tk.Label(window,text="entry a number form 1 to "+str(maxNum))guessBox=tk.Entry(window)resultLabel=tk.Label(window)scoreLabel=tk.Label(window)button=tk.Button(window,text='guess',command=guessGame)#display the entry and labelsguessLabel.pack()guessBox.pack()resultLabel.pack()scoreLabel.pack()button.pack()window.mainloop()

注意:以上代码段应用了try………except。这是为了虽然应用了int()可以将输入数据转化为整型。但是,当输入时空或者不是一个数字的时候,就会出现错误。为了处理这个错误,采用了try。。。。except语句。如果try发生错用,自动跳到except语句中去。

0 0