Python GUI案例之看图猜成语开发(第一篇)
Python GUI案例之看圖猜成語(yǔ)(第一篇)
- 前言
- 爬取素材篇
- 看圖猜成語(yǔ)小程序開(kāi)發(fā)(第一篇)
- 游戲首頁(yè)
- 游戲首頁(yè)完整代碼
Python GUI案例之看圖猜成語(yǔ)開(kāi)發(fā)(第二篇)
Python GUI案例之看圖猜成語(yǔ)開(kāi)發(fā)(第三篇)
Python GUI案例之看圖猜成語(yǔ)開(kāi)發(fā)(完結(jié)篇)
前言
由于之前寫(xiě)的這篇博文(https://blog.csdn.net/qq_59142194/article/details/123937365?spm=1001.2014.3001.5501)對(duì)ttkbootstrap做了個(gè)簡(jiǎn)單地使用方法介紹,并且也得到了許多小伙伴的收藏。所以這次就用ttkbootstrap來(lái)做一個(gè)簡(jiǎn)單的看圖猜成語(yǔ)小游戲的開(kāi)發(fā)來(lái)對(duì)它有一個(gè)綜合地認(rèn)識(shí)。
好了,首先我們?cè)陂_(kāi)發(fā)前,還需要收集一些看圖猜成語(yǔ)對(duì)應(yīng)的素材,所以我們需要用一個(gè)爬蟲(chóng)程序來(lái)爬一波圖片。這里我直接就在度娘上隨便找了一個(gè)網(wǎng)站進(jìn)行爬取的(看圖猜成語(yǔ)用到的網(wǎng)址:http://www.hydcd.com/cy/fkccy/index.htm)。
準(zhǔn)備好成語(yǔ)圖片素材后,我們將準(zhǔn)備要實(shí)現(xiàn)這些功能:
- 一,游戲首頁(yè)頁(yè)面:在首頁(yè)頁(yè)面里需要實(shí)現(xiàn)繪制一個(gè)看圖猜成語(yǔ)文字的標(biāo)題,定義兩個(gè)按鈕功能(開(kāi)始游戲,退出游戲),還有一個(gè)輸入游戲昵稱(chēng)的功能并且要對(duì)昵稱(chēng)進(jìn)行驗(yàn)證是否為空,才能開(kāi)始游戲;
- 二,游戲選擇模式頁(yè)面:在首頁(yè)點(diǎn)擊開(kāi)始游戲后,進(jìn)入游戲的選擇模式頁(yè)面,分為訓(xùn)練模式和闖關(guān)模式兩種;
- 三,游戲訓(xùn)練模式頁(yè)面:將成語(yǔ)圖片加載后,只實(shí)現(xiàn)猜成語(yǔ)功能(一張圖片,一個(gè)輸入框,一個(gè)按鈕)和回答的準(zhǔn)確率;
- 四,游戲闖關(guān)模式頁(yè)面:將實(shí)現(xiàn)自定義有多少個(gè)關(guān)卡數(shù),16個(gè)漢字提示(12個(gè)隨機(jī)生成的干擾漢字),游戲通關(guān)記錄所用的時(shí)間。
本次實(shí)現(xiàn)這些功能主要用到的庫(kù)有:
- ttkbootstrap
- requests
效果實(shí)現(xiàn)
(注:本文所用到的圖片素材均來(lái)自網(wǎng)上
素材提取:https://download.csdn.net/download/qq_59142194/85827790)
了解完這些后,就讓我們開(kāi)始吧!
爬取素材篇
這里就不詳細(xì)介紹爬取的過(guò)程了,是一個(gè)簡(jiǎn)單的爬蟲(chóng),沒(méi)有反爬!!!但是從這個(gè)網(wǎng)站上爬取下來(lái)的圖片有點(diǎn)小(120 x 120),使其圖片在gui上加載時(shí)很小,不太好看。所以我簡(jiǎn)單地用了PIL對(duì)圖像進(jìn)行放大處理(300 x 300)這樣加載出圖片就會(huì)好看些。好了,直接上代碼。
import requests import re import os import time from PIL import Image from fake_useragent import UserAgent# 爬取成語(yǔ)圖片 def SpiderIdiomPictures():cookies = {'BAIDU_SSP_lcr': 'https://www.baidu.com/link?url=58oz4AEVxDWXanBqrfF95dogUPcAVAktBQT0uBu8o4rGPY4J4Kg_-DsmJdvTHryfy8pdGnnOjDG54qbh82KB7K&wd=&eqid=ecc1cb040001afcc0000000662a84cc7','Hm_lvt_8754302607a1cfb0d1d9cddeb79c593d': '1654580566,1655196891','Hm_lpvt_8754302607a1cfb0d1d9cddeb79c593d': '1655200014',}headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9','Accept-Language': 'zh-CN,zh;q=0.9','Cache-Control': 'no-cache','Connection': 'keep-alive','Pragma': 'no-cache','Referer': 'http://www.hydcd.com/cy/fkccy/index3.htm','Upgrade-Insecure-Requests': '1','User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36',}if not os.path.exists('./看圖猜成語(yǔ)'):os.mkdir('./看圖猜成語(yǔ)')idx = 0for page in range(1,11):print(f'\n\033[31m<<<第{page}頁(yè)爬取中……>>>\033[0m')if page == 1:page = ''url = f'http://www.hydcd.com/cy/fkccy/index{page}.htm'session = requests.session()response = session.get(url=url, cookies=cookies, headers=headers)response.encoding = response.apparent_encoding###解析圖片url(http://www.hydcd.com/cy/fkccy/images/CF91100-50.png)和成語(yǔ)for i in re.findall('<img border="0" src="(.*?)"></p>',response.text):result = i.split('"')if len(result) > 2:img_url = f'http://www.hydcd.com/cy/fkccy/{result[0]}' #圖片urlidiom_name = result[2] #圖片名字(成語(yǔ)名)if len(idiom_name) == 4:headers['User-Agent'] = UserAgent().Chromewith open(f'./看圖猜成語(yǔ)/{idiom_name}.png','wb') as f:f.write(session.get(img_url,headers=headers).content)print(f'{idiom_name}.png 保存成功!!!')time.sleep(0.3)idx += 1print(f'\n抓取完畢!!!\n總共抓取\033[31m{idx}張\033[0m圖片')# 圖片放大 def ImageProcessingBig():print(f'\n\033[31m<<<開(kāi)始將圖片進(jìn)行放大>>>\033[0m')for imgfile in os.listdir('./看圖猜成語(yǔ)/'):if len(imgfile.split('.')) == 2:# 待處理圖片路徑img_path = Image.open('./看圖猜成語(yǔ)/'+imgfile)# resize圖片大小,入口參數(shù)為一個(gè)tuple,新的圖片的大小img_size = img_path.resize((300, 300))# 處理圖片后存儲(chǔ)路徑,以及存儲(chǔ)格式imgname = imgfile.split('.')[0]img_size.save(f'./看圖猜成語(yǔ)/{imgname}.png')print(f'\n\033[31m<<<所有圖片已放大完成!!!>>>\033[0m')if __name__ == '__main__':# 爬取網(wǎng)站上的成語(yǔ)圖片(http://www.hydcd.com/cy/fkccy/index.htm),圖片大小120x120SpiderIdiomPictures()# 把爬取到的所有圖片放大(300x300)ImageProcessingBig()看圖猜成語(yǔ)小程序開(kāi)發(fā)(第一篇)
游戲首頁(yè)
游戲首頁(yè)頁(yè)面:在首頁(yè)頁(yè)面里需要實(shí)現(xiàn)繪制一個(gè)看圖猜成語(yǔ)文字的標(biāo)題,定義兩個(gè)按鈕功能(開(kāi)始游戲,退出游戲),還有一個(gè)輸入游戲昵稱(chēng)的功能并且要對(duì)昵稱(chēng)進(jìn)行驗(yàn)證是否為空,才能開(kāi)始游戲。
效果實(shí)現(xiàn):
導(dǎo)包 import ttkbootstrap as ttk import sys,os,random,threading,time,datetime from ttkbootstrap.constants import * from ttkbootstrap.dialogs import Messagebox,Querybox
首先創(chuàng)建一個(gè)ttkbootstrapWindow類(lèi),主要用來(lái)實(shí)例化創(chuàng)建應(yīng)用程序窗(root)、窗口居中、讓窗口顯示出來(lái),以便后面的類(lèi)來(lái)繼承這個(gè)類(lèi)。 class ttkbootstrapWindow:# 實(shí)例化創(chuàng)建應(yīng)用程序窗口root = ttk.Window(title="看圖猜成語(yǔ)", themename="litera", resizable=(False, False))# 讓窗口居中def window_middle(self,windowwidth,windowheight):screenwidth = self.root.winfo_screenwidth()screenheight = self.root.winfo_screenheight()locx = int((screenwidth - windowwidth) / 2)locy = int((screenheight - windowheight) / 2)self.root.geometry("{}x{}+{}+{}".format(windowwidth, windowheight, locx, locy))# 顯示窗口def window_displaymodule(self):self.root.mainloop()
然后就可以開(kāi)始寫(xiě)首頁(yè)里面的東西了。
class guessIdiomsFromPictures(ttkbootstrapWindow):def __init__(self):super().__init__()self.index()self.window_displaymodule()# 首頁(yè)內(nèi)容def index(self):self.window_middle(windowwidth=960,windowheight=540) #窗口大小寬x高(960 x 540),默認(rèn)居中self.index_frame = ttk.Frame(self.root)self.index_frame.pack(fill=BOTH,expand=YES)self.bg_img = ttk.PhotoImage(file='./sucai/index_bg.png')self.bg_img_Label = ttk.Label(self.index_frame, image=self.bg_img)self.bg_img_Label.pack(fill=BOTH, expand=YES)self.title_lable = ttk.Label(self.bg_img_Label, text=' 看圖猜成語(yǔ)', font=('華文行楷', 56, 'italic'), cursor='watch',background='#E7CBB5', bootstyle=WARNING, width=14)self.title_lable.place(x=190, y=80)self.begin_button_img = ttk.PhotoImage(file='./sucai/beginGame.png')self.begin_button = ttk.Button(self.index_frame, bootstyle=(SUCCESS, "outline-toolbutton"),image=self.begin_button_img, command=self.begin_game)self.begin_button.place(x=270, y=310)self.exit_button_img = ttk.PhotoImage(file='./sucai/exitGame.png')self.exit_button = ttk.Button(self.index_frame, bootstyle=(SUCCESS, "outline-toolbutton"),image=self.exit_button_img, command=self.exit_game)self.exit_button.place(x=480, y=320)ttk.Label(self.bg_img_Label, text='請(qǐng)輸入昵稱(chēng):', cursor='watch', bootstyle=DARK).place(x=250, y=212)self.entry_nickname = ttk.Entry(self.index_frame, show=None, font=('微軟雅黑', 16))self.entry_nickname.insert('0', "暴龍戰(zhàn)士之王")self.entry_nickname.place(x=340, y=200, width=360, height=50)# self.index_move()# 驗(yàn)證昵稱(chēng)是否為空def index_verify(self):self.nickname = self.entry_nickname.get().strip()if self.nickname:return Trueelse:return False# 開(kāi)始游戲def begin_game(self):try:if not self.index_verify():Messagebox.show_info(message="請(qǐng)先輸入您的昵稱(chēng)!")returnprint('開(kāi)始游戲')except: pass# 退出游戲def exit_game(self):sys.exit()但是,如果這樣寫(xiě),這些組件都是靜態(tài)布局的,效果感受也沒(méi)有那么好,所以我們需要再寫(xiě)一個(gè)方法來(lái)使部分組件能過(guò)到達(dá)移動(dòng)的動(dòng)態(tài)效果。
下面這個(gè)方法就可以讓self.title_lable、self.begin_button、self.exit_button
實(shí)現(xiàn)移動(dòng)的效果,把這個(gè)方法加到guessIdiomsFromPictures類(lèi)里面并在里面的index方法最后面調(diào)用就行了。
游戲首頁(yè)完整代碼
import ttkbootstrap as ttk import sys from ttkbootstrap.constants import * from ttkbootstrap.dialogs import Messageboxclass ttkbootstrapWindow:# 實(shí)例化創(chuàng)建應(yīng)用程序窗口root = ttk.Window(title="看圖猜成語(yǔ)", themename="litera", resizable=(False, False))# 讓窗口居中def window_middle(self,windowwidth,windowheight):screenwidth = self.root.winfo_screenwidth()screenheight = self.root.winfo_screenheight()locx = int((screenwidth - windowwidth) / 2)locy = int((screenheight - windowheight) / 2)self.root.geometry("{}x{}+{}+{}".format(windowwidth, windowheight, locx, locy))# 顯示窗口def window_displaymodule(self):self.root.mainloop()# 看圖猜成語(yǔ) class guessIdiomsFromPictures(ttkbootstrapWindow):def __init__(self):super().__init__()self.index()self.window_displaymodule()# 首頁(yè)內(nèi)容def index(self):self.window_middle(windowwidth=960,windowheight=540) #窗口大小寬x高(960 x 540),默認(rèn)居中self.index_frame = ttk.Frame(self.root)self.index_frame.pack(fill=BOTH,expand=YES)self.bg_img = ttk.PhotoImage(file='./sucai/index_bg.png')self.bg_img_Label = ttk.Label(self.index_frame, image=self.bg_img)self.bg_img_Label.pack(fill=BOTH, expand=YES)self.title_lable = ttk.Label(self.bg_img_Label, text=' 看圖猜成語(yǔ)', font=('華文行楷', 56, 'italic'), cursor='watch',background='#E7CBB5', bootstyle=WARNING, width=14)self.begin_button_img = ttk.PhotoImage(file='./sucai/beginGame.png')self.begin_button = ttk.Button(self.index_frame, bootstyle=(SUCCESS, "outline-toolbutton"),image=self.begin_button_img, command=self.begin_game)self.exit_button_img = ttk.PhotoImage(file='./sucai/exitGame.png')self.exit_button = ttk.Button(self.index_frame, bootstyle=(SUCCESS, "outline-toolbutton"),image=self.exit_button_img, command=self.exit_game)self.entry_nickname = ttk.Entry(self.index_frame, show=None, font=('微軟雅黑', 16))self.index_move()# 頁(yè)面組件移動(dòng)def index_move(self):def run(rate):rate += 5button_posy = 540 - rate*1.5self.begin_button.place(x=270,y=button_posy)self.exit_button.place(x=480,y=button_posy+10)if rate < 80:self.title_lable.place(x=190, y=rate)self.title_lable.after(60,run ,rate % 80)elif 80<= rate < 150:self.title_lable.after(60, run, rate % 150)else:ttk.Label(self.bg_img_Label, text='請(qǐng)輸入昵稱(chēng):', cursor='watch', bootstyle=DARK).place(x=250, y=212)self.entry_nickname.insert('0', "暴龍戰(zhàn)士之王")self.entry_nickname.place(x=340, y=200, width=360, height=50)run(0)# 驗(yàn)證昵稱(chēng)是否為空def index_verify(self):self.nickname = self.entry_nickname.get().strip()if self.nickname:return Trueelse:return False# 開(kāi)始游戲def begin_game(self):try:if not self.index_verify():Messagebox.show_info(message="請(qǐng)先輸入您的昵稱(chēng)!")returnprint('開(kāi)始游戲')except: pass# 退出游戲def exit_game(self):sys.exit()if __name__ == '__main__':guessIdiomsFromPictures()今天的內(nèi)容就先寫(xiě)到這里吧,喜歡的小伙伴們記得點(diǎn)贊收藏一下哈!!!
總結(jié)
以上是生活随笔為你收集整理的Python GUI案例之看图猜成语开发(第一篇)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: PHP生成缩略图函数
- 下一篇: python处理网络文字流,设置为utf