Python實現拼寫單詞的小遊戲

  先看一下大概的效果,瞭解一下小遊戲的功能,再看源碼
 

 

 

 

 

 

 
import  tkinter as tk
import  random
def e_btn_close(event):
    root.destroy()
def e_btn_guess(event):
    if word == entry_a.get():
        result = "恭喜你猜對了!"
    else:
        result ="很遺憾猜錯了!"
    textvar.set(result)
def e_btn_reset(event):
    entry_a.delete(0,'end')
    textvar.set("")
def e_btn_change(event):
     global word
     word = random.choice(words)
     jumble="".join(random.sample(word,len(word)))
     textguess.set("您要猜的單詞包含字母爲:"+jumble)
     entry_a.delete(0,'end')
     textvar.set("")
 
words = ["hello","summer","January","February","Marcy","April","May","June",\
         "July","August","September","October","November","December"]
word = random.choice(words)
jumble = "".join(random.sample(word,len(word)))
root = tk.Tk(className= "猜單詞")
root.geometry("400x200+200+200")
textguess=tk.StringVar()
textguess.set ("您要猜的單詞包含字母爲:"+jumble)
lable_word=tk.Label(root,width=80,textvariable=textguess)
lable_word.pack(side = "top",anchor = "nw",padx = 10)
root1 = tk.Tk(className= "換一個")
root1.geometry("400x200+200+200")
lable_word = tk.Label(root1,width = 80,text =word)
lable_word.pack(side = "top",anchor = "nw",padx = 10)
entry_a = tk.Entry(root,width = "40")   #建立單行文本,
entry_a.pack(side = "top",padx = 10)    #佈局單行文本框,
entry_a.bind('<Return>',e_btn_guess)    #綁定單行文本框中的回車鍵事件函數
fm1 = tk.Frame(root)                   #建立子框架窗體
fm1.pack(side = 'top',fill = 'both')   #佈局子框架窗體
btn_guess = tk.Button(fm1,text = '提交')#建立轉換按鈕,在子窗體中
btn_reset = tk.Button(fm1,text ="重置")
btn_change =tk.Button(fm1,text='換一個')
btn_close =tk.Button(fm1,text='關閉')        #建立關閉按鈕,在子窗體中

btn_guess.pack(side = "left",padx = 10)           #佈局轉換按鈕
btn_guess.bind('<Button-1>',e_btn_guess)#綁定轉換按鈕,單擊事件函數
btn_reset.pack(side = "left",padx = 10)
btn_reset.bind('<Button-1>',e_btn_reset)
btn_change.pack(side = "left",padx = 10)     
btn_change.bind('<Button-1>',e_btn_change)
btn_close.pack(side = "left",padx = 10)      #佈局關閉按鈕
btn_close.bind('<Button-1>',e_btn_close)     #綁定關閉按鈕,單擊事件函數

# 下面是建立結果標籤
textvar = tk.StringVar()    #建立容器變量
# 建立結果標籤,其中的顯示內容爲容器變量
lable_conversion = tk.Label(root,width = '80',textvariable = textvar,anchor = 'w')
lable_conversion.pack(side = 'top',padx = 10)  #佈局結果標籤
entry_a.focus_set()  #單行文本框得到焦點
root.mainloop()
相關文章
相關標籤/搜索