保存功能没有在 python 3.8.5 中弹出 window 并且也没有显示任何错误,这是什么问题?

save function not popping the window in python 3.8.5 and also not showing any error, what's the problem?

我想知道我的 python 版本是 3.8.5 的代码有什么问题.........我想要记事本中的保存文件选项

    text_url = " "
    def save_file(event = None):
       global text_url
       try:
          if text_url:
             content = str(text_editor.get(1.0,tk.END))
             with open(text_url,"w",encoding="utf-8") as for_read:
                for_read.write(content)
          else:
             text_url=filedialog.asksaveasfile(mode = "w",defaultextension="txt",filetypes=(("Text file","*.txt"),("All files","*.*")))
             conrent2 = text_editor.get(1.0,tk.END)
             text_url.write(content2)
             text_url.close()
       except:
             return

file.add_command(label="Save",image = save_icon,compound=tk.LEFT,accelerator="Ctrl+S",command=save_file)

这是我的全部代码,可以帮助您详细理解

  1. 导入部分
#import tkinter

import tkinter as tk
from tkinter import ttk
from tkinter import font,colorchooser,filedialog,messagebox
from tkinter.filedialog import asksaveasfile
import os

#window formation
main_application = tk.Tk()
main_application.geometry("1200x800")
main_application.title("Speak with Me")

main_menu = tk.Menu()

为文件菜单分配图标

#File menu icons
new_icon = tk.PhotoImage(file = "icon/new.png")
open_icon = tk.PhotoImage(file = "icon/open.png")
save_icon = tk.PhotoImage(file = "icon/save.png")
save_as_icon = tk.PhotoImage(file = "icon/saveas.png")
exit_icon = tk.PhotoImage(file = "icon/exit.png")

#Edit menu icons
copy_icon = tk.PhotoImage(file = "icon/copy.png")
paste_icon = tk.PhotoImage(file = "icon/paste.png")
cut_icon = tk.PhotoImage(file = "icon/cut.png")
clear_all_icon = tk.PhotoImage(file = "icon/clearall.png")
find_icon = tk.PhotoImage(file = "icon/find.png")

#View menu icons
toolbar_icon = tk.PhotoImage(file = "icon/toolbar.png")
statusbar_icon = tk.PhotoImage(file = "icon/statusbar.png")

#theme menu icons
lightdefault_icon = tk.PhotoImage(file = "icon/lightdefault.png")
lightplus_theme = tk.PhotoImage(file = "icon/lightplus.png")
dark_theme = tk.PhotoImage(file = "icon/dark.png")
red_theme = tk.PhotoImage(file = "icon/red.png")
monokai_theme = tk.PhotoImage(file = "icon/monokai.png")
nightblue_theme = tk.PhotoImage(file = "icon/nightblue.png")

制作菜单

#making menubar
file = tk.Menu(main_menu,tearoff=False)
main_menu.add_cascade(label = "File",menu=file)

edit = tk.Menu(main_menu,tearoff=False)
main_menu.add_cascade(label = "Edit",menu=edit)

view = tk.Menu(main_menu,tearoff=False)
main_menu.add_cascade(label = "View",menu=view)

color_theme = tk.Menu(main_menu,tearoff=False)
main_menu.add_cascade(label = "Theme",menu=color_theme)

#creating label
tool_bar_label = ttk.Label(main_application)
tool_bar_label.pack(side=tk.TOP,fill=tk.X)
#Font family
font_tuple=tk.font.families()
font_family=tk.StringVar()
font_box=ttk.Combobox(tool_bar_label,width=30,textvariable=font_family,state="readonly")
font_box["values"]=font_tuple
font_box.current(font_tuple.index("Arial"))
font_box.grid(row=0,column=0,padx=5,pady=5)
#Size selection
size_variable=tk.IntVar()
font_size=ttk.Combobox(tool_bar_label,width=20,textvariable=size_variable,state="readonly")
font_size["values"]=tuple(range(8,100,2))
font_size.current(4)
font_size.grid(row=0,column=1,padx=5,pady=5)
#creating Bold,Italic,Underline,colorpicker,paragraph alignments
#bold
bold_icon = tk.PhotoImage(file = "icon/bold.png")
bold_button=ttk.Button(tool_bar_label,image=bold_icon)
bold_button.grid(row=0,column=2,padx=5,pady=5)
#italic
italic_icon = tk.PhotoImage(file = "icon/italic.png")
italic_button=ttk.Button(tool_bar_label,image=italic_icon)
italic_button.grid(row=0,column=3,padx=5,pady=5)
#underline
u_icon = tk.PhotoImage(file = "icon/underline.png")
u_button=ttk.Button(tool_bar_label,image=u_icon)
u_button.grid(row=0,column=4,padx=5,pady=5)
#colorpicker
cp_icon = tk.PhotoImage(file = "icon/colorwheel.png")
cp_button=ttk.Button(tool_bar_label,image=cp_icon)
cp_button.grid(row=0,column=5,padx=5,pady=5)
#left
L_icon = tk.PhotoImage(file = "icon/leftpara.png")
L_button=ttk.Button(tool_bar_label,image=L_icon)
L_button.grid(row=0,column=6,padx=5,pady=5)
#right
C_icon = tk.PhotoImage(file = "icon/centerpara.png")
C_button=ttk.Button(tool_bar_label,image=C_icon)
C_button.grid(row=0,column=7,padx=5,pady=5)
#center
R_icon = tk.PhotoImage(file = "icon/rightpara.png")
R_button=ttk.Button(tool_bar_label,image=R_icon)
R_button.grid(row=0,column=8,padx=5,pady=5)

#textBOX
text_editor=tk.Text(main_application)
text_editor.config(wrap="word",relief=tk.FLAT)

scroll_bar=tk.Scrollbar(main_application)
text_editor.focus_set()
scroll_bar.pack(side=tk.RIGHT,fill=tk.Y)
text_editor.pack(fill=tk.BOTH,expand=True)
scroll_bar.config(command=text_editor.yview)
text_editor.config(yscrollcommand=scroll_bar.set)

#making status bar
status_bars=ttk.Label(main_application,text="Status Bar")
status_bars.pack(side=tk.BOTTOM)

将功能分配给菜单栏

text_change=False

def change_word(event=None):
    global text_change
    if text_editor.edit_modified():
        text_change=True
        word = len(text_editor.get(1.0,"end-1c").split())
        character=len(text_editor.get(1.0,"end-1c").replace(" ",""))
        status_bars.config(text = "character {} word {}".format(character,word))
    text_editor.edit_modified(False)

text_editor.bind("<<Modified>>",change_word)

#working of Font assign
font_now="Arial"
font_size_now=16

def change_font(main_application):
    global font_now
    font_now=font_family.get()
    text_editor.config(font=(font_now,font_size_now))

def change_size(main_application):
    global font_size_now
    font_size_now=size_variable.get()
    text_editor.config(font=(font_now,font_size_now))

font_box.bind("<<ComboboxSelected>>",change_font)
font_size.bind("<<ComboboxSelected>>",change_size)

#working of BOLD assign

def bold_fun():
    text_get = tk.font.Font(font=text_editor["font"])
    if text_get.actual()["weight"]=='normal':
        text_editor.config(font=(font_now,font_size_now,"bold"))
    if text_get.actual()["weight"]=='bold':
        text_editor.config(font=(font_now,font_size_now,"normal"))

bold_button.configure(command=bold_fun)

#working of Italic assign

def Italic_fun():
    text_get = tk.font.Font(font=text_editor["font"])
    if text_get.actual()["slant"]=='roman':
        text_editor.config(font=(font_now,font_size_now,"italic"))
    if text_get.actual()["slant"]=='italic':
        text_editor.config(font=(font_now,font_size_now,"roman"))

italic_button.configure(command=Italic_fun)

#working of Underline assign

def u_fun():
    text_get = tk.font.Font(font=text_editor["font"])
    if text_get.actual()["underline"]==0:
        text_editor.config(font=(font_now,font_size_now,"underline"))
    if text_get.actual()["underline"]==1:
        text_editor.config(font=(font_now,font_size_now,"normal"))

u_button.configure(command=u_fun)

#working of colorwheel assign

def color_choose_fun():
    color_var=tk.colorchooser.askcolor()
    text_editor.configure(fg=color_var[1])

cp_button.configure(command=color_choose_fun)

#working for text alignment LEFT,CENTER,RIGHT

def L_fun():
    text_get_all=text_editor.get(1.0,"end")
    text_editor.tag_config("left",justify=tk.LEFT)
    text_editor.delete(1.0,tk.END)
    text_editor.insert(tk.INSERT,text_get_all,"left")

L_button.configure(command=L_fun)

def C_fun():
    text_get_all=text_editor.get(1.0,"end")
    text_editor.tag_config("center",justify=tk.CENTER)
    text_editor.delete(1.0,tk.END)
    text_editor.insert(tk.INSERT,text_get_all,"center")

C_button.configure(command=C_fun)

def R_fun():
    text_get_all=text_editor.get(1.0,"end")
    text_editor.tag_config("right",justify=tk.RIGHT)
    text_editor.delete(1.0,tk.END)
    text_editor.insert(tk.INSERT,text_get_all,"right")

R_button.configure(command=R_fun)




#assign icons and sub-menus
#file

#File Options creating
#NEW FILE
text_url = " "

def new_file(event=None):
    global text_url
    text_url = " "
    text_editor.delete(1.0,tk.END)

file.add_command(label="New",image = new_icon,compound=tk.LEFT,accelerator="Ctrl+N",command=new_file)

def open_file(event=None):
    global text_url
    text_url = filedialog.askopenfilename(initialdir=os.getcwd(),title="select file",filetypes=(("Text file","*.txt"),("All files","*.*")))
    try:
        with open(text_url,"r") as for_read:
            text_editor.delete(1.0,tk.END)
            text_editor.insert(1.0,for_read.read())
    except FileNotFoundError:
        return
    except:
        return
    main_application.title(os.path.basename(text_url))
    
file.add_command(label="Open",image = open_icon,compound=tk.LEFT,accelerator="Ctrl+O",command=open_file)

def save_file(event = None):
    global text_url
    try:
        if text_url:
            content = str(text_editor.get(1.0,tk.END))
            with open(text_url,"w",encoding="utf-8") as for_read:
                for_read.write(content)
        else:
            text_url=filedialog.asksaveasfile(mode = "w",defaultextension="txt",filetypes=(("Text file","*.txt"),("All files","*.*")))
            conrent2 = text_editor.get(1.0,tk.END)
            text_url.write(content2)
            text_url.close()
    except:
        return

file.add_command(label="Save",image = save_icon,compound=tk.LEFT,accelerator="Ctrl+S",command=save_file)
file.add_command(label="Save As",image = save_as_icon,compound=tk.LEFT,accelerator="Ctrl+Alt+S")
file.add_command(label="Exit",image = exit_icon,compound=tk.LEFT,accelerator="Ctrl+")
#edit
edit.add_command(label="Copy",image = copy_icon,compound=tk.LEFT,accelerator="Ctrl+C")
edit.add_command(label="Paste",image = paste_icon,compound=tk.LEFT,accelerator="Ctrl+V")
edit.add_command(label="Cut",image = cut_icon,compound=tk.LEFT,accelerator="Ctrl+X")
edit.add_command(label="Clea All",image = clear_all_icon,compound=tk.LEFT,accelerator="Ctrl+Alt+X")
edit.add_command(label="Find",image = find_icon,compound=tk.LEFT,accelerator="Ctrl+F")
#view
view.add_checkbutton(label="Tool Bar",onvalue=True,offvalue=0,image = toolbar_icon,compound=tk.LEFT)
view.add_checkbutton(label="Status Bar",onvalue=True,offvalue=0,image = statusbar_icon,compound=tk.LEFT)
#theme
color_icons=(lightdefault_icon,lightplus_theme,dark_theme,red_theme,monokai_theme,nightblue_theme)

color_dict = {
        'Light Default' : ('#000000',"#ffffff"),
        'Light Plus'  : ('#474747','#e0e0e0'),
        'Dark' : ('#c4c4c4','#2d2d2d'),
        'Red'  : ('#2d2d2d','#ffe8e8'),
        'Monokai' : ('#d3b774','#474747'),
        'Night Blue'  : ('#ededed','#6b9dc2')

    }

count = 0
for key in color_dict:
    color_theme.add_radiobutton(label=key,image=color_icons[count],compound=tk.LEFT)
    count+=1
    
 
main_application.config(menu=main_menu)


main_application.mainloop()

我想知道如何解决这个问题或需要其他类型的编码

首先,你不应该将 text_url 初始化为 " ",因为 if text_url: 将被评估为 True。因此,您将尝试打开文件 " " 进行写入,这会引发异常。但是您的代码将忽略异常,因此您什么也看不到。

其次你不应该使用 asksaveasfile() 因为 text_url 将被分配一个打开的 File 对象。然后下次调用 save_file() 时,if text_url: 将被评估为 True,因此 with open(text_url, "w", ...) 将引发异常,因为 text_url 不是文件名。但是异常再次被忽略,没有任何反应。

下面修改new_file()save_file()

text_url = ""  # initialize as "" instead of " "

def new_file(event=None):
    global text_url
    text_url = ""  # initialize as "" instead of " "
    text_editor.delete(1.0, tk.END)

...

def save_file(event=None):
    global text_url
    try:
        if text_url == "":
            text_url = filedialog.asksaveasfilename(defaultextension="txt",
                                                    filetypes=(("Text file","*.txt"),("All files","*.*")))
        if text_url:
            content = text_editor.get(1.0, tk.END)
            with open(text_url, "w", encoding="utf-8") as file:
                file.write(content)
    except Exception as e:
        print(e)  # better print out exception