tkinter 询问目录()
Posted
技术标签:
【中文标题】tkinter 询问目录()【英文标题】:tkinter askdirectory() 【发布时间】:2017-02-11 19:35:22 【问题描述】:基于上次更新的文件移动。仅使用按钮 3,我在目录末尾缺少一个斜杠。这会导致路径与我要移动的文本文件合并:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1482, in __call__
return self.func(*args)
File "C:/Python34/check2.py", line 30, in fileMove
if os.stat(src).st_mtime > now - 1 * 86400:
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:/Somewhere/filenametextfile'
import shutil, sys, time, os
import tkinter as tk
from tkinter import *
import tkinter.filedialog
root = Tk()
def fileMove():
sourcePath = filedialog.askdirectory()
receivePath = filedialog.askdirectory()
source = sourcePath
dest = receivePath
files = os.listdir(source)
now = time.time()
for f in files:
src = (source) +f
dst = (dest) +f
if os.stat(src).st_mtime > now - 1 * 86400:
if os.path.isfile(src):
shutil.move(src, dst)
print("File move is Alright, Alright, Alright")
所有显示按钮
def button_press():
if one:
x = 1
display.configure(text=x)
if two:
x = 2
display.configure(text=x)
if three:
x = 3
display.configure(text=x)
display = LabelFrame(root, bg="red", , )
display.pack()
one = Button(root, text="1", , ,command=fromSource)
one.pack(side="left")
two = Button(root, text="2", , , command=toReceive)
two.pack(side="left")
three = Button(root, text="3", , ,command=fileMove)
three.pack(side="left")
root.mainloop()
【问题讨论】:
您是否尝试过简单地添加斜线?还是使用os.path.join
?
【参考方案1】:
您应该使用os.path.join
方法来连接路径,而不是简单的+ 字符串连接。这样代码可以在多个平台(Windows/Mac/Linux)上运行
例如
from tkinter import Tk
from tkinter import filedialog
import os
root = Tk()
root.withdraw()
current_directory = filedialog.askdirectory()
file_name = "test.txt"
file_path = os.path.join(current_directory,file_name)
print(file_path)
【讨论】:
以上是关于tkinter 询问目录()的主要内容,如果未能解决你的问题,请参考以下文章