程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python GUI case: figure guessing idiom development (Part 1)

編輯:Python

Python GUI Case of guessing idioms by looking at pictures ( Chapter one )

  • Preface
  • Crawl material
  • Look at the picture and guess idioms. Applet development ( Chapter one )
    • Game home page
    • Game home page complete code

Python GUI The case of figure guessing idiom development ( Second articles )
Python GUI The case of figure guessing idiom development ( Third articles )
Python GUI The case of figure guessing idiom development ( Conclusion )


Preface

Because of this article written before post (https://blog.csdn.net/qq_59142194/article/details/123937365?spm=1001.2014.3001.5501) Yes ttkbootstrap Made a simple introduction to how to use , And it has also been collected by many friends . So I'll use it this time ttkbootstrap To do a simple figure guessing idiom game development to have a comprehensive understanding of it .
Okay , First of all, before development , You also need to collect some materials to guess the corresponding idioms by looking at the pictures , So we need to use a Crawler program to climb a wave of pictures . Here I directly found a website on Du Niang to crawl ( Look at the picture and guess the website used in the idiom :http://www.hydcd.com/cy/fkccy/index.htm).

After preparing idiom picture materials , We are going to implement these functions :

  • One , Game home page : In the home page, you need to draw a title to guess idioms by looking at pictures , Define two button functions ( Start the game , Quit the game ), There is also a function to input the game nickname and verify whether the nickname is empty , To start the game ;
  • Two , Game selection mode page : Click start game on the home page , Enter the selection mode page of the game , It is divided into two modes: training mode and breakthrough mode ;
  • 3、 ... and , Game training mode page : Load the idiom picture , Only guess idioms ( A picture , An input box , A button ) And the accuracy of the answer ;
  • Four , Game entry mode page : How many levels will be customized ,16 Chinese character prompt (12 Randomly generated interfering Chinese characters ), The time taken for game clearance records .

The main libraries used to realize these functions this time are :

  • ttkbootstrap
  • requests

Effect of implementation


( notes : The picture materials used in this article are all from the Internet
Material extraction :https://download.csdn.net/download/qq_59142194/85827790)

After knowing this , Let's get started !


Crawl material

I won't introduce the crawling process in detail here , Is a simple reptile , There is no anti climbing !!! But the pictures taken from this website are a little small (120 x 120), Make its picture in gui Loading on is very small , Not very good. . So I simply used PIL Enlarge the image (300 x 300) In this way, the loaded image will look better . Okay , Go straight to the code .

import requests
import re
import os
import time
from PIL import Image
from fake_useragent import UserAgent
# Crawl idiom pictures 
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('./ Look at the picture and guess the idiom '):
os.mkdir('./ Look at the picture and guess the idiom ')
idx = 0
for page in range(1,11):
print(f'\n\033[31m<<< The first {
page} Page crawling ……>>>\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
### Resolution images url(http://www.hydcd.com/cy/fkccy/images/CF91100-50.png) And idioms 
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]}' # picture url
idiom_name = result[2] # Picture name ( Idiom name )
if len(idiom_name) == 4:
headers['User-Agent'] = UserAgent().Chrome
with open(f'./ Look at the picture and guess the idiom /{
idiom_name}.png','wb') as f:
f.write(session.get(img_url,headers=headers).content)
print(f'{
idiom_name}.png Saved successfully !!!')
time.sleep(0.3)
idx += 1
print(f'\n After grabbing !!!\n Total grabs \033[31m{
idx} Zhang \033[0m picture ')
# Picture enlargement 
def ImageProcessingBig():
print(f'\n\033[31m<<< Start to enlarge the picture >>>\033[0m')
for imgfile in os.listdir('./ Look at the picture and guess the idiom /'):
if len(imgfile.split('.')) == 2:
# Image path to be processed 
img_path = Image.open('./ Look at the picture and guess the idiom /'+imgfile)
# resize Picture size , The entry parameter is a tuple, The size of the new picture 
img_size = img_path.resize((300, 300))
# Storage path after processing pictures , And storage format 
imgname = imgfile.split('.')[0]
img_size.save(f'./ Look at the picture and guess the idiom /{
imgname}.png')
print(f'\n\033[31m<<< All pictures have been enlarged !!!>>>\033[0m')
if __name__ == '__main__':
# Crawl the idiom pictures on the website (http://www.hydcd.com/cy/fkccy/index.htm), Picture size 120x120
SpiderIdiomPictures()
# Enlarge all the pictures you crawl (300x300)
ImageProcessingBig()

Look at the picture and guess idioms. Applet development ( Chapter one )


Game home page

Game home page : In the home page, you need to draw a title to guess idioms by looking at pictures , Define two button functions ( Start the game , Quit the game ), There is also a function to input the game nickname and verify whether the nickname is empty , To start the game .
Effect of implementation :


Guide pack
import ttkbootstrap as ttk
import sys,os,random,threading,time,datetime
from ttkbootstrap.constants import *
from ttkbootstrap.dialogs import Messagebox,Querybox

First create a ttkbootstrapWindow class , It is mainly used to instantiate and create application windows (root)、 Center window 、 Let the window show , So that later classes can inherit this class .
class ttkbootstrapWindow:
# Instantiate to create an application window 
root = ttk.Window(title=" Look at the picture and guess the idiom ", themename="litera", resizable=(False, False))
# Center the window 
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))
# Display window 
def window_displaymodule(self):
self.root.mainloop()

Then you can start writing things on the home page .

class guessIdiomsFromPictures(ttkbootstrapWindow):
def __init__(self):
super().__init__()
self.index()
self.window_displaymodule()
# Home page content 
def index(self):
self.window_middle(windowwidth=960,windowheight=540) # The window size is wide x high (960 x 540), Default Center 
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=' Look at the picture and guess the idiom ', font=(' Chinese Xingkai ', 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=' Please enter your nickname :', cursor='watch', bootstyle=DARK).place(x=250, y=212)
self.entry_nickname = ttk.Entry(self.index_frame, show=None, font=(' Microsoft YaHei ', 16))
self.entry_nickname.insert('0', " King of Tyrannosaurus Rex warriors ")
self.entry_nickname.place(x=340, y=200, width=360, height=50)
# self.index_move()
# Verify that the nickname is empty 
def index_verify(self):
self.nickname = self.entry_nickname.get().strip()
if self.nickname:
return True
else:
return False
# Start the game 
def begin_game(self):
try:
if not self.index_verify():
Messagebox.show_info(message=" Please enter your nickname first !")
return
print(' Start the game ')
except: pass
# Quit the game 
def exit_game(self):
sys.exit()

however , If you write like this , These components are statically laid out , The effect is not so good , So we need to write another method to make some components reach the dynamic effect of mobile .


The following method can make self.title_lable、self.begin_button、self.exit_button
Achieve the effect of mobile , Add this method to guessIdiomsFromPictures Class and in it index Just call the last method .

# Page components move 
def index_move(self):
def run(rate):
rate += 5
button_posy = 540 - rate*1.5
self.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=' Please enter your nickname :', cursor='watch', bootstyle=DARK).place(x=250, y=212)
self.entry_nickname.insert('0', " King of Tyrannosaurus Rex warriors ")
self.entry_nickname.place(x=340, y=200, width=360, height=50)
run(0)

Game home page complete code

import ttkbootstrap as ttk
import sys
from ttkbootstrap.constants import *
from ttkbootstrap.dialogs import Messagebox
class ttkbootstrapWindow:
# Instantiate to create an application window 
root = ttk.Window(title=" Look at the picture and guess the idiom ", themename="litera", resizable=(False, False))
# Center the window 
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))
# Display window 
def window_displaymodule(self):
self.root.mainloop()
# Look at the picture and guess the idiom 
class guessIdiomsFromPictures(ttkbootstrapWindow):
def __init__(self):
super().__init__()
self.index()
self.window_displaymodule()
# Home page content 
def index(self):
self.window_middle(windowwidth=960,windowheight=540) # The window size is wide x high (960 x 540), Default Center 
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=' Look at the picture and guess the idiom ', font=(' Chinese Xingkai ', 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=(' Microsoft YaHei ', 16))
self.index_move()
# Page components move 
def index_move(self):
def run(rate):
rate += 5
button_posy = 540 - rate*1.5
self.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=' Please enter your nickname :', cursor='watch', bootstyle=DARK).place(x=250, y=212)
self.entry_nickname.insert('0', " King of Tyrannosaurus Rex warriors ")
self.entry_nickname.place(x=340, y=200, width=360, height=50)
run(0)
# Verify that the nickname is empty 
def index_verify(self):
self.nickname = self.entry_nickname.get().strip()
if self.nickname:
return True
else:
return False
# Start the game 
def begin_game(self):
try:
if not self.index_verify():
Messagebox.show_info(message=" Please enter your nickname first !")
return
print(' Start the game ')
except: pass
# Quit the game 
def exit_game(self):
sys.exit()
if __name__ == '__main__':
guessIdiomsFromPictures()

Today's content will be written here first , Remember to like your friends and collect them !!!


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved