我的问题
filetypes
在 Filter
(见下图)因为它们处于灰色模式,如果设置 filetypes
如下 filetypes = [
("Python File", "*.py"),
("Image File", "*.bmp"),
("All Files", "*.*")
]
.py
我们也可以选择.bmp
在窗口自test.bmp
突出显示。这意味着 filetypes
, .py
和 .bmp
, 可以同时激活。这是Filter
行为正常吗? 我期望的是我们可以从
filetypes
的集合中挑出一种类型。这些选项应该是 mutually exclusive
,即如果选择 Python File (.py)
在 Filter
,然后只有 .py
文件将可以在窗口中选择。这是代码:
from tkinter import *
from tkinter import ttk
from tkinter.filedialog import askopenfilename
# from tkinter.filedialog import askopenfile
# from tkinter.filedialog import askopenfilenames
filetypes = [
("Python File", "*.py"),
("Image File", "*.bmp"),
("All Files", "*.*")
]
def OpenFile():
p = askopenfilename(initialdir="../",
filetypes =filetypes,
title = "Choose a file.")
print ("Path to File: \n", p)
#Using try in case user types in unknown file
# or closes without choosing a file.
# try:
# with open(p, 'r') as f:
# print("Content of File:\n", f.read())
# except:
# print("Error!")
root = Tk()
root.title( "File Opener")
label = ttk.Label(root,
text ="File Read Test!",
foreground="red",
font=("Helvetica", 16))
label.pack()
menu = Menu(root)
root.geometry("300x200")
root.config(menu=menu)
file = Menu(menu)
file.add_command(label = 'Open', command = OpenFile)
file.add_command(label = 'Exit', command = root.quit)
menu.add_cascade(label = 'File', menu = file)
root.mainloop()
更多例子
("All Files", "*.*")
?仍然无法在文件类型和两者之间切换 .py
和 .bmp
是活跃的。并且所有其他文件类型都超出了先前设置的范围。 filetypes = [
("Python File", "*.py"),
("Image File", "*.bmp")]
("All Files", "*.*")
.这就是我所期望的*.*
终于生效了。 filetypes = [("All Files", "*.*")]
系统信息
最佳答案
在我的系统上:
我发现这个简单的解决方法让我得到了想要的行为:
filetypes = [
("All Files", "*.*"),
("Python File", "*.py"),
("Image File", "*.bmp"),
]
也就是说,通过让它想出 "All Files"
最初,然后在打开的对话框中切换到其他类型适本地过滤文件。
关于python - macOS tkinter : how does filetypes of askopenfilename work,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58799432/