框架的Tkinter滚动条

Chr*_*ung 55 python tkinter scrollbar frame

我的目标是在一个框架中添加一个垂直滚动条,框架中有几个标签.一旦框架内的标签超过框架的高度,滚动条就会自动启用.经过搜索,我找到了这个有用的帖子.基于这一职位,我明白,为了达到我想要的,(纠正我,如果我错了,我是初学者),我要创建一个Frame第一,然后创建一个Canvas该框架内,坚持滚动条到帧好.之后,创建另一个框架并将其作为窗口对象放在画布中.所以,我终于想到了这个:

from Tkinter import *

def data():
    for i in range(50):
       Label(frame,text=i).grid(row=i,column=0)
       Label(frame,text="my text"+str(i)).grid(row=i,column=1)
       Label(frame,text="..........").grid(row=i,column=2)

def myfunction(event):
    canvas.configure(scrollregion=canvas.bbox("all"),width=200,height=200)

root=Tk()
sizex = 800
sizey = 600
posx  = 100
posy  = 100
root.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy))

myframe=Frame(root,relief=GROOVE,width=50,height=100,bd=1)
myframe.place(x=10,y=10)

canvas=Canvas(myframe)
frame=Frame(canvas)
myscrollbar=Scrollbar(myframe,orient="vertical",command=canvas.yview)
canvas.configure(yscrollcommand=myscrollbar.set)

myscrollbar.pack(side="right",fill="y")
canvas.pack(side="left")
canvas.create_window((0,0),window=frame,anchor='nw')
frame.bind("<Configure>",myfunction)
data()
root.mainloop()
Run Code Online (Sandbox Code Playgroud)
  1. 我做得对吗?是否有更好/更聪明的方法来实现此代码给我的输出?
  2. 为什么我必须使用网格方法?(我尝试了放置方法,但画布上没有任何标签.)
  3. anchor='nw'在画布上创建窗口时使用有什么特别之处?

因为我是初学者,请保持简单的答案.

Gon*_*nzo 38

请注意,建议的代码仅适用于Python 2

这是一个例子:

from Tkinter import *   # from x import * is bad practice
from ttk import *

# http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame

class VerticalScrolledFrame(Frame):
    """A pure Tkinter scrollable frame that actually works!
    * Use the 'interior' attribute to place widgets inside the scrollable frame
    * Construct and pack/place/grid normally
    * This frame only allows vertical scrolling

    """
    def __init__(self, parent, *args, **kw):
        Frame.__init__(self, parent, *args, **kw)            

        # create a canvas object and a vertical scrollbar for scrolling it
        vscrollbar = Scrollbar(self, orient=VERTICAL)
        vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
        canvas = Canvas(self, bd=0, highlightthickness=0,
                        yscrollcommand=vscrollbar.set)
        canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
        vscrollbar.config(command=canvas.yview)

        # reset the view
        canvas.xview_moveto(0)
        canvas.yview_moveto(0)

        # create a frame inside the canvas which will be scrolled with it
        self.interior = interior = Frame(canvas)
        interior_id = canvas.create_window(0, 0, window=interior,
                                           anchor=NW)

        # track changes to the canvas and frame width and sync them,
        # also updating the scrollbar
        def _configure_interior(event):
            # update the scrollbars to match the size of the inner frame
            size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
            canvas.config(scrollregion="0 0 %s %s" % size)
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the canvas's width to fit the inner frame
                canvas.config(width=interior.winfo_reqwidth())
        interior.bind('<Configure>', _configure_interior)

        def _configure_canvas(event):
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the inner frame's width to fill the canvas
                canvas.itemconfigure(interior_id, width=canvas.winfo_width())
        canvas.bind('<Configure>', _configure_canvas)


if __name__ == "__main__":

    class SampleApp(Tk):
        def __init__(self, *args, **kwargs):
            root = Tk.__init__(self, *args, **kwargs)


            self.frame = VerticalScrolledFrame(root)
            self.frame.pack()
            self.label = Label(text="Shrink the window to activate the scrollbar.")
            self.label.pack()
            buttons = []
            for i in range(10):
                buttons.append(Button(self.frame.interior, text="Button " + str(i)))
                buttons[-1].pack()

    app = SampleApp()
    app.mainloop()
Run Code Online (Sandbox Code Playgroud)

它还没有鼠标滚轮绑定到滚动条,但它是可能的.但是,使用滚轮滚动可能会有点颠簸.

编辑:

到1)
恕我直言滚动帧在Tkinter有点棘手,似乎没有做很多.似乎没有优雅的方法来做到这一点.
您的代码的一个问题是您必须手动设置画布大小 - 这就是我发布的示例代码解决的问题.

2)
你在谈论数据功能?地方也适合我.(一般我更喜欢网格).

3)
嗯,它将窗口定位在画布上.

我注意到的一件事是你的例子默认处理鼠标滚轮滚动,而我发布的那个没有.将来有必要看一下.

  • @ChrisAung:这个解决方案的好处是它有一个可重用的类 `VerticalScrolledFrame`,你可以用它来替代任何 `Frame`。使用解决方案中的代码,您需要为您希望能够滚动的每个“框架”重写所有代码。使用此代码,它几乎是“Frame”的替代品。所以不要因为行数而不愿意使用它。如果您只需要一个可滚动框架,他的解决方案是更多的代码。如果你需要两个,两种技术都需要等量的代码,而且他的更易于维护(更少冗余。) (2认同)

Bry*_*ley 23

我做得对吗?有更好/更聪明的方法来实现此代码给我的输出吗?

一般来说,是的,你做得对.除了画布之外,Tkinter没有本机可滚动容器.正如您所看到的,设置起来并不困难.如您的示例所示,它只需要5或6行代码即可使其工作 - 具体取决于您如何计算行数.

为什么我必须使用网格方法?(我尝试过放置方法,但画布上没有出现任何标签?)

你问为什么必须使用网格.不需要使用网格.可以使用地方,网格和包装.简单来说,有些更自然地适合特定类型的问题.在这种情况下,看起来你正在创建一个实际的网格 - 标签的行和列 - 所以网格是自然的选择.

在画布上创建窗口时使用anchor ='nw'有什么特别之处?

锚点告诉您窗口的哪个部分位于您给出的坐标处.默认情况下,窗口的中心将放置在坐标处.对于上面的代码,您希望左上角("西北")角位于坐标处.


Mik*_* T. 10

请看我的课程是一个可滚动的框架.它的垂直滚动条也绑定到<Mousewheel>事件.所以,你所要做的就是创建一个框架,用你喜欢的方式填充小部件,然后让这个框架成为我的框架ScrolledWindow.scrollwindow.如果有什么不清楚,请随时询问.

很多来自@ Brayan Oakley的回答都接近这个问题

class ScrolledWindow(tk.Frame):
    """
    1. Master widget gets scrollbars and a canvas. Scrollbars are connected 
    to canvas scrollregion.

    2. self.scrollwindow is created and inserted into canvas

    Usage Guideline:
    Assign any widgets as children of <ScrolledWindow instance>.scrollwindow
    to get them inserted into canvas

    __init__(self, parent, canv_w = 400, canv_h = 400, *args, **kwargs)
    docstring:
    Parent = master of scrolled window
    canv_w - width of canvas
    canv_h - height of canvas

    """


    def __init__(self, parent, canv_w = 400, canv_h = 400, *args, **kwargs):
        """Parent = master of scrolled window
        canv_w - width of canvas
        canv_h - height of canvas

       """
        super().__init__(parent, *args, **kwargs)

        self.parent = parent

        # creating a scrollbars
        self.xscrlbr = ttk.Scrollbar(self.parent, orient = 'horizontal')
        self.xscrlbr.grid(column = 0, row = 1, sticky = 'ew', columnspan = 2)         
        self.yscrlbr = ttk.Scrollbar(self.parent)
        self.yscrlbr.grid(column = 1, row = 0, sticky = 'ns')         
        # creating a canvas
        self.canv = tk.Canvas(self.parent)
        self.canv.config(relief = 'flat',
                         width = 10,
                         heigh = 10, bd = 2)
        # placing a canvas into frame
        self.canv.grid(column = 0, row = 0, sticky = 'nsew')
        # accociating scrollbar comands to canvas scroling
        self.xscrlbr.config(command = self.canv.xview)
        self.yscrlbr.config(command = self.canv.yview)

        # creating a frame to inserto to canvas
        self.scrollwindow = ttk.Frame(self.parent)

        self.canv.create_window(0, 0, window = self.scrollwindow, anchor = 'nw')

        self.canv.config(xscrollcommand = self.xscrlbr.set,
                         yscrollcommand = self.yscrlbr.set,
                         scrollregion = (0, 0, 100, 100))

        self.yscrlbr.lift(self.scrollwindow)        
        self.xscrlbr.lift(self.scrollwindow)
        self.scrollwindow.bind('<Configure>', self._configure_window)  
        self.scrollwindow.bind('<Enter>', self._bound_to_mousewheel)
        self.scrollwindow.bind('<Leave>', self._unbound_to_mousewheel)

        return

    def _bound_to_mousewheel(self, event):
        self.canv.bind_all("<MouseWheel>", self._on_mousewheel)   

    def _unbound_to_mousewheel(self, event):
        self.canv.unbind_all("<MouseWheel>") 

    def _on_mousewheel(self, event):
        self.canv.yview_scroll(int(-1*(event.delta/120)), "units")  

    def _configure_window(self, event):
        # update the scrollbars to match the size of the inner frame
        size = (self.scrollwindow.winfo_reqwidth(), self.scrollwindow.winfo_reqheight())
        self.canv.config(scrollregion='0 0 %s %s' % size)
        if self.scrollwindow.winfo_reqwidth() != self.canv.winfo_width():
            # update the canvas's width to fit the inner frame
            self.canv.config(width = self.scrollwindow.winfo_reqwidth())
        if self.scrollwindow.winfo_reqheight() != self.canv.winfo_height():
            # update the canvas's width to fit the inner frame
            self.canv.config(height = self.scrollwindow.winfo_reqheight())
Run Code Online (Sandbox Code Playgroud)

  • 框架随其内部的小部件一起增长,并且从不滚动。调整窗口大小不会调整画布的大小。 (4认同)
  • 小错误,你的最后一行应该是 `self.canv.config(height= ...)` (2认同)