1

我想要做的是在控制器类的 onopen 函数中,我试图在 View 类中运行 update_listbox 函数,该函数将更新列表框。这给了我错误 update_listbox() must be called with View instance 作为第一个参数。我不完全理解我在做什么,所以如果有人可以向我解释我在这里做错了什么以及如何正确地做这将非常有帮助。

干杯乍得维克

from Tkinter import *
import tkMessageBox
import tkFileDialog
from tkFileDialog import askopenfilename
from tkMessageBox import askokcancel

class Controller(object):
    def __init__(self, master=None):

        self._master = master
        #filemenubar
        self.menu()
        #listbox
        self.listboxFrame = View(master)
        self.listboxFrame.pack(fill=BOTH, expand=YES)
        #entry widget
        self.EntryFrame = Other(master)
        self.EntryFrame.pack(fill = X)

    def menu(self):

        menubar = Menu(self._master)
        self._master.config(menu=menubar)

        fileMenubar = Menu(menubar)
        fileMenubar.add_command(label="Open Products File", command=self.onopen)
        fileMenubar.add_command(label="Save Products File", command=self.onsave)
        fileMenubar.add_command(label="exit", command=self.onExit)
        menubar.add_cascade(label="File", menu=fileMenubar)

    def onopen(self):
        fname = askopenfilename()
        products.load_items(fname)
        View.update_listbox() #
        #this gives me error stating that it needs View instance as first argument
        #and adding self here only gives it the controller instance

class View(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        self.list = Listbox(self, selectmode=EXTENDED)
        self.list.pack(fill=BOTH, expand=YES)
        self.current = None
        self.update_listbox()

    def update_listbox(self):   
        temp=products.get_keys()
        for i in temp:
            self.list.insert(END, str(products.get_item(i))) 
4

1 回答 1

3

您需要实例化一个View对象。例如:

def onopen(self):
    fname = askopenfilename()
    products.load_items(fname)

    myview = View(self._master)   # Instantiate the object
    myview.update_listbox()       # Now call update_listbox()

这是因为成员变量(例如:)的内存self.list在对象被实例化之前不会被分配。或者另一种说法self.list是直到被调用才创建,这发生在您从类定义View.__init__()创建对象时。ViewView

于 2012-10-10T05:07:30.390 回答