我不明白是什么问题使程序冻结了

2024-04-26 01:19:14 发布

您现在位置:Python中文网/ 问答频道 /正文

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,0,1,2,3,1,2,0,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!',font='Helvetica 20 bold',fg='green')
        lblresult.pack(padx=20,pady=30)
    if score >= 50 and score < 80:
        lblresult = Label(resultwin,text='Great!',font='Helvetica 20 bold',fg='blue')
        lblresult.pack(padx=20,pady=30)
    if score >= 80:
        lblresult = Label(resultwin,text='Excellent!',font='Helvetica 20 bold',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,candidate_ans,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,m2,m3,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,variable=mcqvar,command=selected)
    m2.pack(padx=10,pady=20)
    m3 = Radiobutton(startwin,text=mcq_choices[indexes[0]][2],value=2,variable=mcqvar,command=selected)
    m3.pack(padx=10,pady=20)
    m4 = Radiobutton(startwin,text=mcq_choices[indexes[0]][3],value=3,variable=mcqvar,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",
            "Delhi",
            "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"
        ]
    }
]

为了使程序能够成功运行,我已经尽力编写了这个程序。在我编写这个程序之前,我也仔细阅读了文档,并遵循了合适的方法。是不是我错过了什么让节目冻结了?请问当我按下按钮时,这个程序冻结的原因是什么?如果可能的话,有人能教我如何解决这个问题吗


Tags: ofthetextinifglobalpackanswers
1条回答
网友
1楼 · 发布于 2024-04-26 01:19:14

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

  • 使用不存在的变量
  • 无限循环
  • 覆盖根目录
  • 受污染的名称空间
  • 恶名
  • 重复逻辑
  • 访问错误的变量
  • 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,0,1,2,3,1,2,0,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,variable=choice_var,command=next)
    c3 = tk.Radiobutton(root,value=2,variable=choice_var,command=next)
    c4 = tk.Radiobutton(root,value=3,variable=choice_var,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,pady=10,anchor='nw')
    c3.pack(padx=100,pady=10,anchor='nw')
    c4.pack(padx=100,pady=10,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",
            "Delhi",
            "Benaras",
            "Agra"
        ],
        [
            "custom location",
            "end",
            "center",
            "beginning"
        ],
        [
            "Bengluru",
            "Kochin",
            "Mumbai",
            "vishakhapatnam"
        ],
        [
            "perl",
            "css",
            "python",
            "java"
        ],
        [
            "function",
            "void",
            "fun",
            "def"
        ],
        [
            "all",
            "var",
            "let",
            "global"
        ]
    ]
]

相关问题 更多 >