繁体   English   中英

如何从同一类的不同实例中访问类成员函数? 蟒蛇

[英]How to access class member functions from within different instances of that same class? Python

我的问题是我的tkinter应用程序。 我有一个用于折叠应用程序一部分的按钮,但是,如果单击左侧的每个按钮,则必须按7次折叠按钮才能删除应用程序右侧第一次创建的所有实例。在createArea成员函数中。

我将类的每个实例存储在一个名为dictionary ,我需要使用destroyRight函数在每个实例中销毁应用程序的所有右侧。

当将每个类实例存储在字典中时,我不确定如何访问每个类实例的功能,也不确定如何使一个类的一个实例与所有其他实例进行通信。

帮助将不胜感激。

我的申请图片

from tkinter import*

root = Tk()
class Buttons:
    def __init__(self,master,imperialText,metricText,metricVal):
        self.imperialText,self.metricText,self.metricVal,self.master = imperialText,metricText,metricVal,master

        self.displayedText  = (self.imperialText +'-'+ self.metricText)
        self.button = Button(self.master,text= self.displayedText,command = self.createArea)
        self.button.config(height= 3,width=30)
        self.button.grid(column = 0)

        self.rightCreated = False
        self.rightButtons = []
    def createArea(self):
        self.rightCreated = True
        self.entryBox = Entry(self.master)
        self.entryBox.bind('<Return>',self.calc)
        self.entryBox.grid(column = 1,row = 1)

        self.label = Label(self.master,text = 'Enter '+self.imperialText)
        self.label.grid(column = 1,row = 0)

        self.backButton = Button(self.master,text = '<<Collapse', command = self.destroyRight)
        self.backButton.grid(column = 1, row = 6)

        print('happen') 
        self.rightButtons.extend([self.entryBox,self.label,self.backButton])

    def destroyRight(self):
        collapseAll()
        print(self.rightButtons)
        for i in self.rightButtons:
            i.destroy()


    def calc(self):
        print('hi')

def collapseAll():
    for i in dictionary:
        dictionary[i].destroyRight()




dictionary = {'B1':None,'B2':None,'B3':None,'B4':None,'B5':None,'B6':None,'B7':None}
ImperialText = ['inches','miles','foot','yards','gallons','pounds','ounces']
MetricText = ['centimetres','kilometres','metres','metres','litres','kilograms','grams']
metricVal = [2.54,1.6093,0.3048,0.9144,4.546,0.454,0.454]

num = 0
for i in dictionary:
dictionary[i] = 
Buttons(root,ImperialText[num],MetricText[num],metricVal[num])
    num += 1
    if num == 6:
        print(i)

root.mainloop()

您所要做的只是像dictionary['B1'].calc()这样的事情,它访问字典中的第一个按钮并调用calc方法。

您的实例是字典中的值这一事实并没有什么特别的。 您可以认为这就像为每个实例具有单独的变量B1B2 ...(实际上,全局名称空间只是一个字典)。 将它们放入字典中的一个优点是,您可以轻松地遍历实例,并在每个实例上调用相同的方法,例如:

for b in dictionary.values():
    b.collapse()

管他呢。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM