python 2.7中的滚动条,Checkbutton和canvas

时间:2017-09-14 09:25:08

标签: python python-2.7 tkinter scrollbar

我尝试打开一个新窗口,其中会有一个复选框列表,并且可以滚动。

但是,我的列表没有滚动。 这是我的代码:

class PageCanvas1(tk.Toplevel):
    def __init__(self, parent):
        global arr
        global users
        arr = {}
        tk.Toplevel.__init__(self, parent)
        self.title('Canvas')
        self.geometry('400x600')
        canvas = tk.Canvas(self, bg='white', scrollregion=(0, 0, 400, 20000))
        canvas.pack(fill='both', expand=True)

        vbar = tk.Scrollbar(canvas, orient='vertical')
        vbar.pack(side='right', fill='y')
        vbar.config(command=canvas.yview)
        canvas.config(yscrollcommand=vbar.set)
        canvas.create_text(5, 0, anchor='nw', text="Choose users: ")
        for i in range(1000):
            arr[i] = tk.IntVar()
            Checkbutton(canvas, text=str(i), variable=arr[i]).pack()#.grid(row=i, sticky=W)

root = Tk()
b_choose = Button(root, text='choose users', height=3, width=15, bg="turquoise", command=(lambda arr=ents: PageCanvas(root)))

no scroll

我找不到任何特定的答案,必须打开一个新窗口!我很乐意帮忙!

2 个答案:

答案 0 :(得分:1)

如果通过create_window方法将对象添加到画布中,而不是gridpackplace,则只能滚动画布中的对象。< / p>

答案 1 :(得分:0)

import Tkinter as tk

class PageCanvas1(tk.Toplevel):
    def __init__(self, parent):
        global arr # why use global? set it as an attribute?
        global users # same as above?
        arr = {}
        tk.Toplevel.__init__(self, parent)
        self.title('Canvas')
        self.geometry('400x600')
        canvas = tk.Canvas(self, bg='white', scrollregion=(0, 0, 400, 20000))
        canvas.pack(fill='both', expand=True)

        vbar = tk.Scrollbar(canvas, orient='vertical')
        vbar.pack(side='right', fill='y')
        vbar.config(command=canvas.yview)
        canvas.config(yscrollcommand=vbar.set)
        canvas.create_text(5, 0, anchor='nw', text="Choose users: ")
        # we need a container widget to put into the canvas
        f = tk.Frame(canvas)
        # you need to create a window into the canvas for the widget to scroll
        canvas.create_window((200, 0), window=f, anchor="n")
        for i in range(0, 1000):
            arr[i] = tk.IntVar()
            # widget must be packed into the container, not the canvas
            tk.Checkbutton(f, text=str(i), variable=arr[i]).pack()#.grid(row=i, sticky=W)

if __name__ == "__main__":
    app = PageCanvas1(None)
    app.mainloop()