将导入类的方法与主脚本的类连接

时间:2014-09-24 11:59:23

标签: python oop architecture tkinter

我无法搜索这些问题,因为我不知道要使用的关键字,因此如果它重复或在其他地方回答,请告诉我。

我有一个用tkinter创建主窗口的文件,并导入一些具有不同功能和类的其他模块。我想要一个类的方法将东西输出到我创建的tkinter小部件中。我该怎么办?

file1.py:

from tkinter import * # I use python 3
import tkinter.scrolledtext as tkst
from file2 import *

class Application(Frame):
    def __init__(self, master):
        super(Application, self).__init__(master)
        self.output_text = tkst.ScrolledText(self, width = 100, height = 20,
                                wrap = WORD, bd=0)
        self.output_text.grid(row = 9, column = 0, columnspan = 5, sticky="nsew")

root = Tk()
root.title("Game")
app = Application(root)
center(root)
root.mainloop()

file2.py:

class Hero(object):
    def attack(self, enemy, damage):
        Hero.hits+=1
        if self.hits==0:
            attack = "{}, attacks our enemy {}. Producing {} points of damage.\n".format(
                      self.__name, enemy.creature, truncate(damage))
            # I use code like this in the Application definition.
            app.output_text.insert(END, attack) 

但那变成了:

  File "C:\....\file2.py", line 112, in attack
    app.output_text.insert(END, attack)
NameError: global name 'app' is not defined

我想我应该将一个模块与另一个模块联系起来,但我不知道如何(我读过super函数,但我不知道如何在这里使用它)。我应该做那样的事情或者创建一个事件来在Hero和Application之间传递信息?

1 个答案:

答案 0 :(得分:0)

您可以将课程Hero导入file1.py并通过将应用程序作为另一个参数传递来调用函数attack

注意:我不确定敌人和伤害是什么,所以我正在为你扫视

from tkinter import * # I use python 3
import tkinter.scrolledtext as tkst
from file2 import *
from file2 import Hero#importing the oth

class Application(Frame):
    def __init__(self, master):
        super(Application, self).__init__(master)
        self.output_text = tkst.ScrolledText(self, width = 100, height = 20,
                                wrap = WORD, bd=0)
        self.output_text.grid(row = 9, column = 0, columnspan = 5, sticky="nsew")

root = Tk()
root.title("Game")
app = Application(root)
center(root)

h = Hero()
h.attack(enemy, damage, app) #passing as third argument)

root.mainloop()

file2.py

class Hero(object):
    def attack(self, enemy, damage,app): #change the defenition
        Hero.hits+=1
        if self.hits==0:
            attack = "{}, attacks our enemy {}. Producing {} points of damage.\n".format(
                      self.__name, enemy.creature, truncate(damage))
            # I use code like this in the Application definition.
            app.output_text.insert(END, attack)