【问题标题】:How do you change the variable in a function from a different class and call it back?如何从不同的类更改函数中的变量并将其回调?
【发布时间】:2018-05-10 12:59:11
【问题描述】:

我正在制作一个有关卡的游戏,在每个关卡中,我都需要使用不同的运算符和/或不同的范围。我的问题是我不知道如何从不同的类更改函数中的变量。我想这样做,所以我不需要复制和粘贴我的代码,让它变得冗长。我想将 self.Answer 和 self.strQuestion 用于多个范围。

下面的代码只是为了让类正常工作。

from tkinter import *
import tkinter as tk
import random
from Tkinter import messagebox

class BattleMaths(tk.Tk):
     def __init__(self, *args, **kwargs):        
          tk.Tk.__init__(self, *args, **kwargs)
          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, levelone, leveltwo):
               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)

          lvl1_button = Button(self, text="LEVEL 1", command=lambda: controller.show_frame(levelone))
          lvl1_button.place(relx=0.5, rely=0.5, anchor='center') 

我想将问题 def 放入第二级课程,同时将其更改为 self.Answer = int(numOne) * int(numTwo)self.strQuestion = "{} x {}".format(str(numOne), str(numTwo))

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

    def widgets(self):
          #widgets here

    def question(self): 

          self.UserAnswer = ''
          numOne = random.randrange(1,10)
          numTwo = random.randrange(1,10)
          self.Answer = int(numOne) + int(numTwo) #change this
          self.strQuestion = "{} + {}".format(str(numOne), str(numTwo)) #and change this

    def answer(self):
          #answer checker

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

     #question def here

root = BattleMaths()
root.title("Battle Maths")
root.geometry("400x250")
root.resizable(0,0)
root.mainloop()

【问题讨论】:

  • 你能清楚地解释一下,你想在多个范围内使用哪个变量吗?
  • 我建议您首先阅读此答案中链接到的所有答案:stackoverflow.com/a/7557028/7432

标签: python python-3.x class tkinter


【解决方案1】:

在主类(BattleMaths)中创建您想要的变量,然后您可以通过 controller.my_variable 在子类中更改它们。

示例:self.AnswerBattleMaths 中创建并通过controller.Answerlevelone 中访问

【讨论】:

    猜你喜欢
    • 2017-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    • 2011-03-23
    • 2014-04-01
    • 1970-01-01
    相关资源
    最近更新 更多