Tkinter Python,尝试从文件加载的字典中加载字符串

时间:2017-11-15 23:12:20

标签: python tkinter

我一直在用python编写这个作为Tkinter的个人练习/测试,我正在尝试加载一个包含字典内的字典的文件并读取不应该是问题的文件,但问题是, TempDict没有被定义为分类。

我也很抱歉,如果某些代码没有正确缩进,它没有很好地复制和粘贴,所以我不得不进行一些更正。

import tkinter as tk
from tkinter import *
from tkinter import ttk
import tkinter.messagebox as tm
import os
import pickle


class Quiz (tk.Tk):
    def __init__ (self, *args , **kwargs):


        tk.Tk.__init__(self, *args , **kwargs)
        tk.Tk.wm_title(self, "Quiz")

        container = tk.Frame (self)
        container.pack (side = "top" , fill = "both" , expand = True)
        container.grid_rowconfigure (0,weight = 1)
        container.grid_columnconfigure (0,weight = 1)

        self.frames = {}
        for F in (StartPage, Menu, Difficulty, QuestionsStart):

            frame = F(container, self)
            self.frames[F] = frame
            frame.grid (row = 0, column = 0 , sticky = "nsew")

        self.show_frame(StartPage)

    def show_frame(self,cont):

        frame = self.frames[cont]
        frame.tkraise()

class StartPage(tk.Frame):

    def __init__(self, parent, controller):


        tk.Frame.__init__(self,parent)
        label = tk.Label(self, text = "Login")
        label.pack(pady = 10 , padx = 10)

        global Username
        User = tk.Label (self, text = "Username")
        User.pack()

        Username = tk.Entry(self)
        Username.pack()
        Pass = tk.Label (self, text = "Password")
        Pass.pack()

        Password = tk.Entry (self, show = "*")
        Password.pack()

        button1 = ttk.Button(self, text = "Login",
                        command = lambda: Login(Username,Password,parent,controller,self) )
        button1.pack()

        button2 = ttk.Button(self, text = "Sign Up",
                        command = lambda: Signup())
        button2.pack()



class Menu(tk.Frame):

    def __init__ (self, parent, controller):

        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text = "Menu")
        label.pack()

        Label = tk.Label(self, text = "Please enter Maths or Chemsitry")
        Label.pack()

        Topic = tk.Entry(self)
        Topic.pack()

        Proceed = ttk.Button(self, text = "Proceed", command = lambda: controller.show_frame(Difficulty))
        Proceed.pack()

        Result = ttk.Button(self, text = "Results",
                       command = lambda: Results(controller))
        Result.pack()

        Logout = ttk.Button(self, text = "Log Out",
                        command = lambda: controller.show_frame(StartPage))
        Logout.pack()



class Difficulty(tk.Frame):

    def __init__ (self, parent, controller):

        tk.Frame.__init__(self,parent)
        label = tk.Label(self, text = "Difficulty")
        label.pack()

        Label = tk.Label(self, text = "Please enter Easy, Medium or Hard")
        Label.pack()

        DifficultyInput = tk.Entry(self)
        DifficultyInput.pack()

        StartQuiz = tk.Button(self , text = "Start Quiz", command = lambda: controller.show_frame(QuestionsStart))
        StartQuiz.pack()



        backtomenu = ttk.Button(self, text = "Back to Menu",
                           command = lambda: controller.show_frame(Menu))
        backtomenu.pack()


def DictFromFile ():
    TempDict = {}
    try:
        with open("Questions.txt" , "r") as file:
            TempDict = eval(file.read())
            file.close()
    except IOError as error:
        print (error)
    print(TempDict)
    return TempDict

DictFromFile()

def QuizType(Topic, DifficultyInput):

    QuizSelection = str(Topic.get().lower() + DifficultyInput.get().lower())
    return QuizSelection

class QuestionsStart (tk.Frame):
    def __init__(self , parent, controller):

        tk.Frame.__init__(self,parent)
        Label = tk.Label(self, text = DictFromFile(TempDict[QuizSelection(Topic, DifficultyInput)]["Question1"]))
        Label.pack()




def Login(Username,Password,parent,controller,self):

    Usernames = []
    Login = True
    Username = Username.get()
    Password = Password.get()

    try:

        with open ("Usernames&Passwords.txt" , "rb" ) as file:
            for each in pickle.load(file):
                Usernames.append(each.strip("\n"))
            file.close()

    except IOError as error:
        print (error)

    for each in range(len(Usernames)):
        if Usernames[each] == Username :
            if Usernames[each + 1] == Password:
                Login = True
                controller.show_frame(Menu)
                break
            else:
                Login = False
        else:
           Login = False
    if Login == False:
        tm.showinfo("Your Username or Password is incorrect" , "Your Usename or Password is incorrect")

def Results (controller):

    UsersResults = []
    Counter = 0
    Topic = []
    Difficulty = []
    Mark = []
    Percentage = []
    Grade = []

    try:                      
        with open(Username.get() + ".txt" , "r" , encoding = "UTF-8") as file:
            for each in file:
                UsersResults.append(each.strip("\n"))

    except IOError as error:
        print(error)
    print (UsersResults)
    print (Counter)
    for each in range (len(UsersResults)):
        Topic = UsersResults[Counter]
        Difficulty = UsersResults[Counter + 1]
        Mark = UsersResults[Counter + 2]
        Percentage = UsersResults[Counter + 3]
        Grade = UsersResults[Counter + 4]
        Counter += 5



    return UsersResults






app = Quiz()
app.geometry ("500x300")
app.mainloop()

1 个答案:

答案 0 :(得分:0)

您在

中以错误的方式使用DictFromFile()
tk.Label(self, text=DictFromFile(TempDict[QuizSelection(Topic, DifficultyInput)]["Question1"])

您无法使用参数运行DictFromFile() 它返回你必须为变量提供的字典,然后你就可以得到问题了。

应该是

temp_dict = DictFromFile()

question = temp_dict[QuizSelection(Topic, DifficultyInput)]["Question1"]

tk.Label(self, text=question)

现在您在变量TempDict中有字典temp_dict

但我发现其他问题 - 您使用的其他变量在此处不存在 - QuizSelectionTopicDifficultyInput
它们作为局部变量存在于其他函数中,您不能像全局变量一样使用它。

您可以从功能QuizSelection

获取QuizType()
quiz_selection = QuizType(Topic, DifficultyInput)
question = temp_dict[quiz_selection]["Question1"]

但您仍然无法访问变量TopicDifficultyInput

看起来你不知道如何使用功能。

您还必须学习如何在课程中使用self.