我已经将此内容重写为更多上下文,这是我希望程序执行的逻辑顺序
1通过按打开文件,它需要打开一个指定文件并将其放入文本小部件中(完成) 2通过按提取文件,它需要从指定的子树中提取某些内容(在xml文件中) 3将提取的数据导出到文本文件
但是让我们回到第2点,因为我尚未编写提取器(简单的部分),首先我需要引用我要编辑的文件,这就是我遇到问题的地方。里面提取它不能在openfile中访问vars,我不想再次重新打开文件。
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
import tkinter as tk
interface = tk.Tk()
interface.geometry("500x500")
interface.title("Text display")
def openfile():
filename = filedialog.askopenfilename()
print(filename)
file = open(filename)
txt = file.read()
print(txt)
T = tk.Text(interface, height=10, width=50)
T.insert(tk.END, txt)
T.grid(column=1, row=2)
return txt
def extract():
print(txt)
button = ttk.Button(interface, text="Open text File", command=openfile) # <------
button.grid(column=1, row=1)
buttonex = ttk.Button(interface, text="Extract subtitles", command=extract) # <------
buttonex.grid(column=2, row=1)
interface.mainloop()
NameError:未定义名称“ txt”(当我按提取时)
答案 0 :(得分:1)
正如最初问题的编辑显示,计划中的GUI一样,我建议将您的TK小部件移到tkinter文档中的接口类中。此外,如果您打算进行更复杂的操作,则应创建自己的类来保存数据。操纵它。
import tkinter as tk
class App(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.pack()
self.create_widgets()
def create_widgets(self):
# Create your buttons and connect them to the methods
self.button_load = tk.Button(self)
self.button_load["command"] = self.loadTextFromFile()
self.button_load["text"] = "Load Data"
self.button_load.gird(column=1, row=1)
self.buttonex = tk.Button(self)
self.buttonex["text"] = "Extract subtitles"
self.buttonex["command"] = self.extract()
self.buttonex.grid(column=2, row=1)
# Create the text widget
self.text_widget = tk.Text(self, height=10, width=50)
self.text_widget.grid(column=1, row=2)
def loadTextFromFile(self):
filename = filedialog.askopenfilename()
print(filename)
try:
file = open(filename)
txt = file.read()
file.close()
self.text_widget.insert(tk.END, txt)
except Exception:
# If anything went wrong, close the file before reraising
file.close()
raise
def extract(self):
# Now you have access to self.text_widget and it holds your read in text
do_something(self.text_widget)
# Maybe at the following functions to make your file importable without directly executing it. Could come in handy later on.
def run():
# create the application
myapp = App()
#
# here are method calls to the window manager class
#
myapp.master.title("My Do-Nothing Application")
myapp.master.maxsize(1000, 400)
# start the program
myapp.mainloop()
if __name__ == '__main__':
run()
有关更多示例,请参见tkinter文档:https://docs.python.org/3/library/tkinter.html
附加的if子句检查您的模块是否是主模块并执行run函数。如果您直接运行模块,则这将定义一个入口点;如果要将模块导入另一个模块,则可在导入时阻止函数的执行。可以在这里找到更详细的解释: What does if __name__ == "__main__": do?
----------旧答案--------------
正如注释中指出的那样,您需要以某种方式将局部变量返回给调用函数,以便能够在其他地方使用它们。这可以通过一个简单的return语句来实现:
def openfile():
""" It is the responsibility of the caller to close the return value """
filename = filedialog.askopenfilename()
print(filename)
try:
file = open(filename)
txt = file.read()
T = tk.Text(interface, height=10, width=50)
T.insert(tk.END, txt)
T.grid(column=1, row=2)
return file
except Exception:
# If anything went wrong, close the file before reraising
file.close()
raise
例如,将返回打开的文件ID以便进一步处理。例如:
def extract():
with openfile() as file:
txtex = file.read()
print (txtex)
如果您的目标是操纵文件内容并在以后读取,则需要将您的操纵保存回文件中,否则您的第二次阅读将看不到更改。不要忘记再次关闭文件。
答案 1 :(得分:-3)
您还可以使用全局变量使变量在函数外部可用:
{"status":true}
结果:
def a():
global x
x = "file"
a()
print(x)