首页 > 解决方案 > 如何在 tkinter 的 filedialog 中获取当前文件类型

问题描述

如何在 tkinter 的 filedialog 中获取当前文件类型?

我想获得当前的文件类型来帮助我添加.gif.png在最后不是?例如:

if not new.path_save.endswith('.png') and path_save.currentfiletype == "png":
    new.path_save += ".png"

帮助。

编辑:整个代码:

from tkinter import *
import os, playsound, PIL, tkinter, webbrowser
from tkinter import ttk, filedialog

big_font = ("arial",20)
mid_font = ("arial",15)
small_font = ("arial",10)

class main:
    root = Tk()
    def __init__(self):
        main.root.title("Nitro Camp Image Editor")
        self.win_width = main.root.winfo_screenwidth()
        self.win_height = main.root.winfo_screenheight()
        #main.root.state('zoomed')
        main.root['background'] = "#242424"
        main.root.geometry(f"+{int(self.win_width/6)}+{int(self.win_height/6)}")
        main.root.minsize(800,600)

class new:
    path_save = ""
    def __init__(self):
        self.new_frm = Frame(main.root,bg="#303030",width=200,height=main.root.winfo_screenheight()+30)
        self.new_frm.place(x=15,y=15)
        
        ## Layout ##
        self.new_btn = Button(self.new_frm,text="New Image",bg="#303030",fg="white",activebackground="#78BDFA",activeforeground="white",
                                borderwidth=0,width=17,height=2,font = ("arial",15,"bold"), command= self.clicked
                                )
        self.new_btn.place(x=1,y=1)

        self.settings_btn = Button(self.new_frm,text="Settings",bg="#303030",fg="white",activebackground="#78BDFA",activeforeground="white",
                                borderwidth=0,width=18,height=2,font = ("arial",15,"normal")
                                )
        self.settings_btn.place(x=1,y=70)
    
    def clicked(self):
        # Frame #
        self.new_btn['state'] = DISABLED
        self.clicked_frm = Frame(main.root,bg="#303030",width=530,height=500)
        self.clicked_frm.place(x=240,y=50)

        ## Add Layout ##
        # Labels #
        Label(self.clicked_frm,text="Resolution: ",bg="#303030",fg="white",font=mid_font).place(x=5,y=5)
        Label(self.clicked_frm,text="  ↔️               ↕️   ",bg="#303030",fg="white",font=mid_font).place(x=5,y=40)
        Label(self.clicked_frm,text="Mode ‍ : ",bg="#303030",fg="white",font=mid_font).place(x=5,y=100)
        Label(self.clicked_frm,text="Bit Depth ‍ : ",bg="#303030",fg="white",font=mid_font).place(x=5,y=150)
        Label(self.clicked_frm,text="Color : ",bg="#303030",fg="white",font=mid_font).place(x=5,y=200)

        # Entries #
        self.x_ent = Entry(self.clicked_frm,width=6,borderwidth=0,bg="#262626",fg="#78BDFA",font=mid_font)
        self.x_ent.place(x=70,y=43)

        self.y_ent = Entry(self.clicked_frm,width=6,borderwidth=0,bg="#262626",fg="#78BDFA",font=mid_font)
        self.y_ent.place(x=200,y=43)

        self.bit_ent = Entry(self.clicked_frm,width=4,borderwidth=0,bg="#262626",fg="#78BDFA",font=mid_font)
        self.bit_ent.place(x=150,y=155)

        # OptionsMenu
        self.style = ttk.Style(self.clicked_frm)
        self.style.theme_use("clam")
        self.style.configure("TMenubutton", relief=FLAT, font=small_font, bd=0, highlightthickness=0,
        arrowcolor="white", foreground="white", background="#323232")

        self.style.map("TMenubutton",
        background=[('disabled', '#262626'),('pressed', "#303030"), ('active', '#262626')],
        foreground=[('disabled', "#707070"),('active', "white")])

        self.mode_options = ['1', 'L', 'LA', 'P', 'PA', 'RGB', 'RGBA', 'CMYK', 'YCbCr', 'LAB', 'HSV', 'I', 'F']
        self.str_mode = StringVar()
        self.mode = ttk.OptionMenu(self.clicked_frm, self.str_mode, self.mode_options[5], *self.mode_options)
        self.mode['menu'].configure(relief=FLAT, font=small_font,
                borderwidth=0, activeborderwidth=0,  activeforeground="white", background="#272727", foreground="white",
                activebackground= "#78BDFA", selectcolor="white")
        self.mode.place(x=120,y=100)

        self.color_options = ['white', 'black', 'red', 'blue', 'green', 'Transparency']
        self.str_color = StringVar()
        self.color = ttk.OptionMenu(self.clicked_frm, self.str_color, self.color_options[0], *self.color_options)
        self.color['menu'].configure(relief=FLAT, font=small_font,
                borderwidth=0, activeborderwidth=0,  activeforeground="white", background="#272727", foreground="white",
                activebackground= "#78BDFA", selectcolor="white")
        self.color.place(x=120,y=200)

        # Buttons
        self.docs_mode = Button(self.clicked_frm,text="Click me for info about mode and bit. (important) ",bg="#303030",fg="blue",
                                    activebackground="#303030", activeforeground="blue", font = ("arial",10,UNDERLINE), borderwidth=0, command= self.info_docs
        )
        self.docs_mode.place(x=10,y=73)

        # set Default values #
        self.x_ent.insert("end", "100")
        self.y_ent.insert("end", "100")
        self.bit_ent.insert("end", "16")

        # Path
        self.path_ent = Entry(self.clicked_frm,width=20,borderwidth=0,bg="#262626",fg="#78BDFA",font=mid_font)
        self.path_ent.place(x=120,y=250)
        self.broswer_btn = Button(self.clicked_frm,text="B",bg="#262626",fg="white",height=1,
                                    activebackground="#78BDFA", activeforeground="white", font = small_font, borderwidth=0, command= self.ask_save
        )
        self.broswer_btn.place(x=340,y=250,height=25)
    
    def info_docs(self):
        webbrowser.open('https://en.wikipedia.org/wiki/Color_depth')
    
    def ask_save(self):
        new.path_save = filedialog.asksaveasfilename(initialdir="/",title="Select the path to save the Image. ",filetypes=[("PNG", '*.png'),
                                                                                                                ("JPEG", '*.jpg'),("GIF", '*.gif'),
                                                                                                                ("ICON", '*.ico'),("BMP", '*.bmp'),
                                                                                                                ("IM", '*.im'),("JFIF", '*.jfif')],
        )
        # here Error #
        if not new.path_save.endswith('.png') and new.path_save['filetypes'] == ("PNG", '*.png'):
            new.path_save += ".png"

        

main()
new()
main.root.mainloop()

标签: pythontkinter

解决方案


您可以使用typevariable选项来获取选定的文件类型:

def ask_save(self):
    type_var = tk.StringVar()
    new.path_save = filedialog.asksaveasfilename(initialdir="/",
                                                 title="Select the path to save the Image. ",
                                                 filetypes=[("PNG", '*.png'),
                                                            ("JPEG", '*.jpg'),("GIF", '*.gif'),
                                                            ("ICON", '*.ico'),("BMP", '*.bmp'),
                                                            ("IM", '*.im'),("JFIF", '*.jfif')],
                                                 typevariable=type_var)
    if new.path_save:
        file_type = type_var.get()
        if not new.path_save.lower().endswith(".png") and file_type == "PNG":
            new.path_save += ".png"

推荐阅读