我對 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()
uj5u.com熱心網友回復:
Button運行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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/468250.html
