如何在Python类中引用Tkinter组件

2 投票
1 回答
3927 浏览
提问于 2025-04-18 06:41

我创建了几个列表框(listbox)控件,选择一个框中的一些项目,然后按下面的按钮,就可以把这些项目移动到另一个框里。

这个功能运行得很好,但我想重复使用这个容器框,因为这两个框的布局是一样的(除了标题标签和按钮按下后的功能)。所以我把除了按钮功能以外的所有代码都移到了一个叫“ColumnSelector”的类里。

不过,要把数据从一个“ColumnSelector”移动到另一个,我需要引用这些实例里面的列表框。下面是我想做的结构,但我不确定这样是否可行。

我尝试过其他方法,比如在ColumnSelector类外创建列表框并传递进去,但这样做也遇到了问题。

那么,引用其他类实例里面的控件,最好的方法是什么呢?

    # Data to be included in second listbox widget
    startingSelection = ('Argentina', 'Australia', 'Belgium', 'Brazil', 'Canada', 'China', 'Denmark')

    # Two functions performed by the ColumnSelectors
    def removeSelected(*args):
        idxs = selectedColumns.listBox.curselection() # <- Does not reference correctly
        if len(idxs)>=1:
            for n in reversed(range(len(idxs))):
                idx = int(idxs[n])
                item = selectedColumns.listBox.get(idx)
                selectedColumns.listBox.delete(idx)
                availableColumns.listBox.insert(availableColumns.listBox.size(), item)

    def addSelected(*args):
        idxs = availableColumns.listBox.curselection() #<- Does not reference correctly
        if len(idxs)>=1:
            for n in reversed(range(len(idxs))):
                idx = int(idxs[n])
                item = availableColumns.listBox.get(idx)
                availableColumns.listBox.delete(idx)
                selectedColumns.listBox.insert(selectedColumns.listBox.size(), item)

    # Create ColumnSelectors, pass heading title and function to perform
    selectedColumns = ColumnSelector(self, "Columns to include in export", (), removeSelected).grid(column=0, row=0, sticky=(N,W))
    availableColumns = ColumnSelector(self, "Available Columns", startingSelection, addSelected).grid(column=1, row=0, sticky=(N,W))

class ColumnSelector(ttk.Frame):
    def __init__(self, parent, labelText, startingSelection, function ):
        listBox = Listbox(self, height=5, selectmode='multiple')
        removeColumnsButton = ttk.Button(self, text="Move", command=function)
        #(etc...)

1 个回答

3

在其他类的实例中,引用小部件的最佳方法是什么?

我觉得这种情况最常见的用法是重复使用一个对象很多次,就像你在一个框架内设置的一些列表框一样。在这种情况下,我认为你应该把尽可能多的可重复代码放在子类中,并在其中创建一个方法,返回你想要的内容。当你在主类中创建子类的实例时,就可以在需要的时候访问它的方法(比如,selectedColumns.get_all_listbox_values())。

你需要记住的一件事是,如果你在同一行中创建并布局实例,它将无法正常工作:

不可以

selectedColumns = ColumnSelector(self, "Columns to include in export", (), removeSelected).grid(column=0, row=0, sticky=(N,W))
selectedColumns.get_all_listbox_values()
>>> AttributeError: 'NoneType' object has no attribute 'get_all_listbox_values'

可以

selectedColumns = ColumnSelector(self, "Columns to include in export", (), removeSelected)
selectedColumns.grid(column=0, row=0, sticky=(N,W))
selectedColumns.get_all_listbox_values()
>>> (0, 1, 2, etc)

下面是设置你脚本的一种方式的示例。这里有一个主类(App)和另一个从框架(MyEntry)继承的类,可以在App中多次使用。App类中有一个按钮,可以打印出MyEntry中一个方法的结果,该方法计算几个值。希望这能给你一些关于如何构建代码的想法。

class App(Frame):
    '''the main window class'''
    def __init__(self, parent):
        Frame.__init__(self, parent)

        # create instances of MyEntry, passing whatever operators as args
        # we can make as many of these instances as we need in just a couple of lines
        # and it retains readability
        self.divide = MyEntry(self, '/')
        self.multiply = MyEntry(self, '*')

        self.divide.pack()
        self.multiply.pack()

        Button(self, text='Calculate', command=self._print_result).pack()

    def _print_result(self):
        '''print the return of the calculate method from the instances of
        the MyEntry class'''
        print self.divide.calculate()
        print self.multiply.calculate()

class MyEntry(Frame):
    '''creates two entries and a label and has a method to calculate
    the entries based on an operator'''
    def __init__(self, parent, operator): # include the operator as an arg
        Frame.__init__(self, parent)

        # make an instance variable from the operator to access it between methods
        self.operator = operator

        # make two entries
        self.num1 = Entry(self)
        self.num2 = Entry(self)

        # grid the entries and a label which contains the operator
        self.num1.grid(row=0, column=0)
        Label(self, text=self.operator).grid(row=0, column=1)
        self.num2.grid(row=0, column=2)

    def calculate(self):
        '''return the value of the two entries based on the operator specified'''
        if self.operator is '/':
            return int(self.num1.get()) / int(self.num2.get())
        elif self.operator is '*':
            return int(self.num1.get()) * int(self.num2.get())
        else:
            return

root = Tk()
App(root).pack()
mainloop()

撰写回答