微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我不明白是什么原因导致程序冻结

如何解决我不明白是什么原因导致程序冻结

import random
import json
from tkinter import *

with open('worldcountries.json') as file_Obj:
    data = json.load(file_Obj)

 
questions = [x for x in data[0].values()]
mcq_choices = [x for x in data[1].values()]

answers = [2,1,2,3,2]
candidate_ans = []
indexes = []

def showresult(score):
    resultwin = Tk()
    resultwin.title('Results')
    if score < 20:
        lblresult = Label(resultwin,text='Too bad!',font='Helvetica 20 bold',fg='red')
        lblresult.pack(padx=20,pady=30)
    if score >= 20 and score < 50:
        lblresult = Label(resultwin,text='Good!',fg='green')
        lblresult.pack(padx=20,pady=30)
    if score >= 50 and score < 80:
        lblresult = Label(resultwin,text='Great!',fg='blue')
        lblresult.pack(padx=20,pady=30)
    if score >= 80:
        lblresult = Label(resultwin,text='Excellent!',fg='yellow')
        lblresult.pack(padx=20,pady=30)
    

def calculate():
    global answers,candidate_ans,indexes
    x = 0
    score = 0
    for x in indexes:
        if candidate_ans[x] == answers[i]:
            score += 10
        x += 1
    showresult(score)

def selected():
    global mcqvar,ques,m1,m2,m3,m4,ques
    x = mcqvar.get()
    candidate_ans.append(x)
    ques = 1
    if ques < len(questions):
        lblquestion.config(text=questions[indexes[ques]])
        m1['text'] = answers[indexes[ques]][0]
        m2['text'] = answers[indexes[ques]][1]
        m3['text'] = answers[indexes[ques]][2]
        m4['text'] = answers[indexes[ques]][3]
        ques += 1
    else:
        calculate()

def startquiz():
    startwin = Tk()
    startwin.title('Start!')
    global indexes
    while len(indexes) <= len(questions):
        x = random.randint(0,9)
        if x in indexes:
            continue
        else:
            indexes.append(x)
    global lblquestion
    lblquestion = Label(startwin,text=questions[indexes[0]])
    lblquestion.pack(padx=10,pady=10)

    global mcqvar
    mcqvar = Intvar()
    global m1,m4
    m1 = Radiobutton(startwin,text=mcq_choices[indexes[0]][0],value=0,variable=mcqvar,command=selected)
    m1.pack(padx=10,pady=20)
    m2 = Radiobutton(startwin,text=mcq_choices[indexes[0]][1],value=1,command=selected)
    m2.pack(padx=10,pady=20)
    m3 = Radiobutton(startwin,text=mcq_choices[indexes[0]][2],value=2,command=selected)
    m3.pack(padx=10,pady=20)
    m4 = Radiobutton(startwin,text=mcq_choices[indexes[0]][3],value=3,command=selected)
    m4.pack(padx=10,pady=20)

    
 
 
win = Tk()
win.title('Start quiz')
win.geometry('300x200')

lbquiz = Label(win,text='QUIZ',font='Helvetica 20 bold')
lbquiz.place(x=75,y=50)

btnstart = Button(win,text='Start',command=startquiz)
btnstart.place(x=100,y=150)




worldcountries.json
[
    {
        "1": "How many Keywords are there in C Programming language ?","2": "Which of the following functions takes A console Input in Python ?","3": "Which of the following is the capital of India ?","4": "Which of The Following is must to Execute a Python Code ?","5": "The Taj Mahal is located in  ?","6": "The append Method adds value to the list at the  ?","7": "Which of the following is not a costal city of india ?","8": "Which of The following is executed in browser(client side) ?","9": "Which of the following keyword is used to create a function in Python ?","10": "To Declare a Global variable in python we use the keyword ?"
    },{
        "1": [
            "23","32","33","43"
        ],"2": [
            "get()","input()","gets()","scan()"
        ],"3": [
            "Mumbai","Delhi","Chennai","LuckNow"
        ],"4": [
            "TURBO C","Py Interpreter","Notepad","IDE"
        ],"5": [
            "Patna","Benaras","Agra"
        ],"6": [
            "custom location","end","center","beginning"
        ],"7": [
            "Bengluru","Kochin","Mumbai","vishakhapatnam"
        ],"8": [
            "perl","css","python","java"
        ],"9": [
            "function","void","fun","def"
        ],"10": [
            "all","var","let","global"
        ]
    }
]

为了使程序成功运行,我尝试编写了该程序。在编写此程序之前,我还仔细阅读了文档,并遵循了适当的方法。我错过了什么使程序冻结?请问按下按钮时该程序死机的原因是什么?如果可能的话,有人可以教我如何解决这个问题?

解决方法

您的代码有很多问题,包括但不限于:

  • 使用不存在的变量
  • 无限循环
  • 覆盖根
  • 污染的命名空间
  • 命名错误
  • 重复逻辑
  • 访问错误的变量
  • mainloop
  • 您的“答案”列表有误〜我没有解决此问题

以下脚本是您测验的完整版本,可以解决所有问题。

#don't pollute your namespace with *
import random,json,tkinter as tk


#you kept makng new references to Tk
#~this is the one and only reference
#~attempting to make more than one root in the same process is wrong
root = tk.Tk()
root.title('Start quiz')
root.geometry('400x300')


#get json 
with open('worldcountries.json') as file_Obj:
    data = json.load(file_Obj)


#init unchanging data
#"worldcountries.json" was changed to be only lists,`values()` is not necessary
questions = [x for x in data[0]]
choices   = [x for x in data[1]]

#these values are still wrong
correct_answers = [2,1,2,3,2]


#whack-a-mole method of clearing the screen
def clear_all():
    for child in root.winfo_children():
        #whack-a-mole
        if child in root.place_slaves():
            child.place_forget()
        elif child in root.pack_slaves():
            child.pack_forget()
        elif child in root.grid_slaves():
            child.grid_forget()


''' WIDGETS
    create all widgets without displaying them
'''
def widgets():
    global choice_var
    choice_var = tk.IntVar()

    global question_lbl
    question_lbl = tk.Label(root)

    global c1,c2,c3,c4
    #don't set the text yet,let next_question do it
    c1 = tk.Radiobutton(root,value=0,variable=choice_var,command=next)
    c2 = tk.Radiobutton(root,value=1,command=next)
    c3 = tk.Radiobutton(root,value=2,command=next)
    c4 = tk.Radiobutton(root,value=3,command=next)
    
    global display_lbl
    display_lbl = tk.Label(root,font='Helvetica 20 bold')
    
    global start_btn
    start_btn = tk.Button(root,text='Start',command=start_quiz)


''' START/END SCREEN
    if correct is not None this will be the end screen ELSE start screen
'''
def screens(correct=None):
    clear_all()
    display_lbl.pack(padx=20,pady=30)

    if not correct is None: 
        #by checking the higher scores first we can simplify our conditions
        if correct   > 7:
            display_lbl.config(text='Excellent!',fg='yellow')
        elif correct > 4:
            display_lbl.config(text='Great!',fg='blue')
        elif correct > 1:
            display_lbl.config(text='Good!',fg='green')
        else:
            display_lbl.config(text='Too Bad!',fg='red')
    else:
        #score is None,this is a start screen
        display_lbl.config(text='Quiz')

    start_btn.place(relx=.5,rely=.5,anchor='center')


''' NEXT DELEGATE
    display the next question if there is one
    ELSE add score and display end screen
'''
def next():
    global question

    #append answer to history
    user_answers.append(choice_var.get())

    if question < len(questions):
        #derive next question and choices
        question_lbl.config(text=questions[indexes[question]])

        #you had all of these set to 'answers[indexes[question]][n]'
        c1['text'] = choices[indexes[question]][0]
        c2['text'] = choices[indexes[question]][1]
        c3['text'] = choices[indexes[question]][2]
        c4['text'] = choices[indexes[question]][3]

        question += 1
    else:
        #calculate number of correct answers and display end screen
        correct = 0
        for x in indexes:
            if user_answers[x] == correct_answers[x]:
                #why add 10? You don't display this number
                correct += 1
        screens(correct)


''' START QUIZ
    init dynamic data and pack/show question/answer interface
'''
def start_quiz():
    clear_all()

    global user_answers
    user_answers    = []

    global indexes  
    #shuffle the question order
    #your old method for doing this was running forever
    indexes = list(range(len(questions)))
    random.shuffle(indexes)

    global question
    question = 0

    #display the question/answer interface
    #don't set the text yet,let next() do it
    question_lbl.pack(padx=10,pady=10)

    c1.pack(padx=100,pady=10,anchor='nw')
    c2.pack(padx=100,anchor='nw')
    c3.pack(padx=100,anchor='nw')
    c4.pack(padx=100,anchor='nw')

    #get first question
    next()


#create all widgets
widgets()

#show start display
screens()

#application loop
root.mainloop()

您没有使用任何键名,所以我摆脱了它们。

worldcountries.json

[
    [
        "How many Keywords are there in C Programming language ?","Which of the following functions takes A console Input in Python ?","Which of the following is the capital of India ?","Which of The Following is must to Execute a Python Code ?","The Taj Mahal is located in  ?","The append Method adds value to the list at the  ?","Which of the following is not a costal city of india ?","Which of The following is executed in browser(client side) ?","Which of the following keyword is used to create a function in Python ?","To Declare a Global variable in python we use the keyword ?"
    ],[
        [
            "23","32","33","43"
        ],[
            "get()","input()","gets()","scan()"
        ],[
            "Mumbai","Delhi","Chennai","Lucknow"
        ],[
            "TURBO C","Py Interpreter","Notepad","IDE"
        ],[
            "Patna","Benaras","Agra"
        ],[
            "custom location","end","center","beginning"
        ],[
            "Bengluru","Kochin","Mumbai","vishakhapatnam"
        ],[
            "perl","css","python","java"
        ],[
            "function","void","fun","def"
        ],[
            "all","var","let","global"
        ]
    ]
]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。