简体   繁体   中英

Horizontal Scrollbar not working in Python TKinter Frame

I have a canvas (for ttk.Frame not having xview , yview methods) holding frames inside of it, which I want to browse horizontally, as they are in the same row. Found some tutorials, and while they were dealing with different combination of widgets, I followed them, and tried to apply them to my problem, but with no success. I do see a scrollbar, but it doesn't do or respond to anything.

class App:
    def __init__(self,db):
        self.db = db
        self.root = tkinter.Tk()                             
        self.masterframe = ttk.Frame(self.root)
        self.masterframe.grid()

        self.mastercanvas = tkinter.Canvas(self.masterframe)
        self.mastercanvas.grid()

        self.scrollbar = ttk.Scrollbar(self.masterframe,orient="horizontal",
            command = self.mastercanvas.xview)

        self.scrollbar.grid()
        self.mastercanvas.configure(xscrollcommand=self.scrollbar.set)

        for i,e in enumerate(self.db.elements):
            xf = XFrame(self,e)
            xf.grid(row=0,column=i,sticky="n")

Edit:

class XFrame:
    def __init__(self,app,x):
        self.app = app
        self.x = x
        self.frame = ttk.Frame(self.app.mastercanvas)
        self.set_up() # this sets frame's padding and populates it with widgets   

Now, where ever I paste two lines of code here suggested* - at the end of the first init definition, or at the end of the second init definition - nothing new happens. I see my frames appearing as I intended them to appear - 3 of them. Part of the 4th. And an unfunctional scrollbar.

*

self.update_idletasks() # using self.root in first, self.app.root in second variant
self.mastercanvas.configure(scrollregion=self.mastercanvas.bbox("all")) 
# in second variant reffered to as self.app.mastercanvas ...

You've got to configure the scrollregion attribute of the canvas so that it knows how much of the virtual canvas you want to scroll. This should do it:

# create everything that will be inside the canvas
...

# next, cause the window to be drawn, so the frame will auto-size
self.update_idletasks() 

# now, tell the canvas to scroll everything that is inside it
self.mastercanvas.configure(scrollregion=self.mastercanvas.bbox("all"))

That being said, there's nothing in your canvas to be scrolled, and I'm not entirely sure what you were expecting to be in the canvas. If you are wanting to scroll through the instances of XFrame , they need to be children of some other frame, and that other frame needs to be an object on the canvas.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM