gpt4 book ai didi

Python 程序不记得变量

转载 作者:行者123 更新时间:2023-11-30 22:15:54 25 4
gpt4 key购买 nike

我正在制作一个程序,用户可以上传 .csv 文件,然后显示内容,然后操作该文件,然后将操作的文件作为电子邮件的附件发送。

我的问题是,python 没有记忆起 SortingCSV 和 UploadAction 函数中的“fname”。所以我无法对显示的 .csv 文件内容执行任何操作。

这是我收到的错误:

NameError: name 'fname' is not defined

def load_file(self):
#Upload a CSV file and display its contents
fname = askopenfilename(filetypes=(("CSV files", "*.csv"),
("HTML files", "*.html;*.htm"),
("All files", "*.*") ))
print(fname)
print('The file has been uploaded, contents are displayed below')

import csv

with open(fname) as f:
reader = csv.reader(f)
for row in reader:
print(" ".join(row))

def SortingCSV(self):
#Allows user to switch the contents of the file to the desired ings
print(fname)
print("Tkinter is easy to use!")

def UploadAction(self):
#Allows user to send the converted file to website

import smtplib

content = 'Here is your completed file'
attach = (fname.csv)
mail = smtplib.SMTP('smtp.gmail.com',587)
mail.ehlo()
mail.starttls()
mail.login('[insert email]','[insert password]')

mail.sendmail('[insert email]','[insert recipient]',content)

mail.close()
print("The file has been sent to your inbox")

if __name__ == "__main__":
MyFrame().mainloop()

最佳答案

global fname 添加为使用该变量的所有函数的第一行。这将使 fname 成为全局可见的变量。不过,全局变量是邪恶的。更好的解决方案是将所有 GUI 功能打包到一个类中。

关于Python 程序不记得变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50146327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com