代码之家  ›  专栏  ›  技术社区  ›  ColorfulYoshi

如何在Tkinter中只打开一种格式的文件

  •  0
  • ColorfulYoshi  · 技术社区  · 2 年前

    所以我想做一些类似记事本的东西,但我想打开 .txt 仅限文件。
    我不知道怎么做,也没有在网上找到任何东西。
    我的代码:

    import tkinter as tk # Import Tkinter
    from tkinter.filedialog import askopenfilename # Import dialog box (to ask for file directory)
    
    window = tk.Tk() # Create window
    window.wm_geometry("600x600") # Set geometry
    window.title("Test") # Rename
    
    class FileOperations: # Class for file operations
    
        def open_file(self, path): # File open function
            file_opened = open(path, "r") # Open
            file_contentment = file_opened.read() # Read
            return file_contentment # Return
    
    file_ops = FileOperations() # Assign variable to a class
    
    newfile_button = tk.Button(master=window, text="New", width=10, height=1, font=("Arial", 10)) # Not done yet, do not mention it
    newfile_button.grid(column=0, row=0) # Grid
    
    savefile_button = tk.Button(master=window, text="Save File", width=10, height=1, font=("Arial", 10)) # Not done yet, do not mention it
    savefile_button.grid(column=1, row=0) # Grid
    
    openfile_button = tk.Button(master=window, text="Open File", width=10, height=1, font=("Arial", 10),
                                command=lambda: file_ops.open_file(askopenfilename())) # Fix it?
    openfile_button.grid(column=2, row=0) # Grid
    
    tk.mainloop() # Mainloop
    

    任何建议都很有帮助。

    1 回复  |  直到 2 年前
        1
  •  1
  •   CN-LanBao    2 年前

    只需使用param filetypes 这样地

    askopenfilename(filetypes=(("Text Files", "*.txt"),))