14

利用爬虫技术获取英语单词,并通过tkinter库实现猜单词游戏

 3 years ago
source link: https://blog.csdn.net/qq_46632290/article/details/112019066
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

利用爬虫技术获取英语单词,并通过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=0
        self.lose_times=0
        self.final_time=' '
        self.gui()  
    def get_words(self):
        def Get_Shanbay(page):
            url="https://www.shanbay.com/wordlist/104899/202159/?page=%s"%page
            rsp=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+=1
                self.label.configure(text="Congratulations! You're right! ",bg='red')
            else:
                self.lose_times+=1
                self.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+=1
                messagebox.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+=1
                messagebox.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])+long
        strtime=allsecond//3600
        h=str(allsecond//3600)
        m=str(allsecond%3600//60)
        s=str(allsecond%3600%60)
        if len(h)==1:
            h='0'+h
        if len(m)==1:
            m='0'+m
        if len(s)==1:
            s='0'+s
        self.final_time=h+':'+m+':'+s
    def 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=0
        self.lose_times=0
        self.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+=1
            label.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()
        
代码中还有很多不尽人意的地方,由于作者技术水平的限制,暂时没有实现各种已有的设计理念,比如,利用多线程设计一个PK模式,图形界面的软件应用优化等等,感兴趣的哥哥姐姐们不妨试试。我在评论区静候你们的佳音。

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK