Вставить текст в TextBuffer через функцию - python - PullRequest
0 голосов
/ 05 марта 2012

У меня следующая проблема:

Как мне вставить текст в мой текстовый буфер?

Interface.py

class MainWindow:
    def __init__(self):

        # Build our Interface from the XML/Glade file
        gladefile = "MainWindow.glade"
        try:
            self.builder = Gtk.Builder()
            self.builder.add_from_file(gladefile)
        except:
            print("Failed to load Glade file: %s" % gladefile)

        # Connect signals
        self.builder.connect_signals(self)

        # Get the widgets
        self.window = self.builder.get_object("MainWindow")

        ...

        # TextViews
        self.TextViewCommandInput = self.builder.get_object("TextViewCommandInput")
        self.TextViewCommandOutput = self.builder.get_object("TextViewCommandOutput")

        ...

def DrawCommandView(output):
    TextBufferCommandInput = MainWindow.TextViewCommandInput.get_buffer()
    TextBufferCommandInput.insert_at_cursor(output + "\n")

И импортировать «DrawCommandView» в файл

Commands.py

from Interface import MainWindow, DrawCommandView

output = "Hello World"
DrawCommandView(output)

if __name__ == "__main__":
    StartMainWindow = MainWindow()
    StartMainWindow.main()

Но я продолжаю получать эту ошибку:

Traceback (most recent call last):
  File "/home/user/Dokumente/Workspace/project/Commands.py", line 5, in <module>
    DrawACommandView(output)
  File "/home/user/Dokumente/Workspace/project/Interface.py", line 182, in DrawCommandView

    TextBufferCommandInput = MainWindow.TextViewCommandInput.get_buffer()
AttributeError: class MainWindow has no attribute 'self'

Спасибо за вашу помощь!

Greetz

Ответы [ 2 ]

0 голосов
/ 04 августа 2012

Я полагаю, вам нужно set_text() вместо get_buffer().

См. Документацию set_text().

Затем позже get_buffer() может получитьтекст, вставленный set_text().

Вот несколько методов, которые я использовал, чтобы иметь общий способ использования буфера.

def GetTextBuffer(self):
    self.text_buffer = self.text_edit.get_buffer()
    # self.text_edit is a Gtk.TextView() instance
    # to get the text buffer from TextView
    # buffer.get_text( start iterator, end iterator, bool )
    # the third argument set to True = Include hidden characters
    # third argument set to False = Don't include hidden characters
    # hidden characters would be visual formatting markup and such
    return self.text_buffer.get_text(
        self.text_buffer.get_start_iter(),
        self.text_buffer.get_end_iter(), 
        False)

def SetTextBuffer(self, to_buffer):
    # to_buffer is user input from widgets, or default values set at run time.
    text_buffer = self.text_edit.get_buffer()
    text_buffer.set_text(to_buffer)
0 голосов
/ 05 марта 2012

Когда вы говорите TextBufferCommandInput = MainWindow.TextViewCommandInput.get_buffer() Вы запрашиваете атрибут класса в MainWindow с именем TextViewCommandInput. У вас нет атрибута класса TextViewCommandInput, у вас есть атрибут экземпляра TextViewCommandInput. Вам нужно передать экземпляр MainWindow в DrawCommandView, чтобы перейти к TextViewCommandInput.

...