1

テキストボックスを使用して、Python シェルからの出力を Tkinter GUI にリダイレクトしたいと考えています。

たとえば、私のゲームでインベントリをクリックすると、Python シェルに物資が表示されます。GUIテキストボックス内に表示させたいです。

どうすればこれを行うことができますか?

4

1 に答える 1

0

次のようなテキストボックスのハンドラーを作成できます。

class textbox_handler:
  def __init__(self, text):
    self.data = []
    self.text = text #text is your tk text widget.
  def write(self, s):
    self.data.append(s)
  def print_out(self):
    for line in data:
        self.text.insert('end',line)

次に、メイン関数で次のようにします。

import sys
def main():
  handler = textbox_handler(text1)
  sys.stdout = handler
  print "sample text."
  print "sample text #2."
  print "another sample text."
  #or you can use without setting sys.stdout
  print >>handler, "yet another sample text."

各 print ステートメントは、handler オブジェクトの write メソッドを呼び出します。これらの文字列は、handler.data から簡単に取得できます。

于 2012-06-16T20:44:05.340 に答える