繁体   English   中英

从tkinter中的另一个类更新列表框

[英]updating listbox from another class in tkinter

我正在尝试做的是在Controller类的onopen函数中我试图在View类中运行update_listbox函数,它将更新列表框。 这给了我错误update_listbox()必须使用View实例作为第一个参数调用。 我不完全明白我在做什么,所以如果有人可以向我解释我在这里做错了什么以及如何正确地做到这一点会非常有帮助。

欢呼tchadwik

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))) 

您需要实例化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__()之前不会创建self.list ,这是从View类定义创建View对象时发生的。

暂无
暂无

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

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