![](/img/trans.png)
[英]How do i use an 'if' on a checkbutton in tkinter. (python 3.8)
[英]How do i access a function from another file in python with Tkinter. I can't find any solution to my specific problem
我是 python 和 Tkinter 的新手,所以我可能在这里犯了一个简单的错误,但这是一个学校项目,因此,我没有太多时间学习所有内容。 无论如何,我正在使用 Tkinter 制作一个应用程序,我想将代码拆分为不同的 python 文件,一个文件中的函数并从主文件访问它们。 3 天以来我一直试图找出问题所在,这看起来是一个非常简单的错误,但我不知道它是什么。
Tkinter 回调 Traceback(最近一次调用最后一次)中的异常:文件“C:\Users\mcdd1\AppData\Local\Programs\Python\Python39\lib\ tkinter_init _.py”,第 1884 行,调用中返回 self.func( *args) 文件 "d:\mcdd1\Desktop\UNI\Switch-Frames-Template-master\textfunc.py",第 22 行,在 open_file my_text.delete("1.0", END) NameError: name 'my_text' is not定义
这些是我使用过的代码:主文件是 mainnav.py,
from textfunc import open_file
toolbar_frame = Frame(frame2, bg="blue")
toolbar_frame.pack(fill=X)
my_frame = Frame(frame2)
my_frame.pack(pady=5)
my_text = Text(my_frame, width=97, height=25, font=("Helvetica", 16), selectbackground="yellow", selectforeground="black", undo=True, wrap="none")
my_text.pack()
open_button = Button(toolbar_frame, text="Open", command=open_file)
open_button.grid(row=0, column=0, sticky=W, padx=5, pady=5)
具有函数 textfunc.py 的文件(在同一目录中)
global open_status_name
open_status_name = False
global selected
selected = False
def open_file():
my_text.delete("1.0", END)
text_file = filedialog.askopenfilename(initialdir="", title="Open File", filetypes=(("Text Files", "*.txt"), ("All Files", "*.*")))
if text_file:
global open_status_name
open_status_name = text_file
text_file = open(text_file, 'r')
stuff = text_file.read()
my_text.insert(END, stuff)
text_file.close()
这些只是我认为解决问题所需的代码片段。 任何帮助将不胜感激!
my_text变量未在mainnav.py文件中定义。 如果你想访问它,你可以将它作为参数传递给open_file() function:
主导航.py:
from textfunc import open_file
toolbar_frame = Frame(frame2, bg="blue")
toolbar_frame.pack(fill=X)
my_frame = Frame(frame2)
my_frame.pack(pady=5)
my_text = Text(my_frame, width=97, height=25, font=("Helvetica", 16), selectbackground="yellow", selectforeground="black", undo=True, wrap="none")
my_text.pack()
open_button = Button(toolbar_frame, text="Open", command=lambda: open_file(my_text))
open_button.grid(row=0, column=0, sticky=W, padx=5, pady=5)
文本函数.py:
def open_file(my_text):
my_text.delete("1.0", END)
text_file = filedialog.askopenfilename(initialdir="", title="Open File", filetypes=(("Text Files", "*.txt"), ("All Files", "*.*")))
if text_file:
global open_status_name
open_status_name = text_file
text_file = open(text_file, 'r')
stuff = text_file.read()
my_text.insert(END, stuff)
text_file.close()
注意:您需要使用 lambda 将参数传递给 Button 的命令。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.