Python 类之间相互作用

Python 类之间相互作用,python,class,tkinter,interaction,Python,Class,Tkinter,Interaction,我想让一个类通过函数在另一个类中进行交互。 单击时添加1的按钮。但是,当我进行交互时,有一个错误提示,Resources尚未定义 这就是我想要的,但似乎什么都没有发生 from tkinter import * class Caracteristicas: def __init__(self,master): self.caracteristicas = Frame(master) self.caracteristicas.grid(row=1,c

我想让一个类通过函数在另一个类中进行交互。 单击时添加1的按钮。但是,当我进行交互时,有一个错误提示,
Resources
尚未定义

这就是我想要的,但似乎什么都没有发生

from tkinter import *


class Caracteristicas:

    def __init__(self,master):

        self.caracteristicas = Frame(master)
        self.caracteristicas.grid(row=1,column=0)

        self.forca = Label(self.caracteristicas, text='FORÇA FÍSICA')
        self.forca.grid(row=0,column=0)

        self.show_forca = Label(self.caracteristicas,text='1')
        self.show_forca.grid(row=0,column=1)

        self.b_forca = Button(self.caracteristicas,text='+',command=self.ad_for)
        self.b_forca.grid(row=0,column=2)

        self.Forca = 1

    def ad_for(self):
        global Forca
        self.Forca += 1
        Vida = self.Forca + 10
        self.show_forca['text'] = self.Forca
        Recursos.show_ferimentos['text'] = Vida


class Recursos:

    def __init__(self, master):

        self.recursos = Frame(master)
        self.recursos.grid(row=1,column=1)

        self.ferimentos = Label(self.recursos, text='FERIMENTOS')
        self.show_ferimentos = Label(self.recursos, text='10')

        self.ferimentos.grid(row=0,column=0)
        self.show_ferimentos.grid(row=1,column=0)


ficha = Tk()
a = Caracteristicas(ficha)
b = Recursos(ficha)
ficha.mainloop()

我想知道如何在
特性
类和
资源
类之间进行交互

我设法解决了前一个问题,但又出现了另一个问题。这是我的主要程序,而提出的解决方案在这种情况下不起作用

from tkinter import *
from Caracteristicas import Caracteristicas
from Recursos import Recursos

ficha = Tk()
a = Caracteristicas(ficha)
b = Recursos(ficha)
ficha.mainloop()

如果它们是要在main中使用的不同文档

如果您有两个类的实例,并且您需要其中一个类中的函数来修改另一个类中的数据或调用方法,则通常需要将对另一个对象的引用传递到将与其交互的对象中

在代码中,这可能意味着您应该将对
Recursos
实例的引用传递到
Caracteristicas
对象的构造函数中,以便以后使用

下面是一个非常简短的版本,它可能看起来像:

class Caracteristicas:
    def __init__(self, master, resource):
        self.resource = resource    # save value for later
        ... # the rest of the constructor can be the same

    def ad_for(self):
        self.Forca += 1
        Vida = self.Forca + 10
        self.show_forca['text'] = self.Forca
        self.resource.show_ferimentos['text'] = Vida   # main change is here!
您还需要将创建对象的代码更改为:

b = Recursos(ficha)
a = Caracteristicas(ficha, b) # pass the reference to the resource object in

你问题的最后一部分是葡萄牙语。请更新它,因为这个论坛是纯英语的。更改
Recursos.show_ferimentos['text']=Vida
b.show_ferimentos['text']
@HenryYik,谢谢,伙计,它成功了。但是你能告诉我为什么交换吗?
b
代表你创建的类
Recursos
的实例,而
Recursos
只是对类
Recursos
的引用。谢谢@HenryYik,但是出现了另一个问题。你能帮助我吗?检查这个案子,我已经更新了