将变量从一个函数传输到另一个函数而不触发 random.choice

Transferering variable from one function to another without triggering random.choice

我是 python 的新手,在一个问题上卡了几个小时。我正在制作一个随机选择单词的问答游戏,您必须正确回答。当我一开始 运行 代码一切正常并且工作正常时,但是在调用 new_word() 函数之后,click() 函数不会更新所以它最终是相同的答案,即使问题变了。我试图通过在 click() 函数中调用 new_word() 函数来解决这个问题,但这带来了更多问题。

下面是我的代码,唯一的例外是 ('filedirectory') 是我的 .csv 文件的实际文件目录 .任何帮助将不胜感激!

import random
from random import choice, randrange
from tkinter import *
import csv

window = Tk()

window.geometry("400x200")
window.title("Test")

def new_word():
    with open('filedirectory') as f:
        reader = csv.reader(f)
        Entree = random.choice(list(reader))
    show_word['text'] = Entree[0].title()
    return Entree

show_word = Label(window, text="Your word is:")
show_word.grid(row=1, column= 0)

def click():
    print(Entree)
    input_text = textentry.get()
    output.delete(0.0, END)
    # Entree = new_word()
    if input_text == Entree[1]:
        output.insert(END, "Correct")
    else:
        output.insert(END, "That's wrong: " + Entree[1])

Entree = new_word()

Button(window, width=6 , height=1 , text="Validate", command=click, takefocus=0).grid(row=3, column=0)

textentry = Entry(window, width=20)
textentry.grid(row=2, column= 0)
textentry.focus()

Button(window, width=6, height=1, text="New word", command=new_word ,takefocus=0).grid(row=2, column=1)


def press_enter(enter):
    click()
window.bind('<Return>', press_enter)


Label(window, text="Definition", takefocus=0).grid(row=4, column=0)

output = Text(window, height=3, width=40, wrap=WORD, takefocus=0)
output.grid(row=5, column=0)

def press_tab(tab):
    new_word()
    textentry.delete(0, END)
    output.delete(0.0, END)
window.bind('<Tab>', press_tab)


Button(window, text='Quit', command=window.destroy, takefocus=0).grid(row=7, column=1)


window.mainloop()

Button 运行s new_word() 但它不知道如何处理返回值但是 new_word() - 你必须使用 global Entree 和直接给这个变量赋值。

def new_word():
    global Entree

    with open('filedirectory') as f:
        reader = csv.reader(f)
        Entree = random.choice(list(reader))

    show_word['text'] = Entree[0].title()

开始时你必须 运行 new_word() 而不是 Entree = new_word()