macOS tkinter:askopenfilename的文件类型如何工作

问题描述 投票:0回答:1

我的问题

  1. [如果将filetypes设置如下,则它们处于灰色模式,因此无法在Filter中的filetypes之间切换(请参见下图)
filetypes = [ 
            ("Python File", "*.py"), 
            ("Image File", "*.bmp"),
            ("All Files", "*.*")
            ]
  1. 尽管默认文件类型为.py,但由于.bmp高亮显示,因此我们也可以在窗口中选择test.bmp。这意味着可以同时激活filetypes.py.bmp。此Filter行为正常吗?

我期望我们可以从filetypes的集合中选择一种类型,这些选项应该是mutually exclusive,即,如果在Python File (.py)中选择Filter,则只有.py文件会可在窗口中选择。

enter image description here

这里是代码:

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")]


![enter image description here

  • 仅保留("All Files", "*.*")。这就是我的期望,*.*终于生效。
filetypes = [("All Files", "*.*")]

enter image description here

系统信息

  • macOS Catalina
  • python 3.7.5
  • TkVersion 8.6
python-3.x macos tkinter file-type
1个回答
0
投票

我在相同的macOS上遇到了相同的问题。 :(

© www.soinside.com 2019 - 2024. All rights reserved.