Tkinter - 在 Windows 资源管理器中打开目录 window 的方法
Tkinter - way to open a directory window in Windows Explorer
我一直在研究 Tkinter,最近做了一个小程序来监视文件夹并检查里面有多少文件。
我想创建在 Windows 资源管理器中打开文件夹的按钮,但我找不到任何相关信息。
有人有什么想法吗?
干杯,
乔恩
感谢您的快速回复,我已经尝试过类似的方法,但我可能做错了什么。这是我的代码:
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 参数必须存在,或者可以指出更多信息的方向,我们将不胜感激。
干杯!
乔恩
self 必须在调用以相同 class 名称定义的函数时使用,其中 label1 或 button1 是一个对象。否则你会得到 Tkinter 回调异常,因为找不到函数。
这就是将 open 重命名为 self.open 的原因
您可以使用终端命令来执行此操作,并创建一个按钮来调用此函数。 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)
使用命令
我注意到的一件事是路径对斜杠或反斜杠敏感。 “C:/文件夹”不适用于 os.system。它只是从一些默认的 Documents 文件夹开始。 “C:\文件夹”有效。
我一直在研究 Tkinter,最近做了一个小程序来监视文件夹并检查里面有多少文件。
我想创建在 Windows 资源管理器中打开文件夹的按钮,但我找不到任何相关信息。
有人有什么想法吗?
干杯, 乔恩
感谢您的快速回复,我已经尝试过类似的方法,但我可能做错了什么。这是我的代码:
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 参数必须存在,或者可以指出更多信息的方向,我们将不胜感激。
干杯! 乔恩
self 必须在调用以相同 class 名称定义的函数时使用,其中 label1 或 button1 是一个对象。否则你会得到 Tkinter 回调异常,因为找不到函数。
这就是将 open 重命名为 self.open 的原因
您可以使用终端命令来执行此操作,并创建一个按钮来调用此函数。 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)
使用命令
我注意到的一件事是路径对斜杠或反斜杠敏感。 “C:/文件夹”不适用于 os.system。它只是从一些默认的 Documents 文件夹开始。 “C:\文件夹”有效。