在Python中使用tablelist包装器配置表格中的组合框值
基本上,我的问题是在用Python(而不是直接用tcl)配置一个表格列表中的下拉框。我准备了一个示例来展示这个问题,但在此之前,我们先看看运行它所需的步骤:
- 从这里复制表格列表的包装代码,保存为'tablelist.py',然后把它放到示例代码的目录里。
- 从这里下载"tklib-0.5",然后把"modules"目录中的"tablelist"文件夹复制到示例代码的目录里。
下面是代码:
from tkinter import *
from tkinter import ttk
from tablelist import TableList
class Window (Frame):
def __init__(self):
# frame
Frame.__init__(self)
self.grid()
# tablelist
self.tableList = TableList(self,
columns = (0, "Parity"),
editstartcommand=self.editStartCmd
)
self.tableList.grid()
# configure column #0
self.tableList.columnconfigure(0, editable="yes", editwindow="ttk::combobox")
# insert an item
self.tableList.insert(END,('Even'))
def editStartCmd(self, table, row, col, text):
#
# must configure "values" option of Combobox here!
#
return
def main():
Window().mainloop()
if __name__ == '__main__':
main()
你会看到它的结果是一个只有一列/单元格的窗口,初始值是(Even)。点击这个单元格后,下拉框会出现(因为使用了"editstartcommand"),但它没有任何值(None)。我知道要编辑单元格的小部件,需要使用"editwinpath"命令来获取临时小部件的路径名,但这个方法只返回一个字符串,指向下拉框小部件的地址,而这个地址是不可调用的。
我会很感激任何帮助或可能的解决方案。
1 个回答
0
我知道我自己回复自己的问题有点奇怪,但我希望这对将来的其他人有帮助。在阅读了TCL中的tablelist脚本和示例后,我找到了我的答案。这个答案有两个部分,一个是关于包装器(在Python中使用的tablelist包装器,你可以在这里找到),另一个部分在我的示例代码中。首先,包装器需要修改,以便在“TableList”类的“configure”方法中包含小部件的路径名。以下是修改后的版本:
def configure(self, pathname, cnf={}, **kw):
"""Queries or modifies the configuration options of the
widget.
If no option is specified, the command returns a list
describing all of the available options for def (see
Tk_ConfigureInfo for information on the format of this list).
If option is specified with no value, then the command
returns a list describing the one named option (this list
will be identical to the corresponding sublist of the value
returned if no option is specified). If one or more
option-value pairs are specified, then the command modifies
the given widget option(s) to have the given value(s); in
this case the return value is an empty string. option may
have any of the values accepted by the tablelist::tablelist
command.
"""
return self.tk.call((pathname, "configure") +
self._options(cnf, kw))
第二个也是最后一个部分是“editstartcommand”(在我的示例代码中是“editStartCmd”方法)必须在最后返回它的“text”变量。这个小技巧可以防止你点击条目时,它们变成“None”。示例代码的正确形式是:
from tkinter import *
from tkinter import ttk
from tablelist import TableList
class Window (Frame):
def __init__(self):
# frame
Frame.__init__(self)
self.grid()
# tablelist
self.tableList = TableList(self,
columns = (0, "Parity"),
editstartcommand=self.editStartCmd
)
self.tableList.grid()
# configure column #0
self.tableList.columnconfigure(0, editable="yes", editwindow="ttk::combobox")
# insert an item
self.tableList.insert(END,('Even'))
def editStartCmd(self, table, row, col, text):
#
# must configure "values" option of Combobox here!
#
pathname = self.tableList.editwinpath()
self.tableList.configure(pathname, values=('Even','Odd'))
return text
def main():
Window().mainloop()
if __name__ == '__main__':
main()
就这些,希望我说得够清楚。