【发布时间】:2023-01-21 10:05:41
【问题描述】:
我有 2 个文件。
app.py 是包含所有 tk 相关内容的 tkinter 文件。
app_functions.py 只是函数。
因此,当我运行 app.py 并单击 tk 按钮时,该命令会在 app_functions.py 文件中执行一个函数,但在该函数中,它需要将 .insert() 文本发送到 @987654327 中的 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 Text() 小部件相同的文件中具有该功能和确定它有效,但我想将 tk 的东西和功能保存在单独的文件中。
我试图完成的基本概念:
- 单击 app.py 中的按钮,它会在
app_functions.py中执行名为display_raw_gsc_code的函数 -
display_raw_gsc_codeapp_functions.py中的函数完成它的工作,然后将文本插入app.py中的Text()小部件@ -
app.py中的Text()小部件显示接收到的文本。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()的参数传递。 -
那马上就奏效了。太感谢了 :)
-
我如何将您的答案标记为最佳答案/将此问题标记为已解决?
-
您可以自己写一个答案并接受它以将此问题标记为已解决。