2023年9月26日 星期二

小專案-單字卡

 





點擊 XX表示不熟悉這個單字,   點擊勾勾表示熟悉這個單字

import tkinter as tk
import pandas as pd
import random

try:
    data=pd.read_csv("不熟悉詞彙.csv")
    print(data)
except FileNotFoundError:
   
    data=pd.read_csv('data\\french_words.csv')
    print(data)
    to_learn=data.to_dict(orient='records')#'records的參數是建立一個字典依據[{column:val},{column:val}....]
else:
    print(f'正常執行')
    to_learn=data.to_dict(orient='records')
    #'records的參數是建立一個字典依據[{column:val},{column:val}....]
    print(to_learn)


設定背景綠色

,設定標題間隔


'''常數區'''

BACKGROUND_COLOR='#B1DDC6'

''''''
window=tk.Tk()
window.title('Flash Card')

window.config(padx=50,pady=50,background=BACKGROUND_COLOR)





'''UI設定區'''
canv=tk.Canvas(width=800,height=526,highlightthickness=0,background=BACKGROUND_COLOR)
#設定畫布大小, 關閉光線, 背景顏色設定綠色




img_obj_font=tk.PhotoImage(file='images\\card_front.png')

img_obj_back=tk.PhotoImage(file='images\\card_back.png')
#建立image物件 ,畫布必須讀取圖片物件

can_font=canv.create_image(400,263,image=img_obj_font)
#建立畫布實例,使用font圖片
canv.grid(row=0,column=0,columnspan=2)
#這邊圖片屬性設定colunmspan=2 是因為下面有2個button ,這樣才能橫跨他們

canv_title=canv.create_text(400,150,text='Title',font=("Ariel",40,'italic'))
#設定顯示語言
canv_word=canv.create_text(400,263,text='Word',font=("Ariel",60,'bold'))
#設定顯示的單字
img_obj_wrong=tk.PhotoImage(file='images\\wrong.png')
unknow_button=tk.Button(image=img_obj_wrong,command=next_card)
unknow_button.grid(row=1,column=0)
unknow_button.config(highlightthickness=0) #去除掉周圍邊光線

img_obj_right=tk.PhotoImage(file='images\\right.png')
right_button=tk.Button(image=img_obj_right)
right_button.grid(row=1,column=1)
right_button.config(highlightthickness=0,command=is_know)




next_card() #這樣就可以再一打開程式就直接顯示單字


cur_card='' #使用全域變數,方便另一個函數讀取目前選到的單字

'''按鈕功能區'''
def next_card():
    '典籍之後顯示下一組'
   
    global cur_card, flip_timer
    #使用全域變數, 統一計時,
    window.after_cancel(flip_timer)
    #重置前一個計時器,避免點開後面卡片時 不到3秒直接翻牌, 因為之前的函式仍在執行
   
   
    cur_card=random.choice(to_learn)
    # print(f'cur_card={cur_card["French"]}')
    canv.itemconfig(canv_title,text='French',fill='black')
    canv.itemconfig(canv_word,text=cur_card['French'],fill='black')
    canv.itemconfig(can_font,image=img_obj_font)
    flip_timer=window.after(3000,three_card)
    #再次計時三秒翻牌

   
   
   

def three_card():
    '翻轉卡片'
    canv.itemconfig(can_font,image=img_obj_back)
    canv.itemconfig(canv_title,text='English',fill='white')
    canv.itemconfig(canv_word,text=cur_card['English'],fill='white')
   
flip_timer=window.after(3000,three_card)
#window.after(3千毫秒=3秒,執行這個函式)

def is_know():
    print(f'目前長度={len(to_learn)}')
    print('將已知的單字移除')
    to_learn.remove(cur_card)
    print(f'移除後長度={len(to_learn)}')
    #留存不熟悉的單字資料, 以便下次讀取
    data=pd.DataFrame(to_learn)
    data.to_csv('不熟悉詞彙.csv',index=False)
    #將index=False 避免把DataFrame的索引寫進去
    next_card()






標籤:

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁