如何从tkinter条目创建重新分级按钮?

hmae6n7t  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(284)

我在做一个vocab测试程序,我在做一个评分按钮。但我遇到了一个问题,当我按两次评分时,评分、条目、对、错都会保留附录,我找不到重置这些列表的方法。因此,当我在更正答案后再次按下评分按钮时,评分重叠并出错。

import tkinter
from tkinter import *

window = tkinter.Tk()
container = tkinter.Frame(window)
canvas = tkinter.Canvas(container)
window.title('Rescue word test')
window.geometry('640x480')
window.resizable(True, True)
scrollbar = tkinter.Scrollbar(container, orient="vertical", command=canvas.yview)

# scroll

main_frame = Frame(window)
main_frame.pack(fill=BOTH, expand=1)

my_canvas = Canvas(main_frame)
my_canvas.pack(side=LEFT, fill=BOTH, expand=1)

my_scrollbar = tkinter.Scrollbar(main_frame, orient=VERTICAL, command=my_canvas.yview)
my_scrollbar.pack(side=RIGHT, fill=Y)

my_canvas.configure(yscrollcommand=my_scrollbar.set)
my_scrollbar.bind('<Configure>', lambda e: my_canvas.configure(scrollregion= my_canvas.bbox("all")))

second_frame = Frame(my_canvas)

my_canvas.create_window((0,0), window= second_frame, anchor="nw")

def mouse_scroll(event):
    my_canvas.yview_scroll(-1 * int((event.delta / 120)), "units")
my_canvas.bind_all("<MouseWheel>", mouse_scroll)

def getEntry( i ):
    return list( second_frame.children.values() )[ i ]

Day21_eng = ['exquisite', 'acquisition', 'regulate', 'transportation', 'insight', 'straightforward', 'cultivate', 'innovation', 'preserve', 'odor', 'exception', 'munch', 'proclaim', 'slap', 'variability', 'investigate', 'flare', 'outpace', 'genuine', 'plead', 'fossilize', 'toil', 'drastic', 'withhold', 'inanimate', 'clockwise', 'amnesia', 'revive', 'theorize', 'culprit', 'limp', 'worn-out', 'indignity', 'span', 'bribe']
Day21_kor = [['우아한', '정교한', '절묘한'], ['취득', '획득', '습득'], ['규제하다', '통제하다'], ['운송', '운임', '추방'], ['통찰', '통찰력'], ['명확한', '솔직한'], ['경작하다', '기르다', '장려하다', '육성하다'], ['혁신'], ['보전', '보호지', '보호하다', '보존하다'], ['냄새', '악취', '기미', '낌새'], ['예외'], ['우적우적 먹다'], ['선언하다'], ['찰싹 때리다'], ['변화성', '가변성', '변용성'], ['조사하다'], ['불끈 성나게 하다', '이글거리다', '불꽃', '타오름'], ['앞지르다', '속도가 더 빠르다'], ['진짜의', '진품의'], ['탄원하다', '변호하다', '애원하다'], ['고착화하다', '화석화하다'], ['수고', '노고', '힘들게 일하다'], ['급격한', '극단적인'], ['보류하다', '유보하다'], ['생명 없는', '무생물의'], ['시계방향으로'], ['기억상실'], ['부활시키다', '되살아나게 하다'], ['이론화하다'], ['죄인', '범죄자', '장본인'], ['절뚝거리다', '느릿느릿 가다', '기운이 없는','축 처진'], ['닳아빠진', '진부한', '지친'], ['모욕', '무례', '치욕'], ['기간', '폭', '범위', '걸치다', '이르다'], ['뇌물을 주다', '뇌물']]

entries = []
grade =[]
def check():
    for i, e in enumerate(entries):
        value = e.get()
        grade.append(str(value in Day21_kor[i]))
    right = [i for i, value in enumerate(grade) if value == 'True']
    wrong = [k for k, value in enumerate(grade) if value == 'False']
    print(right) # I can check that these lists keep appends
    print(wrong)
    print(entries)
    print(grade)
    r = 0
    for i in range(0, len(right)):
        label_right = Label(second_frame, text='O', fg='Blue')
        label_right.grid(column=3, row= right[r])
        r += 1
    w = 0
    for i in range(0, len(wrong)):
        label_wrong = Label(second_frame, text='X', fg= 'red')
        label_wrong.grid(column=3, row= wrong[w])
        w += 1

b = 0
for row, item in enumerate(Day21_eng):
    global label_word 
    label_word = tkinter.Label(second_frame, text= item)
    label_word.grid(column=0, row=row)
    b += 1
    #입력 값 35개
    entry = tkinter.Entry(second_frame, width=30)
    entry.grid(row=row, column=1, sticky='nsew')
    # important to bind each one for access
    entry.bind('<Return>', getEntry)
    entries.append(entry) # save 'entry' into list
b_check = tkinter.Button(second_frame, text='grade', command=check)
b_check.grid(columnspan=2, row=36)

window.mainloop()

如何重新设置这些列表,以便对答案重新评分?我试着加上 right=[] wrong=[] entries=[] grade=[] 并使用另一个列表来消除列表中的重叠值,

def check():
    for i in range(0,35):
        test_try_list[test_try].append(entry) # save 'entry' into list
    for i, e in enumerate(test_try_list[test_try]):
        value = e.get()
        i_list.append(i)
    print(i_list)
    if len(i_list) > 35:
        for i in range(0, len(i_list)):
            new_i_list.append(i_list[i] % 35)
            for v in new_i_list:
                if v not in new_i_list2:
                    new_i_list2.append(v)
    print(new_i_list2)

但它仍然不起作用。如何制作按钮以重新评分?

tzdcorbm

tzdcorbm1#

你可以用 grade.clear() 清除列表

def check():
    grade.clear()

或者你必须使用 global 通知函数必须将新列表分配给外部/全局变量

def check():
    global grade

    grade = []

但我会在没有这些列表的情况下运行它

def check():
    correct = 0
    wrong   = 0

    for i, (e, expected) in enumerate(zip(entries, Day21_kor)):
        value = e.get()
        if value in expected:
            correct += 1
            label = Label(second_frame, text='O', fg='Blue')
        else:
            wrong += 1
            label = Label(second_frame, text='X', fg= 'red')

        label.grid(column=3, row=i)

    print('Correct:', correct, 'Wrong:', wrong)

相关问题