繁体   English   中英

在Tkinter中创建ScrolledText小部件类

[英]Creating a ScrolledText widget class in Tkinter

我试图在TKinter中创建一个Scrolled Text小部件类,该类允许在实例创建时指定宽度和高度。 我有一个Scrolled Text类,该类可以起作用,并且在创建Scrolled Text实例时允许我在小部件中输入文本,但是我不知道如何在创建实例时指定小部件的宽度和高度。 此滚动文本小部件的大部分直接来自Lutz的Programming Python文本。 到目前为止,这是我的“滚动文本”类:

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

我要创建的实例看起来像这样,这使我可以指定“滚动文本”窗口小部件的宽度和高度:

ScrolledText(text='aa', width=25, height=5).mainloop()

我希望能够更改在实例创建过程中指定的宽度和高度,以获取不同大小的“滚动文本”窗口小部件,但是无论我指定什么宽度和高度,我总是得到相同大小的“滚动文本”窗口小部件。 如果有人对如何修改此Scrolled Text类有任何建议,以允许输入可变的高度和宽度,我将不胜感激。 谢谢乔治

您似乎没有使用width和height参数。 您需要将值传递到创建文本窗口小部件的位置。 有两种方法可以做到这一点。 您可以将widthheight参数另存为对象属性,也可以将其传递到makewidgets方法中。

这是将它们另存为对象属性的示例:

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)
        ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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