首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python tkinter "in“操作符不起作用

python tkinter "in“操作符不起作用
EN

Stack Overflow用户
提问于 2021-01-29 02:39:31
回答 1查看 44关注 0票数 0

我的问题是,只有当你单独输入答案时,程序才会声明答案是正确的,但我想让你实际上可以在entry小工具中放置一个短语,如果答案在该短语中,它会说正确,我在没有tkinter的情况下完成了这项工作,但我不能让它在tkinter中工作。这是我的代码,可以帮助我吗,谢谢。

代码

代码语言:javascript
复制
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()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-29 05:02:04

我不得不将这条if语句从下面的语句中翻转过来:

代码语言:javascript
复制
if useranwser.get() in questions[0].answer:
            print("Correct")
            score += 1

要这样做:

代码语言:javascript
复制
if questions[0].answer in useranwser.get():
            print("Correct")
            score += 1

感谢@justin ezequiel的解决方案和@random davis的调试技巧

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65943285

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档