天天看點

基于tkinter的第一個GUI小項目:背英語六級單詞軟體任務1.引入庫2.讀入資料3.打開視窗4.初始化5.放置标簽和按鈕6.按鈕事件7.示範

文章目錄

  • 任務
  • 1.引入庫
  • 2.讀入資料
  • 3.打開視窗
  • 4.初始化
  • 5.放置标簽和按鈕
  • 6.按鈕事件
  • 7.示範

任務

  基于爬取到的英語六級高頻詞,利用python中的tkinter做出一個能起到考察詞彙掌握情況作用的GUI。

1.引入庫

import tkinter as tk #GUI
import random #抽單詞
           

2.讀入資料

f=open('./cet6word.txt','r',encoding='utf-8')
word=[]
mean=[]
for line in f:
    l=line.split()
    word.append(l[0])    
    m=''
    for i in l:
        if i!=l[0]:
            m=m+i
    mean.append(m)
           

該處使用的是爬取英語六級高頻詞中儲存的資料。

3.打開視窗

# 主視窗
window = tk.Tk()
window.title("cet6---1.0")   # 視窗标題
window.geometry('400x500')  # 視窗尺寸
           

4.初始化

l=['']*100#标簽
bt=[['']*5]*100#按鈕
c=0#計數
           

5.放置标簽和按鈕

代碼如下:

j=random.randint(0,len(word))
print(j)
print(word[j],": ")
k=random.randint(0,3)
#标簽
var = tk.StringVar()
l[c] = tk.Label(window, textvariable=var, bg='gray',fg='white', font=('Arial', 12), width=50, height=2)
l[c].pack()
var.set(word[j])
# 按鈕
for z in range(4):
    if(z==k):          
        bt[c][z]=(tk.Button(window, text=mean[j], width=35, height=2))
        bt[c][z].pack()#正确答案随機放在四個選項中
    else:
        bt[c][z]=(tk.Button(window, text=mean[random.randint(0,len(word))], width=35, height=2))
        bt[c][z].pack()
for i in range(4):
    if(bt[c][i].config('text')[-1]==mean[j]):
        bt[c][i].bind("<Button-1>",hit_me1)
    else:
        bt[c][i].bind("<Button-1>",hit_me2)
bt[c][4]=(tk.Button(window, text='下一個', width=15, height=2))
bt[c][4].bind("<Button-1>",hit_me3)    
bt[c][4].pack()
           

6.按鈕事件

代碼如下:

def hit_me1(event):#按鈕正确答案
    event.widget["bg"]='green'#綠色表示正确
def hit_me2(event):#按鈕錯誤答案
    event.widget["bg"]='red'#紅色表示錯誤
def hit_me3(event):#按鈕下一頁
    global c
    for i in range(5):
        bt[c][i].destroy()#删掉上一頁的按鈕
    l[c].destroy()#删掉上一頁的标簽
    c=c+1
    #偷懶複制粘貼
    j=random.randint(0,len(word))
    print(j)
    print(word[j],": ")
    k=random.randint(0,3)
    var = tk.StringVar()
    l[c] = tk.Label(window, textvariable=var, bg='gray',fg='white', font=('Arial', 12), width=50, height=2)
    l[c].pack()
    var.set(word[j])
    for z in range(4):
        if(z==k):          
            bt[c][z]=(tk.Button(window, text=mean[j], width=35, height=2))
            bt[c][z].pack()
        else:
            bt[c][z]=(tk.Button(window, text=mean[random.randint(0,len(word))], width=35, height=2))
            bt[c][z].pack()
    for i in range(4):
        if(bt[c][i].config('text')[-1]==mean[j]):
            bt[c][i].bind("<Button-1>",hit_me1)
        else:
            bt[c][i].bind("<Button-1>",hit_me2)
    bt[c][4]=tk.Button(window, text='下一個', width=15, height=2)
    bt[c][4].bind("<Button-1>",hit_me3)    
    bt[c][4].pack()
           

7.示範

基于tkinter的第一個GUI小項目:背英語六級單詞軟體任務1.引入庫2.讀入資料3.打開視窗4.初始化5.放置标簽和按鈕6.按鈕事件7.示範
基于tkinter的第一個GUI小項目:背英語六級單詞軟體任務1.引入庫2.讀入資料3.打開視窗4.初始化5.放置标簽和按鈕6.按鈕事件7.示範

小結

  寫了大半天bug才勉強能運作了,忽略界面醜,功能簡陋,還是差強人意。就到這裡,以後有時間再随緣更新更新。