Python GUI案例之看图猜成语开发(完结篇)
Python GUI案例之看圖猜成語(yǔ)(完結(jié)篇)
- 看圖猜成語(yǔ)小程序開發(fā)(完結(jié)篇)
- 總結(jié)
- 完整代碼
Python GUI案例之看圖猜成語(yǔ)開發(fā)(第一篇)
Python GUI案例之看圖猜成語(yǔ)開發(fā)(第二篇)
Python GUI案例之看圖猜成語(yǔ)開發(fā)(第三篇)
看圖猜成語(yǔ)小程序開發(fā)(完結(jié)篇)
素材提取:https://download.csdn.net/download/qq_59142194/85827790
總結(jié)
到了這里也就完全地結(jié)束了,淺談一下我的感受吧!
最開始我想開發(fā)這個(gè)看圖猜成語(yǔ)的小程序時(shí),還是從一個(gè)Python接單群里面看到的一個(gè)單子(需求大概就像是這樣開發(fā)與這個(gè)差不多的功能吧)說起。我想可能是一個(gè)大一、二左右學(xué)生的一項(xiàng)作業(yè)吧,但是當(dāng)時(shí)我也忙著準(zhǔn)備期末考試,然后我就這樣白白地看著這個(gè)單子離我而去,難受!!!(話說回來(lái),進(jìn)那些接單群差不多也有5個(gè)月了還是沒有接到過一個(gè)單子,當(dāng)然是我太菜了,我看到的單子中也就10個(gè)單子中有2、3個(gè)能做的吧,哈哈哈),所以那次的單子對(duì)我來(lái)說還是比較可惜的。駭,不說這個(gè)了!!!
對(duì)于這次我寫的這個(gè)小程序來(lái)說,還是花了差不多有兩天的時(shí)間吧!在寫這個(gè)功能來(lái)說也沒什么太大的困難,只要把ttkbootstrap里面用到的組件這些用法了解清楚后,也就是在實(shí)現(xiàn)這些功能的邏輯上有一點(diǎn)的困難吧!多想會(huì)兒也就能理清邏輯了。
然后就是對(duì)我寫的代碼風(fēng)格的一些評(píng)價(jià)吧,我自己覺得是真的存在很大問題的。在寫代碼的過程中關(guān)于類的使用沒有理解清楚,變量、方法這些的命名都是我平感覺寫的,哈哈哈! 我只是在想怎么怎么實(shí)現(xiàn)這些功能以及功能之間的邏輯關(guān)系,但是沒有注重代碼風(fēng)格的規(guī)范,所以有看這篇博文代碼的朋友還請(qǐng)手下留情。在后面繼續(xù)學(xué)習(xí)敲代碼的過程會(huì)逐漸地注重開發(fā)的嚴(yán)謹(jǐn)性,寫代碼的規(guī)范性以及還要更好地簡(jiǎn)化代碼,減少冗余,形成代碼優(yōu)美之風(fēng)。哈哈哈!!!
但是話也說回來(lái),我的代碼之間的邏輯與功能的實(shí)現(xiàn)也是挺可以的,至少我測(cè)試了十幾次也都沒有問題。這點(diǎn)也是不錯(cuò)的吧,不是都說,人和代碼只要有一個(gè)能跑就行了嗎,哈哈哈(手動(dòng)狗頭保命)。
好了,文筆有限,發(fā)揮不下去了,就這樣了吧!
對(duì)了,如果有需要源碼及所用到的圖片素材在上面那個(gè)鏈接里不能下載的話,也可以私信我拿取!!!
”微風(fēng)吹動(dòng)了窗外的梧桐樹,陽(yáng)光從玻璃窗里投過來(lái),好像照著我心上的夢(mèng)想。而夢(mèng)想是凌晨拿起筆的堅(jiān)持,是掀開被子的毫不猶豫和冷水撲面的清醒,是六點(diǎn)看到旭日東升的驚艷和筆記綻放的光。“在未來(lái)的時(shí)間里讓我們一起來(lái)用雙手敲出夢(mèng)想吧!
加油!加油!加油!
完整代碼
import ttkbootstrap as ttk import sys,os,random,threading,time,datetime from ttkbootstrap.constants import * from ttkbootstrap.dialogs import Messagebox,Queryboxclass 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.index_frame,text=' 看圖猜成語(yǔ)', font=('華文行楷',56,'italic'),cursor='watch', background='#E7CBB5', bootstyle=WARNING,width=14)self.begin_button_img = ttk.PhotoImage(file='./sucai/beginGame.png')self.entry_nickname = ttk.Entry(self.index_frame, show=None, font=('微軟雅黑', 16))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.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)輸入昵稱:', 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)證昵稱是否為空def index_verify(self):self.nickname = self.entry_nickname.get().strip()if self.nickname:return Trueelse:return False# 開始游戲def begin_game(self):try:if not self.index_verify():Messagebox.show_info(message="請(qǐng)先輸入您的昵稱!")returnself.index_frame.destroy()game_modeSelection_page(self.nickname)except:pass# 退出游戲def exit_game(self):sys.exit()#游戲模式選擇頁(yè)面 class game_modeSelection_page(ttkbootstrapWindow):def __init__(self,nickname):super().__init__()self.nickname = nicknameself.page()def page(self):self.window_middle(500,300)self.frame = ttk.Frame(self.root)self.frame.pack(fill=BOTH, expand=YES)self.bg = ttk.PhotoImage(file='./sucai/bg2.png')ttk.Label(self.frame,anchor='nw', image=self.bg).pack()l1 = ttk.Label(self.frame,text='訓(xùn)練模式', font=('華文行楷', 32),relief=RAISED,cursor='hand2',bootstyle=WARNING,background='#324762')l1.place(x=150,y=60)l1.bind("<Button-1>",self.game_train_mode)l2 = ttk.Label(self.frame, text='闖關(guān)模式', font=('華文行楷', 32),relief=RAISED,cursor='hand2',bootstyle=SUCCESS,background='#324762')l2.place(x=150, y=140)l2.bind("<Button-1>", self.game_chuangguan_mode)def game_train_mode(self,event):self.frame.destroy()game_train_page(self.nickname)def game_chuangguan_mode(self,event):# 默認(rèn)10個(gè)關(guān)卡(initialvalue=10)number = Querybox.get_integer(prompt="請(qǐng)?jiān)O(shè)置關(guān)卡數(shù)量:",title="自定義關(guān)卡數(shù)量 ",initialvalue=10,minvalue=0,maxvalue=50)if number:self.frame.destroy()game_chuangguan_page(self.nickname,number)#在游戲兩種模式中有相同寫法的組件 class game_same_components(ttkbootstrapWindow):def __init__(self):super().__init__()def same_page(self,nickname):self.nickname = nicknameself.window_middle(960, 540)self.canvas = ttk.Canvas(self.root)self.canvas.pack(fill=BOTH, expand=YES)self.bg = ttk.PhotoImage(file='./sucai/bg3.png')self.canvas.create_image(0, 35, anchor='nw', image=self.bg)self.canvas.create_rectangle(0, 0, 960, 35, fill='#F4F4F4', outline='#F4F4F4')nickname_lable = ttk.Label(self.canvas, text=f'歡迎:【{self.nickname}】玩家上線', font=20, bootstyle=INFO,background='#F4F4F4')nickname_lable.place(x=960, y=4)def nickname_lable_move(rate):rate += 5nickname_lable.place(x=960 - rate, y=4)if rate < 960:nickname_lable.after(50, nickname_lable_move, rate % 960)nickname_lable_move(0)self.return_button_img = ttk.PhotoImage(file='./sucai/return.png')self.return_button = ttk.Button(self.canvas, bootstyle=(LIGHT, "outline-toolbutton"), image=self.return_button_img,command=self.return_game_modeSelection_page)self.return_button.place(x=0, y=35)def return_game_modeSelection_page(self):self.canvas.destroy()game_modeSelection_page(self.nickname)#游戲訓(xùn)練模式頁(yè)面 class game_train_page(game_same_components):def __init__(self,nickname):super().__init__()self.nickname = nicknameself.game_page()loading_img_times = 0 # 記錄加載圖片次數(shù)answer_times = 0 # 記錄回答總次數(shù)answer_correct_times = 0 # 記錄回答正確次數(shù)#游戲頁(yè)面def game_page(self):self.same_page(self.nickname)self.canvas.create_rectangle(200, 100, 535, 435)self.answer_idiom_entry = ttk.Entry(self.canvas, show=None, font=('微軟雅黑', 32),bootstyle=DANGER)self.answer_idiom_entry.place(x=580,y=190,height=100,width=300)self.answer_idiom_entry.bind("<Return>", lambda event: self.answer())self.answer_idiom_button_img = ttk.PhotoImage(file='./sucai/ensure.png')answer_idiom_button = ttk.Button(self.canvas, bootstyle=(LIGHT, "outline-toolbutton"),image=self.answer_idiom_button_img,command=self.answer)answer_idiom_button.place(x=635,y=310)see_idiom_button = ttk.Button(self.canvas,text='查看', bootstyle=(PRIMARY, "outline-toolbutton"),command=self.see_answer)see_idiom_button.place(x=480, y=470)self.accuracy_lable1 = ttk.Label(self.canvas,text='正確率:',font=('華文行楷', 20),background='#D3E0E8')self.accuracy_lable1.place(x=600, y=120)self.accuracy_lable2 = ttk.Label(self.canvas, text="0.0%", font=('華文行楷', 20),bootstyle=DANGER,background='#D3E0E8')self.accuracy_lable2.place(x=750, y=120)self.loading_idiom_img()#加載成語(yǔ)圖片def loading_idiom_img(self):self.loading_img_times += 1self.idiom = random.choice(os.listdir('./看圖猜成語(yǔ)'))self.idiom_result = self.idiom.split('.')[0]print('答案:',self.idiom_result)self.idiom_img = ttk.PhotoImage(file=f'./看圖猜成語(yǔ)/{self.idiom}')lm = ttk.Label(self.canvas,image=self.idiom_img)lm.place(x=215,y=115)guanqia_lable = ttk.Label(self.canvas, font=('華文行楷', 32),background='#48A6B0')guanqia_lable.place(x=300,y=450)guanqia_lable.config(text=f'第 {self.loading_img_times} 關(guān)')#查看答案def see_answer(self):Messagebox.show_info(message=self.idiom_result)def answer(self):if self.answer_idiom_entry.get().strip():self.answer_times += 1if self.answer_idiom_entry.get().strip() == self.idiom_result:Messagebox.show_info(message="恭喜,回答正確!!!")self.loading_idiom_img()self.answer_idiom_entry.delete(0,'end')self.answer_correct_times += 1else:if not Messagebox.yesno(message="回答錯(cuò)誤!!!\n是否繼續(xù)回答?") == 'Yes':self.loading_idiom_img()self.answer_idiom_entry.delete(0, 'end')self.accuracy_lable2.config(text=f'{round(self.answer_correct_times / self.answer_times, 2) * 100}%')#游戲闖關(guān)模式頁(yè)面 class game_chuangguan_page(game_same_components):CLICKTIMES = 0 #點(diǎn)擊次數(shù)TRUEANSWER = '' #答案IDX = 1 #第幾關(guān),默認(rèn)第1關(guān)def __init__(self, nickname,number):super().__init__()self.nickname = nicknameself.idiom_list = random.sample(os.listdir('./看圖猜成語(yǔ)'), number) #隨機(jī)初始化選取20張圖片,用于設(shè)置20個(gè)關(guān)卡self.game_page()def game_page(self):self.same_page(self.nickname)self.canvas.create_rectangle(150, 100, 485, 435)self.guanqia_lable = ttk.Label(self.canvas,text='第? / ?關(guān)', font=('華文行楷', 32), background='#48A6B0') #顯示關(guān)卡數(shù)self.guanqia_lable.place(x=200, y=40)self.lm = ttk.Label(self.canvas) #用于配置圖片self.lm.place(x=165, y=115)self.result_label = ttk.Label(self.canvas,text='', font=('華文行楷', 32), background='#A1F8EE', bootstyle=DANGER) # 用于顯示答案的結(jié)果self.result_label.place(x=40,y=135,height=300)ttk.Button(self.canvas,text='重選', bootstyle=(SUCCESS, "outline-toolbutton"),command=self.update_label).place(x=550,y=470,width=90,height=60) # 重選按鈕self.create_selection_result_label()self.create_option_text_label()self.loading_idiom_img()self.recording_time()# 創(chuàng)建四個(gè)用于選擇結(jié)果的標(biāo)簽def create_selection_result_label(self):self.answer_list = []for i in range(4):label = ttk.Label(self.canvas, text='', font=("微軟雅黑", 35), background='', width=2, cursor='hand2')label.place(x=130 + i * 100, y=450)self.answer_list.append(label)# 創(chuàng)建用于選擇的內(nèi)容標(biāo)簽def create_option_text_label(self):def click_label(event):if self.CLICKTIMES < 4:self.CLICKTIMES += 1label_text = event.widget["text"] # 得到標(biāo)簽上的文本self.answer(label_text)self.label_oop_list = []# 設(shè)置4行4列的標(biāo)簽for i in range(4):for j in range(4):label = ttk.Label(self.canvas, text='', font=("微軟雅黑", 35), background='#FFFAE3', width=2,cursor='hand2')label.place(x=510 + j * 100, y=90 + i * 95)label.bind("<Button-1>", click_label)self.label_oop_list.append(label)# 加載成語(yǔ)圖片def loading_idiom_img(self,):self.idiom = self.idiom_list[self.IDX - 1].split('.')[0]print('答案:', self.idiom)disturb_text_list = [self.GBK2312() for i in range(12)] # 隨機(jī)生成12個(gè)干擾漢字disturb_text_list.extend([i for i in self.idiom])for label_oop in self.label_oop_list:text = random.choice(disturb_text_list)disturb_text_list.remove(text)label_oop.configure(text=text)self.guanqia_lable.config(text=f'第 {self.IDX} / {len(self.idiom_list)}關(guān)')self.idiom_img = ttk.PhotoImage(file=f'./看圖猜成語(yǔ)/{self.idiom}.png')self.lm.configure(image=self.idiom_img)def answer(self,label_text):self.answer_list[self.CLICKTIMES - 1].configure(text=label_text)self.TRUEANSWER += label_textif len(self.TRUEANSWER) == 4:if self.TRUEANSWER == self.idiom:t = threading.Thread(target=self.dispaly_answer_result,args=('回\n答\n正\n確',))t.setDaemon(True)t.start()self.IDX += 1if self.IDX > len(self.idiom_list):Messagebox.show_info(message=f"恭喜您已通過!!!\n耗時(shí)為:{self.time_}")self.flag = Falseself.return_game_modeSelection_page()returnself.update_label()self.loading_idiom_img()else:t = threading.Thread(target=self.dispaly_answer_result, args=('回\n答\n錯(cuò)\n誤',))t.setDaemon(True)t.start()# 顯示回答結(jié)果是否正確def dispaly_answer_result(self,text):self.result_label.configure(text=text)time.sleep(3)try: self.result_label.configure(text='')except Exception as e: print(e)# 重選def update_label(self):self.CLICKTIMES = 0self.TRUEANSWER = ''for i in self.answer_list:i.destroy()self.create_selection_result_label()# 隨機(jī)生成一個(gè)漢字def GBK2312(self, ):head = random.randint(0xb0, 0xf7)body = random.randint(0xa1, 0xfe)val = f'{head:x}{body:x}'str = bytes.fromhex(val).decode('gb2312')return str# 記錄通關(guān)所耗時(shí)def recording_time(self):self.flag = True # 定義一個(gè)信號(hào)量,用于當(dāng)我們完成游戲通過時(shí),run()結(jié)束循環(huán)time_label = ttk.Label(self.canvas,text='時(shí)長(zhǎng):00:00:00', font=("華文行楷", 15), background='#DAEFE6',bootstyle=DANGER)time_label.place(x=730,y=50)start_time = datetime.datetime.now()def run():if self.flag:time_label.after(1000, run)update_time = datetime.datetime.now() - start_timeself.time_ =f'時(shí)長(zhǎng):{update_time}'.split('.')[0]time_label.configure(text=self.time_) # 不顯示時(shí)長(zhǎng)的毫秒值run()if __name__ == '__main__':guessIdiomsFromPictures()總結(jié)
以上是生活随笔為你收集整理的Python GUI案例之看图猜成语开发(完结篇)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: TOAD常用快捷键
- 下一篇: python语言程序设计课后答案王恺_超