I am trying to create a Scrolled Text widget class in TKinter that allows for the width and height to be specified at the time of instance creation. I have a Scrolled Text class that functions and will allow me to input the text in the widget when the Scrolled Text instance is created but I cannot figure out how to specify the widget width and height at instance creation. The majority of this Scrolled Text widget is directly from the Programming Python text by Lutz. Here is my Scrolled Text class so far:
class ScrolledText(Frame):
def __init__(self, parent=None, text='', file=None, width='', height=''):
Frame.__init__(self, parent)
self.pack(expand=YES, fill=BOTH) # make me expandable
self.makewidgets()
self.settext(text, file)
def makewidgets(self, width='', height=''):
sbar = Scrollbar(self)
#text = Text(self, relief=SUNKEN)
text = Text(self, relief=SUNKEN)
sbar.config(command=text.yview) # xlink sbar and text
text.config(yscrollcommand=sbar.set) # move one moves other
sbar.pack(side=RIGHT, fill=Y) # pack first=clip last
text.pack(side=LEFT, expand=YES, fill=BOTH) # text clipped first
self.text = text
def settext(self, text='', file=None):
if file:
text = open(file, 'r').read()
self.text.delete('1.0', END) # delete current text
self.text.insert('1.0', text) # add at line 1, col 0
self.text.mark_set(INSERT, '1.0') # set insert cursor
self.text.focus() # save user a click
def gettext(self): # returns a string
return self.text.get('1.0', END+'-1c') # first through last
What I want is to create an instance with something that looks like this, which allows me to specify the width and height of the Scrolled Text widget:
ScrolledText(text='aa', width=25, height=5).mainloop()
I want to be able to change the width and height specified during instance creation to get a different size Scrolled Text widget, but no matter what width and height I specify I always get the same size Scrolled Text widget. If anyone has any suggestions about how to modify this Scrolled Text class to allow for variable height and width input I would appreciate the help. Thanks, George
It doesn't look like you're using the width and height parameters. You need to pass the values to where you are creating the text widget. There are a couple ways to do this. You can save the width
and height
parameters as object attributes, or you can pass them into the makewidgets
method.
Here's an example of saving them as object attributes:
class ScrolledText(...):
def __init__(..., width='', height=''):
...
self.width = width
self.height = height
...
self.makewidgets()
def makewidgets(...):
...
text = Text(self, relief=SUNKEN, width=self.width, height=self.height)
...
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.