【问题标题】:Adding a list of checkbuttons to a scrolled text widget将检查按钮列表添加到滚动文本小部件
【发布时间】:2017-04-08 07:32:52
【问题描述】:

我需要在滚动文本小部件内设置检查按钮,每行一个检查按钮,每个按钮后面都有一些文本。我发现这个解决方案是一个 stackoverflow:

Tkinter checkbuttons inside of a Text widget and scrolling

这是一段代码:

for i in range(1000):
    bg = 'grey'
    if i % 2 == 0:
        bg = 'white'
    cb = tk.Checkbutton(text="checkbutton #%s" % i, bg=bg, width=35, justify=tk.LEFT)
    text.window_create("end", window=cb)
    text.insert("end", "\n") # to force one checkbox per line

这对我来说没有多大意义,因为当检查按钮正确显示时,您无法访问它们中的每一个。还是我错了?

【问题讨论】:

  • “无权访问”是什么意思?为什么你没有访问权限?在此特定代码中,您不断覆盖您的 cb 变量,但没有理由不能将复选按钮添加到列表或字典中。
  • 是的,这就是我的意思:您永久覆盖绑定到检查按钮的变量。你能告诉我如何使用列表或字典来获取每个检查按钮的状态吗?在上面的例子中,像 cb[i] = tk.Checkbutton ... 这样的东西有用吗?
  • 这里没有特定于 tkinter 的内容。您解决此问题的方式与解决在循环中创建任何其他类型的字符串或数字或对象的方式相同。将它们附加到列表中,将它们添加到字典中,您可以随心所欲地进行操作。
  • 嗯,无论我尝试什么,它都不起作用。所有的检查按钮,以及文本小部件内的大量超链接,都是通用的,在循环中创建。我无法对通常用于访问检查按钮状态的变量使用任何类型的列表索引。我检查是否选择了检查按钮的标准方法是使用“my_variable = IntVar()”。当我尝试将它与类似“my_variable[i] = IntVar()”之类的列表索引一起使用时,我收到一条错误消息。我在创建通用超链接时遇到了类似的问题。

标签: python tkinter


【解决方案1】:

与任何其他 python 对象一样,为了在其上调用方法,您需要有一个引用。最简单的解决方案是将小部件和变量的引用保存在列表或字典中。

例如:

import tkinter as tk

class Example(object):
    def __init__(self):

        root = tk.Tk()
        text = tk.Text(root, cursor="arrow")
        vsb = tk.Scrollbar(root, command=text.yview)
        button = tk.Button(root, text="Get Values", command=self.get_values)
        text.configure(yscrollcommand=vsb.set)

        button.pack(side="top")
        vsb.pack(side="right", fill="y")
        text.pack(side="left", fill="both", expand=True)

        self.checkbuttons = []
        self.vars = []
        for i in range(20):
            var = tk.IntVar(value=0)
            cb = tk.Checkbutton(text, text="checkbutton #%s" % i,
                                variable=var, onvalue=1, offvalue=0)
            text.window_create("end", window=cb)
            text.insert("end", "\n")
            self.checkbuttons.append(cb)
            self.vars.append(var)
        text.configure(state="disabled")

        root.mainloop()

    def get_values(self):
        for cb, var in zip(self.checkbuttons, self.vars):
            text = cb.cget("text")
            value = var.get()
            print("%s: %d" % (text, value))

if __name__ == "__main__":
    Example()

【讨论】:

  • 谢谢布莱恩,你真的帮了我很多!
猜你喜欢
  • 2012-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-24
  • 1970-01-01
  • 1970-01-01
  • 2013-05-24
  • 1970-01-01
相关资源
最近更新 更多