我创建了两个列表框小部件,在其中选择一个项目,然后按下面的按钮将项目移动到另一个。在
这工作得非常好,但是我想重用容器框架,因为这两个框架的布局是相同的(除了标题标签和按下按钮时的功能)。所以我把除了button函数之外的所有代码都移到了一个类“ColumnSelector”。在
但是,要将数据从一个“ColumnSelector”移动到另一个,我需要引用实例中的列表框。下面是我想做的事情的结构,但我不确定这是否可能。在
我尝试过其他一些方法,比如在ColumnSelector类之外创建listbox并传递给它,但是这样做也遇到了问题。在
在其他类的实例中引用小部件的最佳方法是什么?在
# 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...)
我认为最常见的用例是无限次地重用一个对象,因为它看起来像是在试图处理一些在框架内设置的列表框。在这种情况下,我认为您应该在子类中放入尽可能多的可重复代码,并在其中创建一个方法来返回您想要的结果。当您在主类中创建子类的实例时,您可以在需要时访问它的方法(即
selectedColumns.get_all_listbox_values()
)。在需要记住的一点是,如果创建实例并将其网格化在同一行上,则实例将无法正常工作:
否
是
^{2}$下面是一个设置脚本的方法示例。有一个主类(
App
)和另一个继承自Frame(MyEntry
)的类,可以在App
中多次使用。在App
类中有一个按钮,它打印出MyEntry
中计算两个值的方法的结果。希望它能帮助您对构建代码有一些想法。在相关问题 更多 >
编程相关推荐