python - 如何在 tkinter 的类之间传递值?

标签 python class variables tkinter

我在 Tkinter/Python 中创建了一个十个问题的多项选择测验。我创建了一个类来存储所有按钮,然后创建了十个其他类来存储出现在子窗口中的每个问题,其中问题作为标签和单选按钮/复选按钮。对于每个问题,当用户按下“Enter”时,程序会将他们的选择与正确的回答者进行比较,并在必要时加 1 分。如何使程序中的所有内容(即每个类(class))都可以使用变量“分数”?我是否必须在类(class)之间传递 score 的值?

class Question_5_Window(tk.Toplevel):
    '''A simple instruction window'''
    def __init__(self, parent):
        tk.Toplevel.__init__(self, parent)
        self.text = tk.Label(self, width=100, height=4, text = "5) What would you do if you were walking to class and you saw a first year crying? Tick all correct answers.")
        self.text.pack(side="top", fill="both", expand=True)

        question_5_Var1 = IntVar()
        question_5_Var2 = IntVar()
        question_5_Var3 = IntVar()

        A_5 = Checkbutton(self, text = "Keep walking", variable = question_5_Var1, onvalue = 1, offvalue = 0, height=5, width = 20)
        A_5.pack()

        B_5 = Checkbutton(self, text = "Take them to guidance", variable = question_5_Var2, onvalue = 1, offvalue = 0, height=5, width = 20)
        B_5.pack()

        C_5 = Checkbutton(self, text = "Talk to them to resolve issue", variable = question_5_Var3, onvalue = 1, offvalue = 0, height=5, width = 20)
        C_5.pack()

        def calculate_score():

            if (question_5_Var2.get() == 1) and (question_5_Var3.get() == 1) and not question_5_Var1.get():
                print("calculate score has worked")
                score = score + 1
            else:
                print("not worked")

            return score

        Enter_5 = Button(self, text= "Enter", width=10, command = calculate_score)
        Enter_5.pack()

        return score

最佳答案

根据我们的讨论,获得所需内容的最快方法是向包含问题按钮的 tk 对象添加一个属性。

class WhateverContainer(tk.Frame):
    def __init__(self)  # ... *args, **kwargs or whatever is appropriate
        # ... other stuff
        self.scores = dict()  # common storage

class Question(tk.TopLevel):
    def __init__(self, parent, question_id):  # ... whatever arguments
        # ...
        def callback()
            if nice_answer:
                parent.scores[question_id] = 1

需要明确的是,这不是一个“好的”解决方案,因为至少子窗口不应直接干扰父窗口的数据。但是,我认为它适用于您的应用程序。如果您想获得有关您的设计和编码的反馈,您可能会在 CodeReview 上找到一些好运。 .

我希望测验对你有用。

关于python - 如何在 tkinter 的类之间传递值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20636224/

相关文章:

r - 如何从数据框中删除某些条件

python - 如何强制 Tornado websockets 在握手时生成错误页面

客户端连接不稳定的python套接字服务器/客户端协议(protocol)

python - 类型错误 : function() takes exactly 2 arguments (1 given) (python)

c++ - 仅包含基类 header 时访问派生类

r - 使用 R 中的 lapply 从分类数据创建子组

javascript - 如何在 javascript 中显示显示 var 值的警报

python - 使用决策树绘制学习曲线时,sklearn 糖尿病数据集的测试分数非常低

java - 为什么这个教科书程序无法识别我的 Point2D 对象?

python - 是否有必要在 python 中显式调用 super().__init__() ?