簡體   English   中英

使用多個對象時,在tkinter Python中查找屬性屬於哪個對象

[英]Finding which object an attribute belongs to in tkinter Python when using multiple objects

我的程序包含3個類。 整個程序在MainWindow類中運行。 MainWindow類首先進行自身初始化,然后是self.menubar對象。 下一個對象是一個文本框,其名稱為self.journal。

程序運行后,我嘗試訪問MainWindowopen_file方法,這是通過訪問Menubarfilemenu方法來完成的。 當我嘗試打開文本文件時,出現以下錯誤: AttributeError: 'Menubar' object has no attribute 'journal'發生。

我試圖用MainWindow.journalTextBox.journal替換self.journal ,它似乎不起作用。

class MainWindow(tk.Tk):

    def __init__(self, *args, **kwargs):


        tk.Tk.__init__(self, *args, **kwargs)

        ''''''
        ''''''

        self.menubar = Menubar(self) # instantaiated Menubar object

        '''''
        '''''
        self.journal = TextBox(self.frame, name='Journal')
        '''''
        '''''



    def open_file(self):
        filename = MainWindow.getFileNameOpen(self)
        if filename == '': # No file chosen
            filename = None
        else:
            self.MainWindow.journal.delete(1.0, END) # This line is the problem       
            fh = open(filename, 'r')
            textFromFile = fh.read().rstrip()          
            self.MainWindow.journal.insert(1.0, textFromFile)
            fh.close()



class Menubar:

    def __init__(self, parent):
        self.menubar = tk.Menu(parent)
        self.fileMenu(self.menubar)

    def fileMenu(self, parent):
        filemenu = tk.Menu(parent, tearoff=0)
        filemenu.add_command(label='Open', accelerator='Ctrl+O', underline=0, command=lambda: MainWindow.open_file(self))



class TextBox(tk.Text):

    def __init__(self, parent, name='', *args, **kwargs):
        tk.Label(master=parent, text=name).pack()
        tk.Text.__init__(self, master=parent, *args, **kwargs)
        self.text.pack()

我強調了導致我出現問題的那條線。 它在def open_file(self)方法下

您可以嘗試以下代碼嗎?

類菜單欄:

def __init__(self, parent):
    self.pt = parent
    self.menubar = tk.Menu(parent)
    self.fileMenu(self.menubar)

def fileMenu(self, parent):
    filemenu = tk.Menu(parent, tearoff=0)
    filemenu.add_command(label='Open', accelerator='Ctrl+O', underline=0, command=lambda: self.pt.open_file())

請注意,我是在self保存parent ,然后使用self.pt而不是Main. ,如果那行不通,您也可以嘗試-

lambda: MainWindow.open_file(self.pt)

而不是當前的lambda部分。

問題出在代碼上-

lambda: MainWindow.open_file(self)

它的作用是嘗試通過將當前MenuBar類的實例(對象)作為參數來調用MAinWindow類內的open_file函數。

當您在類中使用object調用函數時,可以這樣說:

obj.func(**params)

在內部,python的調用方式等效於ItsClass.func(obj, **params) ,因此在open_file()函數內部,當您訪問自身對象(通過參數傳遞)時,它不是MainWindow的實例,而是MenuBar一個實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM