【问题标题】:Tkinter Python , Trying to load a string from a dictionary which is loaded from fileTkinter Python,试图从从文件加载的字典中加载字符串
【发布时间】:2017-11-15 23:12:19
【问题描述】:

我一直将此编码为使用 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()

【问题讨论】:

标签: python tkinter


【解决方案1】:

你在中错误地使用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)

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

但我看到了其他问题 - 你使用了这个地方不存在的其他变量 - QuizSelectionTopicDifficultyInput
它们在其他函数中作为局部变量存在,您不能像全局变量一样使用它。

你可以从函数QuizType()得到QuizSelection

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

但您仍然无法访问变量TopicDifficultyInput


您似乎不知道如何使用函数。

你也必须学习如何在课堂上使用self.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 2012-05-22
    • 1970-01-01
    • 2020-05-19
    相关资源
    最近更新 更多