python - python tkinter“in”运算符不起作用
问题描述
我的问题是,仅当您单独给出答案时,程序才会将答案声明为正确,但我想让您实际上可以在条目小部件中放入一个短语,如果答案在那个短语中,它会说正确,我在没有 tkinter 的情况下完成了这项工作,但我无法让它在 tkinter 中工作,这是我的代码,请你帮忙,谢谢。
编码
import tkinter as tk
from time import sleep
win = tk.Tk()
win.title("Learning game")
class Question:
def __init__(self,prompt,answer):
self.answer = answer
self.prompt = prompt
score = 0
def ask():
global questions
global useranwser
global score
if questions:
#Check both the possible answers
if useranwser.get() in questions[0].answer:
print("Correct")
score += 1
else:
print("Incorrect")
questions.pop(0)
if questions:
s.set(questions[0].prompt)
else:
print('Done')
print("Your score is : ",score)
quit() #optional
useranwser.set('')
question_prompts = [
"When did Tunisia gain independence? \n 1956 , 1984 , 1965 \n", "What is the captial of tunis ? \n Tunis, Gafsa, Nabuel \n",
"Who won 2018 football world cup ? \n Italy, France, England \n","how long is the eiffel tower ?\n 324m, 354m, 412m \n",
"What is the heaviest metal \n Iron, Copper, Uraniam \n "
]
questions = [
Question(question_prompts[4], "uraniam"),
Question(question_prompts[0], "1956"),
Question(question_prompts[1], "tunis"),
Question(question_prompts[2], "france"),
Question(question_prompts[3], "324m")
]
s = tk.StringVar()
useranwser = tk.StringVar()
q = tk.Label(win,textvariable = s)
q.grid(row = 0, column = 0)
u_answer = tk.Entry(win, textvariable = useranwser)
u_answer.grid(row = 1, column = 0)
b = tk.Button(win, text ="Submit", command = ask)
b.grid(row = 2, column =0 )
s.set(questions[0].prompt)#Set the initial question
win.mainloop()
解决方案
如果来自此的声明,我必须翻转此:
if useranwser.get() in questions[0].answer:
print("Correct")
score += 1
对此:
if questions[0].answer in useranwser.get():
print("Correct")
score += 1
感谢@justin ezequiel 的解决方案和@random davis 的调试技巧
推荐阅读
- python - 如何从以前的正则表达式结果中查看字符串
- algorithm - 使用 omega 作为最坏情况运行时间而不是 O
- linux - 检测到 USB 驱动器但无法在 linux 中的任何位置显示
- python - Python 脚本不会使用 PHP 运行
- reactjs - 如何在反应对象上创建新属性?错误:无法分配给只读属性
- asp.net - 如果 __VIEWSTATE 未加密,如何正确解码?
- javascript - 使用 Google Apps 脚本根据列的条件使行在 Google 表格中不可编辑
- r - 覆盖ggplot中渐变色阶的自动分配值
- go - 如何使用beego生成离线swagger doc
- wpf - 如何将焦点设置到内部 TextBox 但闪烁的插入符号可见?