Skip to content

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

I’m very new to python and have gotten stuck on a problem for hours. I’m making a quiz game that picks a random word and you have to answer correctly. When I at first run the code everything i good and working correctly, but after the new_word() function is called the click() function doesn’t update so it ends up being the same answer even though the question changed. I tried to resolve this by calling the new_word() function inside the click() function but that brings out even more problems.

Below is my code with the only exception being that (‘filedirectory’) is my actual filedirectory for the .csv file . Any help would be greatly appreciated!

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()

Answer

Button runs new_word() but it doesn’t know what to do with value returned but new_word() – you have to use global Entree and assign value directly to this variable.

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()

And at start you have to run new_word() instead of Entree = new_word()