1

问题很简单,我使用 . 在 Text 小部件中创建了许多复选框。window_create代码如下:

import tkinter as tk

root = tk.Tk()
sb = tk.Scrollbar(orient="vertical")
text = tk.Text(root, width=40, height=20, yscrollcommand=sb.set)
sb.config(command=text.yview)
sb.pack(side="right",fill="y")
text.pack(side="top",fill="both",expand=True)
for i in range(30):
    cb = tk.Checkbutton(text="checkbutton %s" % i,padx=0,pady=0,bd=0)
    text.window_create("end", window=cb)
    text.insert("end", "\n") 

root.mainloop()

这是它的样子:

在此处输入图像描述

我想选择多个复选框,如果我必须单击每个复选框,这很麻烦。那么这里有没有可以使用SHIFT的方法?

4

1 回答 1

2

您应该将'<Shift-Button-1>'事件绑定到每个检查按钮,以及'<Button-1>指示应该选择的范围的开始。此外,考虑将代码包装在一个类中以获得更好的可读性:

class App:
    def __init__(self, root):
        self.start = 0
        self.root = root
        self.sb = tk.Scrollbar(orient="vertical")
        text = tk.Text(root, width=40, height=20, yscrollcommand=self.sb.set)
        self.sb.config(command=text.yview)
        self.sb.pack(side="right",fill="y")
        text.pack(side="top", fill="both", expand=True)
        self.chkbuttons = [tk.Checkbutton(text="checkbutton %s" % i,padx=0,pady=0,bd=0)
                          for i in range(30)]                        
        for cb in self.chkbuttons:
            text.window_create("end", window=cb)
            text.insert("end", "\n")
            cb.bind("<Button-1>", self.selectstart)
            cb.bind("<Shift-Button-1>", self.selectrange)

    def selectstart(self, event):
        self.start = self.chkbuttons.index(event.widget)

    def selectrange(self, event):
        start = self.start
        end = self.chkbuttons.index(event.widget)
        sl = slice(min(start, end)+1, max(start, end))
        for cb in self.chkbuttons[sl]:
            cb.toggle()
        self.start = end

if __name__ == '__main__':
    root = tk.Tk()
    app = App(root)
    root.mainloop()
于 2013-03-26T10:03:10.787 回答