簡體   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