【问题标题】:Python / Tkinter : How to access a ScrolledText widget from within a method?Python / Tkinter:如何从方法中访问 ScrolledText 小部件?
【发布时间】:2016-02-08 22:49:31
【问题描述】:

我想在 Python / Tkinter 中创建一个简单、可重用的文本输出窗口类,其功能与控制台输出类似,但窗口更好。

到目前为止,我设法直接从构造函数中将文本写入ScrolledText 小部件,但这不是我想要的。

我想创建一个print 或println 方法,让我可以随时从主过程中添加文本。

如何从 print 方法中“调用”文本小部件?

我的主要程序:

    from gui.simpleio import Textwindow 

    a = Textwindow("This is my Textwindow !")
    a.print("I'd like to see a hello from the print method")
    a.stxt.INSERT("but nothing happens")

我在 gui 包中的 Textwindow 类 (simpleio.py):

    from tkinter import Tk, Frame, INSERT
    from tkinter import scrolledtext

    class Textwindow(Frame):

        def __init__(self , title):
            root = Tk()  
            stxt = scrolledtext.ScrolledText(root)
            stxt.pack()
            root.wm_title(title)
            stxt.insert(INSERT,"blah\nblabla\n")
            stxt.insert(INSERT,"yes\nno")
            root.mainloop()

        def print(self,text):
            #self.stxt.insert(INSERT,text)       
            pass

【问题讨论】:

  • 请不要用粗体表示所有内容,仅用于重要的事情。
  • Textwindow.print() 不起作用,因为 self.stxt 未在 Textwindow.__init__() 中定义。
  • 另外,TextWindow 的 __init__ 方法会调用 root.mainloop(),因此在主窗口被销毁之前不会执行以下 a.print 调用。
  • 看看my answer中的errorwindow.py模块到问题Writing to easygui textbox as function is running。

标签: python user-interface oop methods tkinter


【解决方案1】:

给你的 TextWindow 一个 write 方法,实例 a 成为一个打开的文件以供写入。这里是 Lib/idlelib/OutputWindow 的 OutputWindow.write 的简化版。

# Act as output file
def write(self, s):
    self.text.insert('insert', s)
    self.text.see('insert')
    self.text.update()
    return len(s)

添加后,print('Hello in TextWindow', file=a) 应该可以在 3.x 或 2.7 中使用 print_function 未来导入。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多