班级互相影响

时间:2019-04-15 23:14:10

标签: python class tkinter interaction

我想通过功能使一个类与另一个类交互。 一个单击该按钮的按钮,添加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()

我想知道如何在Characteristics类和Resources类之间进行交互

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

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

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

如果它们是要在主文件中使用的不同文件

1 个答案:

答案 0 :(得分:1)

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

在您的代码中,这可能意味着您应该将对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
相关问题