![](/img/trans.png)
[英]How to obtain the path to the directory of the frontmost Windows Explorer window using Python?
[英]Tkinter - way to open a directory window in Windows Explorer
我一直在研究 Tkinter,最近制作了一个小程序来监视文件夹并检查里面有多少文件。
我想创建在 Windows Explorer 中打开文件夹的按钮,但我找不到任何相关信息。
有人有任何想法吗?
干杯,乔恩
感谢您的快速响应,我已经尝试过类似的方法,但我可能做错了什么。 这是我的代码:
def open():
os.system("explorer C:\\ folder dir")
label1 = Button(self, text="Pre TC", fg="red", font=("Ariel", 9, "bold"), command=open)
感谢大家的帮助,这是您的答案的组合对这个问题有所帮助!
仍然不是 100% 关于我所做的工作的原因,但我添加了 self 作为 open() 的参数,所以 open(self) 并添加为命令 self.open。 所以我的问题中编辑后的代码如下所示:
def open(self):
os.system("start C:/folder dir/")
button1= Button(self, text="Pre TC", fg="red", font=("Ariel", 9, "bold"), command=self.open)
(也更改了按钮的名称)
如果有人知道为什么必须存在 self 论点,或者可以将我指向更多信息的方向,我们将不胜感激。
干杯! 乔恩
您可以使用终端命令来执行此操作并制作一个按钮来调用此功能。 Windows 中的示例:
from tkinter import *
from tkinter.ttk import *
import os
# opening any folder
def openFolder():
path='C:'
command = 'explorer.exe ' + path
os.system(command)
root = Tk()
root.geometry('100x100')
btn = Button(root, text = 'Click me !',command = openFolder)
btn.pack(side = 'top')
root.mainloop()
其他有趣的终端命令:
import os
# opening files
file = 'test.md'
command = 'start ' + file
os.system(command)
# opening current folder
command = 'explorer.exe .'
os.system(command)
# opening any folder
path='C:'
command = 'explorer.exe ' + path
os.system(command)
使用命令
您不能在标签项目上使用命令选项。 试着把它变成一个按钮,它应该可以工作!
当您调用在相同类名下定义的函数时,必须使用 self ,其中 label1 或 button1 是一个对象。 否则,由于找不到该函数,您会收到 Tkinter 回调异常。
这就是为什么将 open 重命名为 self.open 起作用的原因
我注意到的一件事是路径对斜杠或反斜杠敏感。 “C:/folder”不适用于 os.system。 它只是从一些默认的 Documents 文件夹开始。 “C:\文件夹”有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.