通过 pythons .insert() 方法将文本插入驻留在另一个文件中的 tkinter Text() 小部件

Insert text via pythons .insert() method to a tkinter Text() widget that resides in another file

我有 2 个文件。

app.py 是包含所有 tk 相关内容的 tkinter 文件。

app_functions.py 只是函数。

所以当我 运行 app.py 并且当我点击一个 tk 按钮时,命令在 app_functions.py 文件中执行一个函数,但是在那个函数中它需要 .insert() 文本到 app.py 文件中的 tk Text() 小部件。但是我收到错误。

这里是错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\Phil-\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
  File "c:\Users\Phil-\python_main\gsc script building app\app.py", line 30, in <lambda>
    button1 = Button(content_frame1, text="INIT_Function", command=lambda: app_functions.display_raw_gsc_code("INIT_FUNCTION_START", "INIT_FUNCTION_END"))
  File "c:\Users\Phil-\python_main\gsc script building app\app_functions.py", line 45, in display_raw_gsc_code
    content_frame2_text_area.insert(tk.END, line)
NameError: name 'content_frame2_text_area' is not defined

当我在 app_functions.py 文件中导入 app.py 文件,然后在 运行 中导入 app.py 文件时,它会加载 gui,然后一旦我单击按钮然后它再次打开 tk gui,这样就不好了。

所以简而言之,当我成功导入函数时,我能够从 tk 按钮执行另一个文件中的函数。 但是在那个函数中,它需要 .insert() 文本到另一个文件中的 tk 小部件,但这对我来说不起作用,所有在线示例都包括在与 tk 按钮和 tk 相同的文件中具有该功能和 tk Text() 小部件并确定它可以工作,但我想将 tk 内容和功能保存在单独的文件中。

我要完成的基本概念:

  1. 单击 app.py 中的按钮执行 app_functions.py
  2. 中名为 display_raw_gsc_code 的函数
  3. display_raw_gsc_code app_functions.py 中的函数完成其工作,然后将文本插入 app.py
  4. 中的 Text() 小部件
  5. Text() app.py 中的小部件显示接收到的文本。

TK 中的按钮(app.py)文件

button1 = Button(content_frame1, text="INIT_Function", command=lambda: app_functions.display_raw_gsc_code("INIT_FUNCTION_START", "INIT_FUNCTION_END"))

函数中的函数(app_functions.py)文件

def display_raw_gsc_code(start, end):
    """ grab gsc 'example code' from raw file & display in output(frame2) area """
    f = open(join(dirname(realpath(__file__)), "raw_gsc_code.txt"), 'rt')
    with f as file:
        copy = False
        for line in file:
            if line.strip() == start:
                copy = True
                continue
            elif line.strip() == end:
                break
            elif copy:
                content_frame2_text_area.insert(tk.END, line)
    f.close()

TK(app.py) 文件中的文本小部件

content_frame2_text_area = Text(content_frame2, relief="ridge", bd=2) #GROOVE
content_frame2_text_area.grid(column=2, row=1, sticky="ns", padx=5, pady=5)

您需要将 content_frame2_text_area 作为 display_raw_gsc_code() 的参数传递。 – acw1668 3 月 16 日 0:49