【问题标题】:Python GUI - Insert text to text boxPython GUI - 将文本插入文本框
【发布时间】:2013-08-12 02:54:07
【问题描述】:

我刚接触 Python GUI,正在测试不同的东西,因为这似乎有助于我更轻松地学习(反复试验)。我正在尝试的一件事是插入来自不同班级的消息。老实说,我不知道我会用这个做什么,但我只是为了尝试而尝试。

# Hello World
# Displays "Hello World!" in a text box.

from tkinter import *

class myClass(object):
    def myMethod():
        print("Hello World!")

class Application(Frame):
    """ GUI application which can reveal the secret of longevity. """
    def __init__ (self, master):
        super(Application, self).__init__(master)
        self.grid()
        self.createWidgets()

    def createWidgets(self):
        # Create a text box
        self.txtBox = Text(self, width = 300, height = 300, wrap = WORD)
        self.txtBox.grid(row = 0, column = 0, sticky = W)

        # display message
        message = myClass.myMethod
        self.txtBox.insert(0.0, message)

# main
root = Tk()
root.title("My Title")
root.geometry("500x500")

app = Application(root)

root.mainloop()

当我运行 .py 文件时,我得到了 GUI,然后是一个显示 <function myClass.myMethod at 0x0000000002A1C6A8> 的框 - 如果我没记错的话,这意味着 myMethod 存储在内存中的位置。

所以我使用 message = myClass.myMethod() 认为这会输出 "Hello World!" - 相反我得到一个错误。起初它类似于对象。init 不接受参数或类似的东西(抱歉,因为我无法重新创建错误) - 现在我收到tkinter.TclError: wrong # args: should be "43128536.43105360 insert index chars ?tagList chars tagList...?

这可能有“Hello World!”吗?从另一个类,在 GUI 文本框中打印?

另外,当我查看代码时,我很好奇。 app = Application(root) 的目的是什么?当我没有它时,我会得到一个空白的 GUI。但是,除了将其设置为等于Application(root) 之外,我没有看到它实际上调用 app 来执行任何操作。

【问题讨论】:

    标签: python user-interface python-3.x tkinter


    【解决方案1】:

    您正在将函数本身添加到文本框。调用函数并使用它的返回值。

        message = myClass.myMethod()
        self.txtBox.insert(1.0, message)
    

    myClass 需要修改。返回字符串而不是打印它。

    class myClass(object):
        def myMethod():
            return "Hello World!"
    

    【讨论】:

    • 哇,谢谢!请问,为什么return 在这种情况下有效,而不是print?我仍然对何时应该使用它们感到困惑。
    • @mccdlibby,print 不返回。它只是打印到终端。
    • 0.0 是无效索引。文本小部件行从 1 开始编号,而不是从零开始。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-06
    • 2015-11-22
    • 2011-01-08
    • 2017-01-10
    • 2020-06-25
    • 2015-03-10
    相关资源
    最近更新 更多