为我的实用程序做了一个基本的Python,这是我学习如何编码的第一个项目,我知道它很混乱,这就是我在这里的原因。
在这个program中,“Upload XML File”下面的按钮调用“browseXMLFiles”函数,“Upload Duplex File”下面的按钮调用“browseLOGFiles”函数(这两个函数的内容是相同的,只是它们查找的文件类型不同),然后“Remove Duplicates”按钮调用“remove_invoices”函数。
很明显,前两个函数会打开一个tkinter文件对话框,您可以在其中分别找到XML和XML文件。
找到文件后,路径被存储在一个全局变量中,这样就可以在“remove_invoices”函数中使用它。
例如,this是两个“browseX”函数全部包含的变量,而全局变量是我试图摆脱的变量:
def browseLOGFiles():
logname = filedialog.askopenfilename(initialdir = "/Logs",
title = "Select a File",
filetypes = (("Text files",
"*.txt*"),
("all files",
"*.*")))
global new_log_name
new_log_name = logname.split('/', -1)
logButton.configure(text=new_log_name[-1])
字符串
我目前的问题:
我试图清理全局变量污染,所以我想让我的remove_invoices函数接受“browseX”函数的返回。我试着用函数本身替换全局变量(因为它是now returns the path:
def browseLOGFiles():
logname = filedialog.askopenfilename(initialdir = "/Logs",
title = "Select a File",
filetypes = (("Text files",
"*.txt*"),
("all files",
"*.*")))
new_log_name = logname.split('/', -1)
logButton.configure(text=new_log_name[-1])
return new_log_name
型
而不是使用全局变量)。最终发生的是,当单击“删除重复项”按钮时,而不是使用函数的返回项,它在remove_invoices函数中再次调用该函数,让您再次选择文件路径。
我应该如何重构我的代码,以便我可以:
1.防止全球变量污染
1.获取前两个函数的结果,而无需在remove_invoices函数中再次调用它们:
功能:
def remove_invoices():
try:
error_file = open(browseLOGFiles(), "r") #This is closed later, I promise
except Exception as e:
if e == "name 'logname' is not defined":
statusLabel.configure(text="Please upload a LOG(.txt) file.")
try:
global tree
tree = ET.parse(browseXMLFiles)
print(f'Opened {browseXMLFiles}. Parsing.')
except:
print(f"Can't find file the specified XML File. Was the filename typed exactly, including the extension?")
型
1条答案
按热度按时间knpiaxh11#
我早就想明白了,但我还是把它放在一边吧。
我的解决方案基本上是将任何与打开文件相关的内容移动到它自己的类FileCloud中。我手头上没有确切的代码,但我将在这里复制它:
字符串
我没有返回值,而是将self.value赋给日志名。现在,如果我需要访问当前日志名,我可以示例化我的类并调用该值:
型
这解决了我的问题与全球气候污染,并允许我访问这些变量的任何地方,我需要他们。
这是在我对类做了很多实验之前,但是如果你是Python新手,或者是整个编码,我保证它们比看起来更容易理解。它们一开始很令人生畏,但会让你的生活变得更容易。