如何在tkinter中使用SHIFT选择多个复选框?

时间:2013-03-26 09:02:40

标签: python checkbox tkinter

问题很简单,我使用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()

这就是它的样子:

enter image description here

我想选择多个复选框,如果我必须点击每个复选框,这很麻烦。那么有没有办法在这里使用 SHIFT

1 个答案:

答案 0 :(得分: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()