我尝试创建一个函数,当用户在inputField中键入文件名并单击保存按钮时。可以使用新的条目名称复制mdb文件,并且该消息将显示source => destination。转到相同的文件名,它将显示文件已存在。但是当我键入新文件名时,单击“保存”按钮。它总是表明文件已经存在。我无法弄清楚我的代码出了什么问题。
from tkinter.ttk import *
class View(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.winfo_toplevel().title("Save File")
self.grid()
self.init_view()
def init_view(self):
self.inputText = Label(self)
self.inputText["text"] = "Input Serial ID"
self.inputText.grid(row=0, column=0, sticky=N + E)
self.inputField = Entry(self)
self.inputField["width"] = 20
self.inputField.grid(row=0, column=1, sticky=N + W)
self.save = Button(self)
self.save["text"] = "Save"
self.save.grid(row=1, column=1, sticky=N + W)
self.displayText = Label(self)
self.displayText["text"] = "Status:Idle"
self.displayText.grid(row=3, column=0, columnspan=7, sticky=N)
if __name__ == '__main__':
root = Tk()
app = View(master=root)
root.mainloop()
import shutil
import sys
from datetime import datetime
from Save_Server_View import View
from tkinter import Tk
year = datetime.now().year
month = datetime.now().month
src = r"HIDE FOR PRI"
dir = os.path.dirname(os.path.realpath('__file__'))
dst = os.path.join(dir, ".\\data\\" + str(year) + "\\" + str(month))
# Controller
class Controller:
def __init__(self):
self.app = View(master=Tk())
self.app.save["command"] = self.save_method
self.app.mainloop()
# Copy & Rename File
def save_method(self):
for root, dirs, files in os.walk(src):
for filename in files:
if not os.path.exists(os.path.join(dst)):
message = (os.path.join(dst)), "not found"
self.app.displayText["text"] = message
else:
first_src_file_path = os.path.join(src, '', filename)
new_dst_file_path = os.path.join(dst, '', self.app.inputField.get() + '.mdb')
new_dst_file_name = os.path.basename(new_dst_file_path)
try:
if not os.path.exists(os.path.join(dst, new_dst_file_name)):
shutil.copy(first_src_file_path, new_dst_file_path)
message = 'source={} => destination={}'.format(src, dst)
self.app.displayText["text"] = message
except:
message = "Unexpected error:", sys.exc_info()[0]
self.app.displayText["text"] = message
else:
self.app.displayText["text"] = 'File has existed.'
# Execute
if __name__ == '__main__':
app = Controller()
我将文件复制到目标文件路径时,可以正确显示该消息。文件名是新的,然后显示'source = {} => destination = {}'。format(src,dst)'。如果目标文件路径中的文件名相同,它将显示“文件已存在。”
单击src
按钮时更新save
内容。只需在for
功能的save_method
循环之前添加以下行即可。
src = self.app.inputField.get()