Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7679799
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T17:57:45+00:00 2026-05-31T17:57:45+00:00

So I’ve got a custom widget that inherits from frame and contains a canvas

  • 0

So I’ve got a custom widget that inherits from frame and contains a canvas and a scrollbar, and a custom widget that also inherits from frame that I want to dynamically add to the canvas, resizing the scrollregion as necessary. Here’s my code:

class MessageItem(Frame):
"""A message to be contained inside a scrollableContainer"""

def __init__(self, message, **kwds):
    Frame.__init__(self, **kwds)
    self.text = Label(self, text = message)
    self.text.grid(column = 0, row = 0, sticky = N+S+E+W)

class scrollableContainer(Frame):
"""A scrollable container that can contain a number of messages"""

def initContents(self):
    """Initializes a scrollbar, and a canvas that will contain all the items"""

    #the canvas that will contain all our items
    self.canv = Canvas(self)
    self.canv.grid(column = 0, row = 0, sticky = N+S+W)
    #force Tkinter to draw the canvas
    self.canv.update_idletasks()
    #use the values from the canvas being drawn to determine the size of the scroll region
    #note that currently, since the canvas contains nothing, the scroll region will be the same as 
    #the size of the canvas
    geometry = self.canv.winfo_geometry()
    xsize, ysize, xpos, ypos = parse_geometry_string(geometry) 
    self.canv['scrollregion'] = (0, 0, xsize, ysize) 

    #the scrollbar for that canvas
    self.vscroll = Scrollbar(self, orient = VERTICAL, command = self.canv.yview )
    self.vscroll.grid(column = 1, row = 0, sticky = N+S+E)

    self.canv["yscrollcommand"] = self.vscroll.set

def __init__(self, **kwds):
    Frame.__init__(self, **kwds)

    #initialize the widget's contents
    self.grid(sticky = N+S+E+W)
    self.pack()
    self.initContents()

    #initialize the list of contents so we can append to it
    self.contents = []

def addMessage(self, message):
    #Add the message to the list of contents
    self.contents.append(MessageItem(message))
    #Add the message to the grid
    self.contents[(len(self.contents) - 1)].grid(column = 0, row = (len(self.contents) - 1))
    #set the new scrollable region for the canvas
    scrollregionlist = self.canv['scrollregion'].split()
    oldRegion = int(scrollregionlist[3])
    newRegion = oldRegion + parse_geometry_string(self.contents[
        (len(self.contents) - 1)].winfo_geometry())[3]
    self.canv['scrollregion'] = (int(scrollregionlist[0]), int(scrollregionlist[1]),
        int(scrollregionlist[2]), newRegion)

The problem I’m experiencing is that self.canv[‘scrollregion’] appears to disappear outside of init. In the addMessage method, in the line:

 scrollregionlist = self.canv['scrollregion'].split()

The scrollregion property on self.canv returns an empty string, which I can verify by putting a

 print self.canv['scrollregion']

immediately before that line

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T17:57:46+00:00Added an answer on May 31, 2026 at 5:57 pm

    You sure a Text widget wouldn’t suffice here?

    anyway,

    from Tkinter import *
    
    
    class MessageItem(Frame):
        """A message to be contained inside a scrollableContainer"""
    
        def __init__(self, master, message, **kwds):
            Frame.__init__(self, master, **kwds)
            self.grid_rowconfigure(0, weight=1)
            self.grid_columnconfigure(0, weight=1)
            self.text = Label(self, text=message, anchor='w', bg='gold')
            self.text.grid(row=0, column=0, sticky='nsew')
    
    class scrollableContainer(Frame):
        """A scrollable container that can contain a number of messages"""
    
        def __init__(self, master, **kwargs):
            Frame.__init__(self, master, **kwargs) #holds canvas & scrollbars
            self.grid_rowconfigure(0, weight=1)
            self.grid_columnconfigure(0, weight=1)
    
            self.canv = Canvas(self, bd=0, highlightthickness=0)
            self.hScroll = Scrollbar(self, orient='horizontal',
                                     command=self.canv.xview)
            self.hScroll.grid(row=1, column=0, sticky='we')
            self.vScroll = Scrollbar(self, orient='vertical',
                                     command=self.canv.yview)
            self.vScroll.grid(row=0, column=1, sticky='ns')
            self.canv.grid(row=0, column=0, sticky='nsew')        
            self.canv.configure(xscrollcommand=self.hScroll.set,
                                yscrollcommand=self.vScroll.set)
    
            self.frm = Frame(self.canv, bd=2, bg='green') #holds messages
            self.frm.grid_columnconfigure(0, weight=1)
    
            self.canv.create_window(0, 0, window=self.frm, anchor='nw', tags='inner')
    
            self.messages = []
            for i in range(20):
                m = MessageItem(self.frm, 'Something Profound', bd=2, bg='black')
                m.grid(row=i, column=0, sticky='nsew', padx=2, pady=2)
                self.messages.append(m)
    
            self.update_layout()        
            self.canv.bind('<Configure>', self.on_configure)
    
        def update_layout(self):
            self.frm.update_idletasks()
            self.canv.configure(scrollregion=self.canv.bbox('all'))
            self.canv.yview('moveto','1.0')
            self.size = self.frm.grid_size()
    
        def on_configure(self, event):
            w,h = event.width, event.height
            natural = self.frm.winfo_reqwidth()
            self.canv.itemconfigure('inner', width= w if w>natural else natural)
            self.canv.configure(scrollregion=self.canv.bbox('all'))
    
        def add_message(self, message):
            m = MessageItem(self.frm, message, bd=2, bg='red')
            m.grid(row=self.size[1], column=0, padx=2, pady=2, sticky='we')
            self.messages.append(m)
            self.update_layout()
    
    
    root = Tk()
    root.grid_rowconfigure(0, weight=1)
    root.grid_columnconfigure(0, weight=1)
    sc = scrollableContainer(root, bd=2, bg='black')
    sc.grid(row=0, column=0, sticky='nsew')
    
    def new_message():
        test = 'Something Profane'
        sc.add_message(test)
    
    b = Button(root, text='New Message', command=new_message)
    b.grid(row=1, column=0, sticky='we')
    
    root.mainloop()
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I've got a string that has curly quotes in it. I'd like to replace
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I want to construct a data frame in an Rcpp function, but when I
I want to count how many characters a certain string has in PHP, but
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
For some reason, after submitting a string like this Jack’s Spindle from a text
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I want use html5's new tag to play a wav file (currently only supported

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.