【问题标题】:How to disable a checkbox in a checkboxtreeview widget in Python如何在 Python 中禁用 checkboxtreeview 小部件中的复选框
【发布时间】:2019-05-06 11:48:59
【问题描述】:

我在 Python 脚本中使用来自 ttkwidgets 模块的 checkboxtreeview 小部件。通过将状态设置为“已选中”、“未选中”或“三态”,我可以使项目的复选框按预期显示。

有什么方法可以禁用复选框,即用户不能再通过单击来更改状态?

非常感谢您的帮助!

【问题讨论】:

  • .state = ['disabled'] 和 .state = ['normal']
  • 谢谢,但不完全...由于复选框本身不能用作小部件(除非您深入研究 checkboxtreeview 对象),我无法像这样设置状态。但是,如果我使用self.tree.change_state(item, 'disabled'),我可以使复选框从树视图中消失,这与禁用一样好。实际上,change_state 调用中使用的不是"checked"、"unchecked" 或"tristate" 的任何字符串都会使复选框消失。
  • 你有关于checkboxtreeview widget的参考吗?
  • 我在这个线程link 上找到了对这个小部件的引用,它是可以使用 pip 安装的 ttkwidgets 的一部分。不幸的是,文档不多,但至少 Python 文档功能显示了一些提示。

标签: python tkinter checkbox treeview


【解决方案1】:

您可以添加一个“禁用”标签,并在用户单击树时调用的_box_click() 函数中检查项目在更改其状态之前未禁用。 在下面的代码中我复制了_box_click()方法的源代码并添加了

if self.tag_has("disabled", item):
    return  # do nothing when disabled

禁用状态更改。 我还配置了“禁用”标签,使字体更轻,以便能够看到禁用的项目:self.tag_configure("disabled", foreground='grey')

这里是完整的代码示例:

import ttkwidgets as tw
import tkinter as tk

class CheckboxTreeview(tw.CheckboxTreeview):

    def __init__(self, master=None, **kw):
        tw.CheckboxTreeview.__init__(self, master, **kw)
        # disabled tag to mar disabled items
        self.tag_configure("disabled", foreground='grey')

    def _box_click(self, event):
        """Check or uncheck box when clicked."""
        x, y, widget = event.x, event.y, event.widget
        elem = widget.identify("element", x, y)
        if "image" in elem:
            # a box was clicked
            item = self.identify_row(y)
            if self.tag_has("disabled", item):
                return  # do nothing when disabled
            if self.tag_has("unchecked", item) or self.tag_has("tristate", item):
                self._check_ancestor(item)
                self._check_descendant(item)
            elif self.tag_has("checked"):
                self._uncheck_descendant(item)
                self._uncheck_ancestor(item) 

root = tk.Tk()

tree = CheckboxTreeview(root)
tree.pack()

tree.insert("", "end", "1", text="1")
tree.insert("1", "end", "11", text="11", tags=['disabled'])
tree.insert("1", "end", "12",  text="12")
tree.insert("11", "end", "111", text="111")
tree.insert("", "end", "2", text="2")
root.mainloop()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2021-01-12
    • 2021-02-14
    • 2021-11-20
    • 2022-09-23
    • 2011-05-21
    • 2013-01-19
    相关资源
    最近更新 更多