当我遇到带有烦人界面的小部件时——例如OptionMenu
,我通常会围绕它编写一个类来抽象出烦人的属性。在这种情况下,我真的不喜欢每次我想创建下拉列表时都使用 StringVar 的冗长,所以我只是创建了一个DropDown
包含类StringVar
内的类(用 Python 3.5 编写,但很容易转换为所有):
class DropDown(tk.OptionMenu):
"""
Classic drop down entry
Example use:
# create the dropdown and grid
dd = DropDown(root, ['one', 'two', 'three'])
dd.grid()
# define a callback function that retrieves the currently selected option
def callback():
print(dd.get())
# add the callback function to the dropdown
dd.add_callback(callback)
"""
def __init__(self, parent, options: list, initial_value: str=None):
"""
Constructor for drop down entry
:param parent: the tk parent frame
:param options: a list containing the drop down options
:param initial_value: the initial value of the dropdown
"""
self.var = tk.StringVar(parent)
self.var.set(initial_value if initial_value else options[0])
self.option_menu = tk.OptionMenu.__init__(self, parent, self.var, *options)
self.callback = None
def add_callback(self, callback: callable):
"""
Add a callback on change
:param callback: callable function
:return:
"""
def internal_callback(*args):
callback()
self.var.trace("w", internal_callback)
def get(self):
"""
Retrieve the value of the dropdown
:return:
"""
return self.var.get()
def set(self, value: str):
"""
Set the value of the dropdown
:param value: a string representing the
:return:
"""
self.var.set(value)
示例用法:
# create the dropdown and grid, this is the ONLY required code
dd = DropDown(root, ['one', 'two', 'three'])
dd.grid()
# optionally, define a callback function that retrieves the currently selected option then add that callback to the dropdown
def callback():
print(dd.get())
dd.add_callback(callback)
编辑添加:创建这篇文章后不久,我对 tk 的其他一些属性感到恼火,最终创建了一个名为tk_tools
使下拉和检查按钮更容易以及解决其他烦恼的包。