Python GUI The case of figure guessing idiom development ( Chapter one )
Python GUI The case of figure guessing idiom development ( Second articles )
Python GUI The case of figure guessing idiom development ( Third articles )
Material extraction :https://download.csdn.net/download/qq_59142194/85827790
Here it will be completely over , Talk about my feelings !
At first, when I wanted to develop this little program to guess idioms by looking at pictures , Or from a Python Pick up a list in the order group ( The requirements are probably like this to develop similar functions ) Speaking of . I think it may be a freshman 、 About two students' homework , But I was also busy preparing for the final exam , Then I just looked at this list for nothing and left me , Uncomfortable !!!( Come back , There are almost also those who join the order group 5 I haven't received a list for months , Of course, I'm too delicious , The list I see is 10 There are 2、3 Something you can do , Ha ha ha ), So the list was a pity for me . Scared , Forget about that !!!
For the small program I wrote this time , It took almost two days ! It's not too difficult to write this function , Just put ttkbootstrap After understanding the usage of the components used inside , That is, there is a little difficulty in realizing the logic of these functions ! After thinking for a while, you can sort out the logic .
Then there are some comments on the style of the code I wrote , I think there is really a big problem . I didn't understand the use of classes clearly in the process of writing code , Variable 、 The names of these methods are all written by me , Ha ha ha ! I'm just thinking about how to realize these functions and the logical relationship between them , But there is no specification that pays attention to code style , So please be merciful if you have read this blog code . Continue to learn the process of tapping code later, and gradually pay attention to the rigor of development , The standardization of writing code and better simplification of code , Reduce redundant , Form the wind of code elegance . Ha ha ha !!!
But then again , The implementation of logic and function between my codes is also quite possible , At least I've tested it a dozen times without any problem . This is also good , Not all say , If only one person and code can run , Ha ha ha ( Manual dog head for life ).
Okay , Writing co., LTD. , I can't play anymore , That's it !
by the way , If you need the source code and the image material you use, you can't download it in the above link , I can also take private messages !!!
” The breeze blew the Wutong trees outside the window , The sun shines through the window , It seems to follow the dream in my heart . And the dream is the persistence of picking up the pen in the morning , It's not hesitating to open the quilt and waking up with cold water , It's the amazing sight of the rising sun and the blooming light of the notes at six .“ In the future, let's hammer out our dreams with both hands !
come on. ! come on. ! come on. !
import ttkbootstrap as ttk
import sys,os,random,threading,time,datetime
from ttkbootstrap.constants import *
from ttkbootstrap.dialogs import Messagebox,Querybox
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.index_frame,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.entry_nickname = ttk.Entry(self.index_frame, show=None, font=(' Microsoft YaHei ', 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()
# 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
self.index_frame.destroy()
game_modeSelection_page(self.nickname)
except:
pass
# Quit the game
def exit_game(self):
sys.exit()
# Game mode selection page
class game_modeSelection_page(ttkbootstrapWindow):
def __init__(self,nickname):
super().__init__()
self.nickname = nickname
self.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=' Training mode ', font=(' Chinese Xingkai ', 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=' Break through mode ', font=(' Chinese Xingkai ', 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):
# Default 10 A level (initialvalue=10)
number = Querybox.get_integer(prompt=" Please set the number of levels :",title=" Customize the number of levels ",initialvalue=10,minvalue=0,maxvalue=50)
if number:
self.frame.destroy()
game_chuangguan_page(self.nickname,number)
# There are components written in the same way in both modes of the game
class game_same_components(ttkbootstrapWindow):
def __init__(self):
super().__init__()
def same_page(self,nickname):
self.nickname = nickname
self.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' welcome :【{
self.nickname}】 Players go online ', font=20, bootstyle=INFO,background='#F4F4F4')
nickname_lable.place(x=960, y=4)
def nickname_lable_move(rate):
rate += 5
nickname_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)
# Game training mode page
class game_train_page(game_same_components):
def __init__(self,nickname):
super().__init__()
self.nickname = nickname
self.game_page()
loading_img_times = 0 # Record the times of loading pictures
answer_times = 0 # Record the total number of responses
answer_correct_times = 0 # Record the number of correct answers
# The game page
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=(' Microsoft YaHei ', 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=' see ', bootstyle=(PRIMARY, "outline-toolbutton"),command=self.see_answer)
see_idiom_button.place(x=480, y=470)
self.accuracy_lable1 = ttk.Label(self.canvas,text=' Accuracy rate :',font=(' Chinese Xingkai ', 20),background='#D3E0E8')
self.accuracy_lable1.place(x=600, y=120)
self.accuracy_lable2 = ttk.Label(self.canvas, text="0.0%", font=(' Chinese Xingkai ', 20),bootstyle=DANGER,background='#D3E0E8')
self.accuracy_lable2.place(x=750, y=120)
self.loading_idiom_img()
# Load idiom pictures
def loading_idiom_img(self):
self.loading_img_times += 1
self.idiom = random.choice(os.listdir('./ Look at the picture and guess the idiom '))
self.idiom_result = self.idiom.split('.')[0]
print(' answer :',self.idiom_result)
self.idiom_img = ttk.PhotoImage(file=f'./ Look at the picture and guess the idiom /{
self.idiom}')
lm = ttk.Label(self.canvas,image=self.idiom_img)
lm.place(x=215,y=115)
guanqia_lable = ttk.Label(self.canvas, font=(' Chinese Xingkai ', 32),background='#48A6B0')
guanqia_lable.place(x=300,y=450)
guanqia_lable.config(text=f' The first {
self.loading_img_times} Turn off ')
# Check the answers
def see_answer(self):
Messagebox.show_info(message=self.idiom_result)
def answer(self):
if self.answer_idiom_entry.get().strip():
self.answer_times += 1
if self.answer_idiom_entry.get().strip() == self.idiom_result:
Messagebox.show_info(message=" Congratulations , Correct answer !!!")
self.loading_idiom_img()
self.answer_idiom_entry.delete(0,'end')
self.answer_correct_times += 1
else:
if not Messagebox.yesno(message=" Wrong answer !!!\n Continue to answer ?") == '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}%')
# Game entry mode page
class game_chuangguan_page(game_same_components):
CLICKTIMES = 0 # Number of hits
TRUEANSWER = '' # answer
IDX = 1 # Which level , Default No 1 Turn off
def __init__(self, nickname,number):
super().__init__()
self.nickname = nickname
self.idiom_list = random.sample(os.listdir('./ Look at the picture and guess the idiom '), number) # Random initialization selection 20 A picture , Used for setting up 20 A level
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=' The first ? / ? Turn off ', font=(' Chinese Xingkai ', 32), background='#48A6B0') # Show the number of levels
self.guanqia_lable.place(x=200, y=40)
self.lm = ttk.Label(self.canvas) # Used to configure pictures
self.lm.place(x=165, y=115)
self.result_label = ttk.Label(self.canvas,text='', font=(' Chinese Xingkai ', 32), background='#A1F8EE', bootstyle=DANGER) # Used to display the result of the answer
self.result_label.place(x=40,y=135,height=300)
ttk.Button(self.canvas,text=' Reselection ', bootstyle=(SUCCESS, "outline-toolbutton"),command=self.update_label).place(x=550,y=470,width=90,height=60) # Reselection button
self.create_selection_result_label()
self.create_option_text_label()
self.loading_idiom_img()
self.recording_time()
# Create four labels for selecting results
def create_selection_result_label(self):
self.answer_list = []
for i in range(4):
label = ttk.Label(self.canvas, text='', font=(" Microsoft YaHei ", 35), background='', width=2, cursor='hand2')
label.place(x=130 + i * 100, y=450)
self.answer_list.append(label)
# Create content tags for selection
def create_option_text_label(self):
def click_label(event):
if self.CLICKTIMES < 4:
self.CLICKTIMES += 1
label_text = event.widget["text"] # Get the text on the label
self.answer(label_text)
self.label_oop_list = []
# Set up 4 That's ok 4 The label of the column
for i in range(4):
for j in range(4):
label = ttk.Label(self.canvas, text='', font=(" Microsoft YaHei ", 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)
# Load idiom pictures
def loading_idiom_img(self,):
self.idiom = self.idiom_list[self.IDX - 1].split('.')[0]
print(' answer :', self.idiom)
disturb_text_list = [self.GBK2312() for i in range(12)] # Random generation 12 Disturbing Chinese characters
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' The first {
self.IDX} / {
len(self.idiom_list)} Turn off ')
self.idiom_img = ttk.PhotoImage(file=f'./ Look at the picture and guess the idiom /{
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_text
if len(self.TRUEANSWER) == 4:
if self.TRUEANSWER == self.idiom:
t = threading.Thread(target=self.dispaly_answer_result,args=(' return \n answer \n just \n indeed ',))
t.setDaemon(True)
t.start()
self.IDX += 1
if self.IDX > len(self.idiom_list):
Messagebox.show_info(message=f" Congratulations on your passing !!!\n Time consuming to :{
self.time_}")
self.flag = False
self.return_game_modeSelection_page()
return
self.update_label()
self.loading_idiom_img()
else:
t = threading.Thread(target=self.dispaly_answer_result, args=(' return \n answer \n wrong \n By mistake ',))
t.setDaemon(True)
t.start()
# Show whether the answer is correct
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)
# Reselection
def update_label(self):
self.CLICKTIMES = 0
self.TRUEANSWER = ''
for i in self.answer_list:i.destroy()
self.create_selection_result_label()
# Randomly generate a Chinese character
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
# Record the time taken for customs clearance
def recording_time(self):
self.flag = True # Define a semaphore , Used when we finish the game and pass ,run() End of cycle
time_label = ttk.Label(self.canvas,text=' Duration :00:00:00', font=(" Chinese Xingkai ", 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_time
self.time_ =f' Duration :{
update_time}'.split('.')[0]
time_label.configure(text=self.time_) # The millisecond value of the duration is not displayed
run()
if __name__ == '__main__':
guessIdiomsFromPictures()