https://blog.csdn.net/qq

编程入门 行业动态 更新时间:2024-10-23 08:26:00

https://<a href=https://www.elefans.com/category/jswz/34/1768312.html style=blog.csdn.net/qq"/>

https://blog.csdn.net/qq

利用爬虫技术获取英语单词,并通过tkinter库实现猜单词游戏
效果图如下:

你需要掌握的知识:
1.tkinter库
2.爬虫技术

总之,简单易懂,源代码如下。

#无网络条件下的单词表# words=['abstract', 'abstraction', 'accomplish', 'accuracy', 'affiliated', 'algorithm', 'algorithmic', 'alias', 'aliasing', 'allocate', 'alternative', 'ambiguous', 'anticipate', 'apparatus', 'arbitrary', 'archery', 'architecture', 'argument', 'arithmetic', 'ascending', 'assert', 'assignment', 'asymptotic', 'automobile', 'balance', 'binary', 'bind', 'bisection', 'blank', 'block', 'bookmark', 'bound', 'bundle', 'calculator', 'canopy', 'capitalize', 'capture', 'cardiovascular', 'cascade', 'category', 'checker', 'circumference', 'clause', 'clue', 'cluster', 'code', 'coherent', 'collection', 'comma', 'command', 'comparison', 'compiler', 'complexity', 'compound', 'computable', 'computation', 'computational', 'compute', 'concatenate', 'concatenation', 'conceptualize', 'conditional', 'configuration', 'conform', 'conquer', 'console', 'construct', 'convert', 'correspond', 'corresponding', 'covert', 'crash', 'crucial', 'cube', 'cumbersome', 'current', 'dealt', 'debug', 'decimal', 'declarative', 'decode', 'deduce', 'default', 'defensive', 'demo', 'denote', 'deposit', 'derivative', 'deviation', 'diagram', 'dictionary', 'difference', 'disc', 'discretion', 'disregard', 'distinct', 'distribution', 'division', 'divisor', 'doctorate', 'documentation', 'driver', 'dub', 'duplicate', 'ease', 'editor', 'encapsulate', 'encapsulation', 'endpoint', 'engage', 'enigma', 'enroll', 'entry', 'enumeration', 'environment', 'epsilon', 'equivalent', 'essentially', 'evaluate', 'exception', 'execute', 'exhaustive', 'exponentiation', 'exterminate', 'factorial', 'fetal', 'fix', 'flag', 'flexibility', 'float', 'formalism', 'fraction', 'frame', 'generalization', 'generate', 'gestation', 'gigabyte', 'guarantee', 'GUI', 'halt', 'handle', 'handler', 'hence', 'heuristic', 'hierarchy', 'hint', 'hypothesis', 'identifier', 'illustrate', 'immutable', 'imperative', 'implement', 'implementation', 'implication', 'import', 'inclusive', 'incorporate', 'increment', 'indentation', 'index', 'indicate', 'indication', 'indirection', 'induction']##猜单词游戏,利用网络爬虫实现单词库的获取,请在有网络的情况下使用import random
import time
from urllib import request
from lxml import  etree
import tkinter as tk
from tkinter import*
from tkinter import ttk#利用tkinter库实现
#词汇表
words=[]
class Guess_word:def __init__(self):self.get_words() self.win_times=0self.lose_times=0self.final_time=' 'self.gui()  def get_words(self):def Get_Shanbay(page):url="/?page=%s"%pagersp=request.urlopen(url)html=rsp.read()html=etree.HTML(html)tr_list=html.xpath("//tr")for tr in tr_list:      strong = tr.xpath('.//strong')if len(strong):name=strong[0].text.strip()words.append(name)for i in range(1,10):Get_Shanbay(i)print('爬取单词中……')def shuffle_word(self,word):list_word=list(word)random.shuffle(list_word)return ''.join(list_word)def gui(self):self.start()self.main_gui()def main_gui(self):self.root=Tk()self.root.title('hangman')self.root.geometry('+0+0')self.root.geometry('1000x800') Label(self.root,text="Welcome to the word guessing game!", bg='green',font=('Arial', 12), fg="white",width=50, height=2).pack() number=tk.StringVar()self.Listchoose=ttk.Combobox(self.root,width=12,textvariable=number,state='readonly')self.Listchoose['values']=['娱乐模式','时间模式']    self.Listchoose.bind("<<ComboboxSelected>>",self.mode)self.Listchoose.pack()    self.Listchoose.set('请选择游戏模式') self.root.mainloop()def mode(self,event):self.root2=Tk()self.root2.title('hangman')self.root2.geometry('+0+0')self.root2.geometry('1000x800')self.label=Label(self.root2,text="Welcome to the word guessing game!", bg='green',font=('Arial', 12), fg="white",width=50, height=2)self.label.pack()self.button2=tk.Button(self.root2,text="退出",bd=4,bg="yellow",activebackground="orange",command=self.Quit,padx=100)self.button2.pack(side=tk.LEFT)mode_name=self.Listchoose.get()    if(mode_name=='娱乐模式'):self.mode1()else:self.mode2()self.root2.mainloop()def mode1(self):self.display()def judge(event):if self.entry.get()==self.correct_word:self.win_times+=1self.label.configure(text="Congratulations! You're right! ",bg='red')else:self.lose_times+=1self.label.configure(text="Sorry! You're wrong! And the correct word is "+self.correct_word+".",bg='blue')self.entry.bind("<Return>",judge) self.button1=tk.Button(self.root2,text="下一题",bd=4,bg="orange",activebackground="yellow",command=self.next1,padx=100)self.button1.pack(side=tk.RIGHT)def mode2(self):messagebox.showinfo("提醒","请在十秒之前内写出你的答案!")self.get_final_time()self.get_time()self.display()def judge(event):self.final_time=' 'if self.entry.get()==self.correct_word:self.win_times+=1messagebox.showinfo("correct!","Congratulations! You're right!")self.time_over('0003.gif','耶!')self.label.configure(text="Congratulations! You're right! ",bg='red')else:self.lose_times+=1messagebox.showinfo("Wrong answer","Sorry! You're wrong! And the correct word is "+self.correct_word+".")self.time_over('0004.gif','呜呜~')self.label.configure(text="Sorry! You're wrong! And the correct word is "+self.correct_word+".",bg='blue')self.entry.bind("<Return>",judge) self.button2=tk.Button(self.root2,text="下一题",bd=4,bg="orange",activebackground="yellow",command=self.next2,padx=100)self.button2.pack(side=tk.RIGHT)def display(self):self.correct_word,shuffle_word=self.get_correct_shuffle_word()self.label1=Label(self.root2, text='Disordered word:  '+shuffle_word,font=('楷体', 14))self.label1.place(x=10, y=80)Label(self.root2, text='Guess the word:', font=('楷体', 14)).place(x=10, y=120)num=tk.StringVar()self.entry=tk.Entry(self.root2,textvariable=num,font=('Arial', 10))self.entry.place(x=180,y=125)def get_final_time(self):long=10   #答题时长hms=time.strftime('%H %M %S').split()allsecond=int(hms[0])*3600+int(hms[1])*60+int(hms[2])+longstrtime=allsecond//3600h=str(allsecond//3600)m=str(allsecond%3600//60)s=str(allsecond%3600%60)if len(h)==1:h='0'+hif len(m)==1:m='0'+mif len(s)==1:s='0'+sself.final_time=h+':'+m+':'+sdef time_over(self,img,text):self.root3=Toplevel()self.root3.title('Welcome to hangman!')self.root3.geometry('+0+0')self.root3.geometry('800x600')self.picture(self.root3,2,img)button=Button(self.root3,text=text,bd=4,bg="orange",activebackground="yellow",command=self.Exit,padx=50)button.pack()def Exit(self):self.root3.destroy()def get_time(self):Time=time.strftime('%Y-%m-%d %H:%M:%S')Label(self.root2, text='当前时间:', bg='gold', font=28).place(x=380, y=50)clock=Label(self.root2,text=Time,font=28)clock.place(x=465, y=50)if Time[11:]==self.final_time:         messagebox.showinfo("超时",'时间到了!正确答案是: '+self.correct_word)self.time_over('0002.gif','别骂了别骂了')clock.after(1000,self.get_time)def Quit(self):messagebox.showinfo('战绩',f'您在这次游戏中共答对{self.win_times}道题,答错{self.lose_times}道题')self.win_times=0self.lose_times=0self.root2.destroy()   def next1(self):self.entry.delete(0,'end')self.button1.destroy()self.label1.destroy()self.label.configure(text="Welcome to the word guessing game!", bg='green')self.mode1()def next2(self):self.entry.delete(0,'end')self.button2.destroy()self.label1.destroy()self.label.configure(text="Welcome to the word guessing game!", bg='green')self.mode2()def get_correct_shuffle_word(self):correct_word=random.choice(words)return correct_word,self.shuffle_word(correct_word)def start(self):self.root1=Tk()self.root1.title('Welcome to hangman!')self.root1.geometry('+0+0')self.root1.geometry('800x600')Label(self.root1,text='我  爱  记 单 词 ', fg='red', bg='yellow',font=('宋体', 30)).pack(side='top')self.picture(self.root1,12,'0001.gif')button1=Button(self.root1,text="进入猜单词游戏",bd=4,bg="orange",activebackground="yellow",command=self.Start,padx=50)button1.pack()self.root1.mainloop()def picture(self,pos,numIdx,img):frames=[PhotoImage(file=img,format='gif -index %i' %(i)) for i in range(numIdx)]def update(idx):frame = frames[idx]idx+=1label.configure(image=frame)pos.after(100, update, idx%numIdx)self.labelframe=LabelFrame(pos,text='图片展示',height=500,width=600)self.labelframe.pack(padx=10,pady=10)self.labelframe.pack_propagate(0)label=Label(self.labelframe)label.pack()pos.after(0,update, 0)def Start(self):messagebox.showinfo("提示","你正在进入猜单词游戏!\n你准备好了吗?")self.root1.destroy()
if __name__=='__main__':guess_word=Guess_word()

更多推荐

https://blog.csdn.net/qq

本文发布于:2024-02-05 09:07:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1674009.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:blog   https   csdn   qq   net

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!